text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Update so order by links are escaped
@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR'])) <table{!! $dg->buildAttributes() !!}> <thead> <tr> @foreach ($dg->columns as $column) <th{!! $column->buildAttributes() !!}> @if ($column->orderby) @if ($dg->onOrderby($column->orderby_field, 'asc')) <span class="glyphicon glyphicon-arrow-up"></span> @else <a href="{{ $dg->orderbyLink($column->orderby_field,'asc') }}"> <span class="glyphicon glyphicon-arrow-up"></span> </a> @endif @if ($dg->onOrderby($column->orderby_field, 'desc')) <span class="glyphicon glyphicon-arrow-down"></span> @else <a href="{{ $dg->orderbyLink($column->orderby_field,'desc') }}"> <span class="glyphicon glyphicon-arrow-down"></span> </a> @endif @endif {!! $column->label !!} </th> @endforeach </tr> </thead> <tbody> @foreach ($dg->rows as $row) <tr{!! $row->buildAttributes() !!}> @foreach ($row->cells as $cell) <td{!! $cell->buildAttributes() !!}>{!! $cell->value !!}</td> @endforeach </tr> @endforeach </tbody> </table> @if ($dg->havePagination()) <div class="pagination"> {!! $dg->links() !!} </div> @endif
@include('rapyd::toolbar', array('label'=>$label, 'buttons_right'=>$buttons['TR'])) <table{!! $dg->buildAttributes() !!}> <thead> <tr> @foreach ($dg->columns as $column) <th{!! $column->buildAttributes() !!}> @if ($column->orderby) @if ($dg->onOrderby($column->orderby_field, 'asc')) <span class="glyphicon glyphicon-arrow-up"></span> @else <a href="{!! $dg->orderbyLink($column->orderby_field,'asc') !!}"> <span class="glyphicon glyphicon-arrow-up"></span> </a> @endif @if ($dg->onOrderby($column->orderby_field, 'desc')) <span class="glyphicon glyphicon-arrow-down"></span> @else <a href="{!! $dg->orderbyLink($column->orderby_field,'desc') !!}"> <span class="glyphicon glyphicon-arrow-down"></span> </a> @endif @endif {!! $column->label !!} </th> @endforeach </tr> </thead> <tbody> @foreach ($dg->rows as $row) <tr{!! $row->buildAttributes() !!}> @foreach ($row->cells as $cell) <td{!! $cell->buildAttributes() !!}>{!! $cell->value !!}</td> @endforeach </tr> @endforeach </tbody> </table> @if ($dg->havePagination()) <div class="pagination"> {!! $dg->links() !!} </div> @endif
Add keys to query list
var React = require('react'); var actions = require('../actions'); var { Navigation } = require('react-router'); var QueryStore = require('../stores/query_store.js'); var QueryList = React.createClass({ mixins: [QueryStore.listenTo, Navigation], getInitialState() { return { queries: [] }; }, _onChange() { this.setState({ queries: QueryStore.all() }); }, chooseQuery(q) { this.props.chooseQuery(q); }, deleteQuery(q) { actions.deleteQuery(q.path); }, render() { return <div className='fill-navy-dark dark pad2'> {this.state.queries.map((q, i) => <div key={q.data.query + '-' + i} className='col12 clearfix contain pad0y'> <div className='col3 right pad1 fill-darken2'> <a onClick={this.chooseQuery.bind(this, q)} className='icon down'>{q.data.name}</a> </div> <div className='col9 contain small'> <pre className='truncate fill-dark unround'>{q.data.query}</pre> {false ? <a onClick={this.deleteQuery.bind(this, q)} className='icon trash pin-topright'></a> : ''} </div> </div>)} </div>; } }); module.exports = QueryList;
var React = require('react'); var actions = require('../actions'); var { Navigation } = require('react-router'); var QueryStore = require('../stores/query_store.js'); var QueryList = React.createClass({ mixins: [QueryStore.listenTo, Navigation], getInitialState() { return { queries: [] }; }, _onChange() { this.setState({ queries: QueryStore.all() }); }, chooseQuery(q) { this.props.chooseQuery(q); }, deleteQuery(q) { actions.deleteQuery(q.path); }, render() { return <div className='fill-navy-dark dark pad2'> {this.state.queries.map(q => <div className='col12 clearfix contain pad0y'> <div className='col3 right pad1 fill-darken2'> <a onClick={this.chooseQuery.bind(this, q)} className='icon down'>{q.data.name}</a> </div> <div className='col9 contain small'> <pre className='truncate fill-dark unround'>{q.data.query}</pre> {false ? <a onClick={this.deleteQuery.bind(this, q)} className='icon trash pin-topright'></a> : ''} </div> </div>)} </div>; } }); module.exports = QueryList;
Add docstrings to Gist integration tests @esacteksab would be so proud
# -*- coding: utf-8 -*- """Integration tests for methods implemented on Gist.""" from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): """Gist integration tests.""" def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): """Show that a user can iterate over the commits in a gist.""" cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): """Show that a user can iterate over the forks of a gist.""" cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
from .helper import IntegrationHelper import github3 class TestGist(IntegrationHelper): def test_comments(self): """Show that a user can iterate over the comments on a gist.""" cassette_name = self.cassette_name('comments') with self.recorder.use_cassette(cassette_name): gist = self.gh.gist(3342247) assert gist is not None for comment in gist.comments(): assert isinstance(comment, github3.gists.comment.GistComment) def test_iter_commits(self): cassette_name = self.cassette_name('commits') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_commits(): assert isinstance(commit, github3.gists.history.GistHistory) def test_iter_forks(self): cassette_name = self.cassette_name('forks') with self.recorder.use_cassette(cassette_name, preserve_exact_body_bytes=True): gist = self.gh.gist(1834570) assert gist is not None for commit in gist.iter_forks(): assert isinstance(commit, github3.gists.gist.Gist)
Use window.localStorage in all cases
/* global chrome, confirm */ var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0; function check (key) { chrome.storage.sync.get(key, function (resp) { console.log('comparing to cloud', key, resp); if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key] && confirm('Overwrite "' + utils.fileNameFromKey(key) + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.')) { console.log('Overwriting', key); window.localStorage.setItem(key, resp[key]); updateFiles(); } else { console.log('add to obj', obj, key); obj[key] = window.localStorage[key]; } done++; if (done >= count) { chrome.storage.sync.set(obj, function () { console.log('updated cloud files with: ', obj, this, arguments); }); } }); } for (var y in window.localStorage) { console.log('checking', y); obj[y] = window.localStorage.getItem(y); if (y.indexOf(utils.getCacheFilePrefix()) !== 0) { continue; } count++; check(y); } }; } module.exports = StorageHandler;
/* global chrome, confirm, localStorage */ var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0; function check (key) { chrome.storage.sync.get(key, function (resp) { console.log('comparing to cloud', key, resp); if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key] && confirm('Overwrite "' + utils.fileNameFromKey(key) + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.')) { console.log('Overwriting', key); localStorage.setItem(key, resp[key]); updateFiles(); } else { console.log('add to obj', obj, key); obj[key] = localStorage[key]; } done++; if (done >= count) { chrome.storage.sync.set(obj, function () { console.log('updated cloud files with: ', obj, this, arguments); }); } }); } for (var y in window.localStorage) { console.log('checking', y); obj[y] = window.localStorage.getItem(y); if (y.indexOf(utils.getCacheFilePrefix()) !== 0) { continue; } count++; check(y); } }; } module.exports = StorageHandler;
Set h1 to null if no headings are present
package bamboo.task; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.regex.Pattern; public class HeadingContentHandler extends DefaultHandler { private static Pattern WHITESPACE_RE = Pattern.compile("\\s+"); private StringBuilder text = new StringBuilder(); private int depth = 0; private boolean sawAnyHeadings = false; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (depth > 0 || localName.equals("h1")) { depth++; sawAnyHeadings = true; if (text.length() != 0) { text.append(" "); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (depth > 0) { depth--; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (depth > 0) { text.append(ch, start, length); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (depth > 0) { text.append(ch, start, length); } } public String getText() { if (sawAnyHeadings) { return WHITESPACE_RE.matcher(text).replaceAll(" "); } else { return null; } } }
package bamboo.task; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.regex.Pattern; public class HeadingContentHandler extends DefaultHandler { private static Pattern WHITESPACE_RE = Pattern.compile("\\s+"); private StringBuilder text = new StringBuilder(); private int depth = 0; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (depth > 0 || localName.equals("h1")) { depth++; if (text.length() != 0) { text.append(" "); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (depth > 0) { depth--; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (depth > 0) { text.append(ch, start, length); } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (depth > 0) { text.append(ch, start, length); } } public String getText() { return WHITESPACE_RE.matcher(text).replaceAll(" "); } }
Change user name to something more practical. Signed-off-by: Se7enChat <[email protected]>
<?php namespace Se7enChat\Libraries\Web\Presenters; use Se7enChat\Boundaries\IndexOutputPort; use Se7enChat\Gateways\UserInterfaceGateway; class IndexPresenter implements IndexOutputPort { private $userInterface; private $lessUrl; private $cssUrl; public function __construct(UserInterfaceGateway $ui) { $this->lessUrl = __DIR__ . '/../../UserInterface/Less'; $this->cssUrl = CHAT_ROOT . 'Public/Styles'; $this->userInterface = $ui; } public function present(array $information) { $this->compileCss(); $this->userInterface->render('index', array( 'pageTitle' => 'Se7enChat', 'cssUrl' => PUBLIC_ROOT . '/Styles', 'javascriptUrl' => PUBLIC_ROOT . '/Scripts', 'imageUrl' => PUBLIC_ROOT . '/Images', 'user_name' => 'Se7enChat', 'user_id' => 1, 'rooms' => array( array('name' => 'Room 1'), array('name' => 'Room 2', 'selected' => 'selected') ) )); } private function compileCss() { $less = new \lessc; $less->checkedCompile( $this->lessUrl . '/index.less', $this->cssUrl . '/index.css'); } }
<?php namespace Se7enChat\Libraries\Web\Presenters; use Se7enChat\Boundaries\IndexOutputPort; use Se7enChat\Gateways\UserInterfaceGateway; class IndexPresenter implements IndexOutputPort { private $userInterface; private $lessUrl; private $cssUrl; public function __construct(UserInterfaceGateway $ui) { $this->lessUrl = __DIR__ . '/../../UserInterface/Less'; $this->cssUrl = CHAT_ROOT . 'Public/Styles'; $this->userInterface = $ui; } public function present(array $information) { $this->compileCss(); $this->userInterface->render('index', array( 'pageTitle' => 'Se7enChat', 'cssUrl' => PUBLIC_ROOT . '/Styles', 'javascriptUrl' => PUBLIC_ROOT . '/Scripts', 'imageUrl' => PUBLIC_ROOT . '/Images', 'user_name' => 'Francisco', 'user_id' => 1, 'rooms' => array( array('name' => 'Room 1'), array('name' => 'Room 2', 'selected' => 'selected') ) )); } private function compileCss() { $less = new \lessc; $less->checkedCompile( $this->lessUrl . '/index.less', $this->cssUrl . '/index.css'); } }
Add bump:major task to Grunt
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["package.json"], createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", push: false } }, shell: { options: { stdout: true, stderr: true, failOnError: true }, push: { command: "git push -u -f --tags origin master" }, publish: { command: "npm publish" }, update: { command: "npm-check-updates -u" }, modules: { command: "npm install" } } }); grunt.registerTask("update", ["shell:update", "shell:modules"]); grunt.registerTask("patch", ["bump", "shell:push", "shell:publish"]); grunt.registerTask("minor", ["bump:minor", "shell:push", "shell:publish"]); grunt.registerTask("major", ["bump:major", "shell:push", "shell:publish"]); grunt.loadNpmTasks("grunt-bump"); grunt.loadNpmTasks("grunt-shell"); };
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["package.json"], createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", push: false } }, shell: { options: { stdout: true, stderr: true, failOnError: true }, push: { command: "git push -u -f --tags origin master" }, publish: { command: "npm publish" }, update: { command: "npm-check-updates -u" }, modules: { command: "npm install" } } }); grunt.registerTask("update", ["shell:update", "shell:modules"]); grunt.registerTask("patch", ["bump", "shell:push", "shell:publish"]); grunt.registerTask("release", ["bump:minor", "shell:push", "shell:publish"]); grunt.loadNpmTasks("grunt-bump"); grunt.loadNpmTasks("grunt-shell"); };
Implement correct derivation of SoftMax
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: return 1 - np.power(np.tanh(signal), 2) activation = np.tanh(signal) return activation @staticmethod def elu(signal, deriv=False, alpha=1.0): activation = (signal >= 0).astype(int) * signal + \ (signal < 0).astype(int) * (alpha * (np.exp(signal) - 1)) if deriv: derivation = (signal >= 0).astype(int) + \ (signal < 0) * (activation + alpha) return derivation return activation @staticmethod def softmax(signal, deriv=False): signal = signal - np.max(signal) activation = np.exp(signal) / np.array([np.sum(np.exp(signal), axis=1)]).T if deriv: jacobian = - activation[..., None] * activation[:, None, :] iy, ix = np.diag_indices_from(jacobian[0]) jacobian[:, iy, ix] = activation * (1 - activation) return jacobian.sum(axis=1) return activation
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: return 1 - np.power(np.tanh(signal), 2) activation = np.tanh(signal) return activation @staticmethod def elu(signal, deriv=False, alpha=1.0): activation = (signal >= 0).astype(int) * signal + \ (signal < 0).astype(int) * (alpha * (np.exp(signal) - 1)) if deriv: activation = (signal >= 0).astype(int) + \ (signal < 0) * (Activator.elu(signal) + alpha) return activation @staticmethod def softmax(signal, deriv=False): signal = signal - np.max(signal) # Implement correct derivation for the softmax normalization if deriv: return np.exp(signal) * (1 - np.exp(signal)) activation = np.exp(signal) / np.array([np.sum(np.exp(signal), axis=1)]).T return activation
Add retry and failure detection to callback.execute
#! /usr/bin/python import json import requests from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) @retry def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs).status_code < 400
#! /usr/bin/python import json import requests class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs)
Remove leftover print call in paginator
""".. Ignore pydocstyle D400. ================== Elastic Paginators ================== Paginator classes used in Elastic app. .. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination """ from __future__ import absolute_import, division, print_function, unicode_literals from rest_framework.pagination import LimitOffsetPagination, _positive_int def get_query_param(request, key): """Get query parameter uniformly for GET and POST requests.""" value = request.query_params.get(key) or request.data.get(key) if value is None: raise KeyError() return value class LimitOffsetPostPagination(LimitOffsetPagination): """Limit/offset paginator. This is standard limit/offset paginator from Django REST framework, with difference that it supports passing ``limit`` and ``offset`` attributes also in the body of the request (not just as query parameter). """ def get_limit(self, request): """Return limit parameter.""" if self.limit_query_param: try: return _positive_int( get_query_param(request, self.limit_query_param), strict=True, cutoff=self.max_limit ) except (KeyError, ValueError): pass return self.default_limit def get_offset(self, request): """Return offset parameter.""" try: return _positive_int( get_query_param(request, self.offset_query_param), ) except (KeyError, ValueError): return 0
""".. Ignore pydocstyle D400. ================== Elastic Paginators ================== Paginator classes used in Elastic app. .. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination """ from __future__ import absolute_import, division, print_function, unicode_literals from rest_framework.pagination import LimitOffsetPagination, _positive_int def get_query_param(request, key): """Get query parameter uniformly for GET and POST requests.""" value = request.query_params.get(key) or request.data.get(key) if value is None: raise KeyError() return value class LimitOffsetPostPagination(LimitOffsetPagination): """Limit/offset paginator. This is standard limit/offset paginator from Django REST framework, with difference that it supports passing ``limit`` and ``offset`` attributes also in the body of the request (not just as query parameter). """ def get_limit(self, request): """Return limit parameter.""" if self.limit_query_param: try: print(get_query_param(request, self.limit_query_param)) return _positive_int( get_query_param(request, self.limit_query_param), strict=True, cutoff=self.max_limit ) except (KeyError, ValueError): pass return self.default_limit def get_offset(self, request): """Return offset parameter.""" try: return _positive_int( get_query_param(request, self.offset_query_param), ) except (KeyError, ValueError): return 0
Disable exception logging of status code 500 during testing.
# -*- coding: utf-8 -*- """ This module sets up the view for handling ``500 Internal Server Error`` errors. """ import datetime import flask import flask_classful from orchard.errors import blueprint class Error500View(flask_classful.FlaskView): """ View for ``500 Internal Server Error`` errors. """ trailing_slash = False @blueprint.app_errorhandler(500) @blueprint.app_errorhandler(Exception) def index(self) -> str: """ Display the error page for internal errors and send a mail to all administrators information them of this error. :return: A page explaining the error. """ message = ('Time: {time}\n' + 'Request: {method} {path}\n' + 'Agent: {agent_platform} | {agent_browser} {agent_browser_version}\n' + 'Raw Agent: {agent}\n\n' ).format(time = datetime.datetime.now(), method = flask.request.method, path = flask.request.path, agent_platform = flask.request.user_agent.platform, agent_browser = flask.request.user_agent.browser, agent_browser_version = flask.request.user_agent.version, agent = flask.request.user_agent.string) if not flask.current_app.testing: # pragma: no cover. flask.current_app.logger.exception(message) return flask.render_template('errors/500.html') Error500View.register(blueprint)
# -*- coding: utf-8 -*- """ This module sets up the view for handling ``500 Internal Server Error`` errors. """ import datetime import flask import flask_classful from orchard.errors import blueprint class Error500View(flask_classful.FlaskView): """ View for ``500 Internal Server Error`` errors. """ trailing_slash = False @blueprint.app_errorhandler(500) @blueprint.app_errorhandler(Exception) def index(self) -> str: """ Display the error page for internal errors and send a mail to all administrators information them of this error. :return: A page explaining the error. """ message = ('Time: {time}\n' + 'Request: {method} {path}\n' + 'Agent: {agent_platform} | {agent_browser} {agent_browser_version}\n' + 'Raw Agent: {agent}\n\n' ).format(time = datetime.datetime.now(), method = flask.request.method, path = flask.request.path, agent_platform = flask.request.user_agent.platform, agent_browser = flask.request.user_agent.browser, agent_browser_version = flask.request.user_agent.version, agent = flask.request.user_agent.string) flask.current_app.logger.exception(message) return flask.render_template('errors/500.html') Error500View.register(blueprint)
Change directory of tempest config
import json import logging import os import requests from jinja2 import Template from os.path import abspath, dirname, exists, join from .utils import run_cmd LOG = logging.getLogger(__name__) class Framework(object): def __init__(self, environment): self.admin = environment.admin self.guests = environment.guests self.endpoints = environment.endpoints self.images = environment.images self.network = environment.network self.router = environment.router def populate(self): raise NotImplementedError class Tempest(Framework): def __init__(self, environment): super(Tempest, self).__init__(environment) def populate_config(self): LOG.info('Building configuration file') template_dir = join(abspath(dirname(__file__)), 'files/') with open(join(template_dir, 'tempest.conf.example'), 'r') as fp: sample = fp.read() self.config = Template(sample).render( admin=self.admin, guests=self.guests, endpoints=self.endpoints, images=self.images, network=self.network, router=self.router) with open('/etc/tempest/tempest.conf', 'w') as fp: fp.write(self.config)
import json import logging import os import requests from jinja2 import Template from os.path import abspath, dirname, exists, join from .utils import run_cmd LOG = logging.getLogger(__name__) class Framework(object): def __init__(self, environment): self.admin = environment.admin self.guests = environment.guests self.endpoints = environment.endpoints self.images = environment.images self.network = environment.network self.router = environment.router def populate(self): raise NotImplementedError class Tempest(Framework): def __init__(self, environment): super(Tempest, self).__init__(environment) def populate_config(self): LOG.info('Building configuration file') template_dir = join(abspath(dirname(__file__)), 'files/') with open(join(template_dir, 'tempest.conf.example'), 'r') as fp: sample = fp.read() self.config = Template(sample).render( admin=self.admin, guests=self.guests, endpoints=self.endpoints, images=self.images, network=self.network, router=self.router) with open('/opt/tempest/tempest.conf', 'w') as fp: fp.write(self.config)
Update Python version classifiers to supported versions
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml4h try: from setuptools import setup except ImportError: from distutils.core import setup setup( name=xml4h.__title__, version=xml4h.__version__, description='XML for Humans in Python', long_description=open('README.rst').read(), author='James Murty', author_email='[email protected]', url='https://github.com/jmurty/xml4h', packages=[ 'xml4h', 'xml4h.impls', ], package_dir={'xml4h': 'xml4h'}, package_data={'': ['README.rst', 'LICENSE']}, include_package_data=True, install_requires=[ 'six', ], license=open('LICENSE').read(), # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Text Processing :: Markup :: XML', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], test_suite='tests', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml4h try: from setuptools import setup except ImportError: from distutils.core import setup setup( name=xml4h.__title__, version=xml4h.__version__, description='XML for Humans in Python', long_description=open('README.rst').read(), author='James Murty', author_email='[email protected]', url='https://github.com/jmurty/xml4h', packages=[ 'xml4h', 'xml4h.impls', ], package_dir={'xml4h': 'xml4h'}, package_data={'': ['README.rst', 'LICENSE']}, include_package_data=True, install_requires=[ 'six', ], license=open('LICENSE').read(), # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Text Processing :: Markup :: XML', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', # 'Programming Language :: Python :: 3.0', # 'Programming Language :: Python :: 3.1', # 'Programming Language :: Python :: 3.2', ], test_suite='tests', )
Add method to get protocol list
package controller; import constant.Urls; import domain.Protocol; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import repository.ProtocolRepository; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @Controller public class ProtocolController { //////////////////////////////////////////////// // ATTRIBUTES @Autowired private ProtocolRepository protocolRepository; //////////////////////////////////////////////// // METHODS @ResponseBody @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.POST) public String createProtocol(@RequestBody Protocol protocol, HttpServletRequest request, HttpServletResponse response) throws IOException { String newProtocolId = protocolRepository.addProtocol(protocol); String protocolUrl = request.getContextPath() + Urls.PROTOCOL_API + '/' + newProtocolId; response.setStatus(HttpStatus.CREATED.value()); response.sendRedirect(protocolUrl); return protocolUrl; } @ResponseBody @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.GET) public List<Protocol> getProtocolList() { return protocolRepository.getAll(); } @ResponseBody @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.GET) public Protocol getProtocol(@PathVariable String id) { return protocolRepository.getById(id); } @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.PUT) public void updateProtocol(@PathVariable String id, @RequestBody Protocol protocol) { protocol.setId(id); protocolRepository.updateProtocol(protocol); } }
package controller; import constant.Urls; import domain.Protocol; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import repository.ProtocolRepository; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class ProtocolController { //////////////////////////////////////////////// // ATTRIBUTES @Autowired private ProtocolRepository protocolRepository; //////////////////////////////////////////////// // METHODS @ResponseBody @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.POST) public String createProtocol(@RequestBody Protocol protocol, HttpServletRequest request, HttpServletResponse response) throws IOException { String newProtocolId = protocolRepository.addProtocol(protocol); String protocolUrl = request.getContextPath() + Urls.PROTOCOL_API + '/' + newProtocolId; response.setStatus(HttpStatus.CREATED.value()); response.sendRedirect(protocolUrl); return protocolUrl; } @ResponseBody @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.GET) public Protocol getProtocol(@PathVariable String id) { return protocolRepository.getById(id); } @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.PUT) public void updateProtocol(@PathVariable String id, @RequestBody Protocol protocol) { protocol.setId(id); protocolRepository.updateProtocol(protocol); } }
Use prepublish.js to compile in grunt
'use strict'; module.exports = function(grunt) { var growl = require('growl'); var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'update LiveScript source', function () { var done = this.async(); // FIXME: Compile changed file only shell.exec([npm, 'run', 'prepublish'].join(' ')); grunt.task.run('test'); done(); }); grunt.registerTask('package_ls', 'update package.ls', function () { var done = this.async(); shell.exec([lsc, '-cj', 'package.ls'].join(' ')); shell.exec([npm, 'install'].join(' ')); growl('Update package.ls', { title: 'Completed' }); done(); }); grunt.registerTask('test', 'run test', function () { var done = this.async(); shell.exec([npm, 'test'].join(' ')); done(); }); grunt.initConfig({ watch: { livescript_src: { files: ['lib/**/*.ls', 'test/**/*.ls', 'public/js/**/*.ls'], tasks: ['livescript_src'] }, package_ls: { files: ['package.ls'], tasks: ['package_ls'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); };
'use strict'; module.exports = function(grunt) { var growl = require('growl'); var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'update LiveScript source', function () { var done = this.async(); // FIXME: Compile changed file only shell.exec(lsc + ' -c lib'); shell.exec(lsc + ' -c test'); grunt.task.run('test'); done(); }); grunt.registerTask('package_ls', 'update package.ls', function () { var done = this.async(); shell.exec(lsc + ' -cj package.ls'); shell.exec(npm + ' install'); growl('Update package.ls', { title: 'Completed' }); done(); }); grunt.registerTask('test', 'run test', function () { var done = this.async(); shell.exec(npm + ' test'); done(); }); grunt.initConfig({ watch: { livescript_src: { files: ['lib/**/*.ls', 'test/**/*.ls'], tasks: ['livescript_src'] }, package_ls: { files: ['package.ls'], tasks: ['package_ls'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); };
Fix bug where images could not be created
/** * Image.js * * @description :: This represents a product image with file paths for different variations (original, thumb, ...). * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { width: { type: 'integer', min: 0 }, height: { type: 'integer', min: 0 }, thumb: { type: 'string' }, medium: { type: 'string' }, large: { type: 'string' }, original: { type: 'string', required: true }, toJSON: function() { var obj = this.toObject() , baseUrl = sails.config.app.baseUrl; if (obj.thumb) { obj.thumb = baseUrl + obj.thumb; } if (obj.medium) { obj.medium = baseUrl + obj.medium; } if (obj.large) { obj.large = baseUrl + obj.large; } obj.original = baseUrl + obj.original; return obj; } }, beforeUpdate: function (values, next) { if (obj.thumb && obj.thumb.indexOf('http') === 0) { delete obj.thumb; } if (obj.medium && obj.medium.indexOf('http') === 0) { delete obj.medium; } if (obj.large && obj.large.indexOf('http') === 0) { delete obj.large; } // Prevent user from overriding these attributes delete values.original; delete values.createdAt; delete values.updatedAt; next(); } };
/** * Image.js * * @description :: This represents a product image with file paths for different variations (original, thumb, ...). * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { width: { type: 'integer', min: 0 }, height: { type: 'integer', min: 0 }, thumb: { type: 'string' }, medium: { type: 'string' }, large: { type: 'string' }, original: { type: 'string', required: true }, toJSON: function() { var obj = this.toObject() , baseUrl = sails.config.app.baseUrl; if (obj.thumb) { obj.thumb = baseUrl + obj.thumb; } if (obj.medium) { obj.medium = baseUrl + obj.medium; } if (obj.large) { obj.large = baseUrl + obj.large; } obj.original = baseUrl + obj.original; return obj; } }, beforeUpdate: function (values, next) { // Prevent user from overriding these attributes delete values.thumb; delete values.medium; delete values.large; delete values.original; delete values.createdAt; delete values.updatedAt; next(); } };
Add method to log error without throwable Add Ln.e(message) in addition to Ln.e(message, error).
package com.genymobile.scrcpy; import android.util.Log; /** * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal * directly). */ public final class Ln { private static final String TAG = "scrcpy"; enum Level { DEBUG, INFO, WARN, ERROR; } private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO; private Ln() { // not instantiable } public static boolean isEnabled(Level level) { return level.ordinal() >= THRESHOLD.ordinal(); } public static void d(String message) { if (isEnabled(Level.DEBUG)) { Log.d(TAG, message); System.out.println("DEBUG: " + message); } } public static void i(String message) { if (isEnabled(Level.INFO)) { Log.i(TAG, message); System.out.println("INFO: " + message); } } public static void w(String message) { if (isEnabled(Level.WARN)) { Log.w(TAG, message); System.out.println("WARN: " + message); } } public static void e(String message, Throwable throwable) { if (isEnabled(Level.ERROR)) { Log.e(TAG, message, throwable); System.out.println("ERROR: " + message); if (throwable != null) { throwable.printStackTrace(); } } } public static void e(String message) { e(message, null); } }
package com.genymobile.scrcpy; import android.util.Log; /** * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal * directly). */ public final class Ln { private static final String TAG = "scrcpy"; enum Level { DEBUG, INFO, WARN, ERROR; } private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO; private Ln() { // not instantiable } public static boolean isEnabled(Level level) { return level.ordinal() >= THRESHOLD.ordinal(); } public static void d(String message) { if (isEnabled(Level.DEBUG)) { Log.d(TAG, message); System.out.println("DEBUG: " + message); } } public static void i(String message) { if (isEnabled(Level.INFO)) { Log.i(TAG, message); System.out.println("INFO: " + message); } } public static void w(String message) { if (isEnabled(Level.WARN)) { Log.w(TAG, message); System.out.println("WARN: " + message); } } public static void e(String message, Throwable throwable) { if (isEnabled(Level.ERROR)) { Log.e(TAG, message, throwable); System.out.println("ERROR: " + message); throwable.printStackTrace(); } } }
Update path fonts gulp task
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build:release gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-npm/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); });
var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build:release gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-framework/release/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); });
Move mouse events to thumbnail
import React, { PropTypes } from 'react'; import '../../css/SearchGifView.css' class SearchGifView extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMouseOut = this.handleMouseOut.bind(this); this.state = { url: props.gif.images.original_still.url }; } handleClick() { this.props.click(this.props.gif); } handleMouseOver() { let gif = this.props.gif; this.setState({ url: gif.images.downsized.url }); } handleMouseOut() { let gif = this.props.gif; this.setState({ url: gif.images.original_still.url }); } render() { return ( <div className="col-xs-4 search-gif-view"> <div className="thumbnail" onClick={this.handleClick} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}> <img role="presentation" src={this.state.url} /> </div> </div> ); } }; SearchGifView.propTypes = { gif: PropTypes.object.isRequired, click: PropTypes.func }; export default SearchGifView;
import React, { PropTypes } from 'react'; import '../../css/SearchGifView.css' class SearchGifView extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMouseOut = this.handleMouseOut.bind(this); this.state = { url: props.gif.images.original_still.url }; } handleClick() { this.props.click(this.props.gif); } handleMouseOver() { let gif = this.props.gif; this.setState({ url: gif.images.downsized.url }); } handleMouseOut() { let gif = this.props.gif; this.setState({ url: gif.images.original_still.url }); } render() { return ( <div className="col-xs-4 search-gif-view" onClick={this.handleClick} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}> <div className="thumbnail"> <img role="presentation" src={this.state.url} /> </div> </div> ); } }; SearchGifView.propTypes = { gif: PropTypes.object.isRequired, click: PropTypes.func }; export default SearchGifView;
Use host instead of hostname Former-commit-id: 40b779195685a054d6247559f4f3fed5ac39d985 Former-commit-id: 426cf513caae3bca89af65bfdcfe1e5751b917d1 Former-commit-id: 8577ea950f5083c9f65a589b2ac1bacb1646f749
/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $(".modal"); // modal functions function closeModal() { modal.remove(); } function saveUrl() { var embedUrl = $('input#embed-url').val(); var fullWidth = $('input#full-width-checkbox').is(':checked'); if (!embedUrl) { console.log("No url added"); sweetAlert('URL field is empty', 'Please add a url and save again'); return; } var parsedEmbedUrl = new URL(embedUrl); console.log(parsedEmbedUrl); console.log(window.location); if (parsedEmbedUrl.host === window.location.host) { embedUrl = parsedEmbedUrl.pathname; } onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>'); modal.remove(); } // bind events $('.btn-embed-cancel').click(function() { closeModal(); }); $('.btn-embed-save').click(function() { saveUrl(); }); modal.keyup(function(e) { if (e.keyCode == 27) { //close on esc key closeModal() } if (e.keyCode == 13) { //save on enter key saveUrl(); } }); }
/** * Created by crispin on 10/12/2015. */ function loadEmbedIframe(onSave) { // add modal window $('.workspace-menu').append(templates.embedIframe()); // variables var modal = $(".modal"); // modal functions function closeModal() { modal.remove(); } function saveUrl() { var embedUrl = $('input#embed-url').val(); var fullWidth = $('input#full-width-checkbox').is(':checked'); if (!embedUrl) { console.log("No url added"); sweetAlert('URL field is empty', 'Please add a url and save again'); return; } var parsedEmbedUrl = new URL(embedUrl); if (parsedEmbedUrl.hostname === window.location.hostname) { embedUrl = parsedEmbedUrl.pathname; } onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>'); modal.remove(); } // bind events $('.btn-embed-cancel').click(function() { closeModal(); }); $('.btn-embed-save').click(function() { saveUrl(); }); modal.keyup(function(e) { if (e.keyCode == 27) { //close on esc key closeModal() } if (e.keyCode == 13) { //save on enter key saveUrl(); } }); }
Append the event name in case of server methods too
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = null , mP = null ; // Load if (input[0] === Enny.TYPES.load.handler) { output.type = Enny.TYPES.load; output.args = input.slice(1); // Emit/link } else if ((eP = ParseMethod(input[0], instName)).method === "flow") { if (Enny.TYPES((mP = ParseMethod(input[1], instName)).type, Enny.TYPES.link)) { output = mP; output.type = Enny.TYPES.link; output.serverMethod = output.method; output.event = output.method; } else { output = eP; output.type = Enny.TYPES.emit; output.event = input[1]; } } // Stream handler if (!output.type) { output = ParseMethod(input[0], instName); output.args = input.slice(1); } return output; };
// Dependencies var ParseMethod = require("./method") , Enny = require("enny") , Ul = require("ul") , Typpy = require("typpy") ; module.exports = function (_input, instName) { var input = Ul.clone(_input); if (Typpy(input, String)) { input = [input]; } var output = {} , eP = null , mP = null ; // Load if (input[0] === Enny.TYPES.load.handler) { output.type = Enny.TYPES.load; output.args = input.slice(1); // Emit/link } else if ((eP = ParseMethod(input[0], instName)).method === "flow") { if (Enny.TYPES((mP = ParseMethod(input[1], instName)).type, Enny.TYPES.link)) { output = mP; output.type = Enny.TYPES.link; output.serverMethod = output.method; } else { output = eP; output.type = Enny.TYPES.emit; output.event = input[1]; } } // Stream handler if (!output.type) { output = ParseMethod(input[0], instName); output.args = input.slice(1); } return output; };
Revert to puppeteer (keeping chromium install for dependencies)
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath() module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadlessNoSandbox'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: [ // '--disable-translate', // '--headless', '--disable-gpu', // '--disable-extensions', '--no-sandbox', // '--disable-setuid-sandbox', '--remote-debugging-port=9222' ] } }, singleRun: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath() module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadlessNoSandbox'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: [ // '--disable-translate', // '--headless', // '--disable-gpu', // '--disable-extensions', '--no-sandbox', // '--disable-setuid-sandbox', // '--remote-debugging-port=9222' ] } }, singleRun: true }); };
Handle request error: controller backupDatabase, restoreDatabase
angular.module('myapp') .controller('HomeController', ['$scope', '$timeout', 'SnapshotServices', function ($scope, $timeout, SnapshotServices) { $scope.listSnapshot = []; $scope.currentSnapshot = ""; $scope.getSnapshots = function () { SnapshotServices.getSnapshots().then(function (data) { $scope.listSnapshot = data['snapshots']; }); }; $scope.backupDatabase = function () { $scope.showLoading(); SnapshotServices.backupDatabase(function () { $timeout(function () { $scope.hideLoading(); }, 500); $scope.getSnapshots(); }).then(function (data) { if (data.status == "success") { } else { } }, function () { $timeout(function () { $scope.hideLoading(); }, 500); }); }; $scope.restoreDatabase = function () { if ($scope.currentSnapshot) { $scope.showLoading() SnapshotServices.restoreDatabase($scope.currentSnapshot, function () { $timeout(function () { $scope.hideLoading(); }, 200); }).then(function (data) { if (data.status == "success") { $scope.currentSnapshot = ""; } else { } }, function () { $timeout(function () { $scope.hideLoading(); }, 500); }); } }; $scope.chooseSnapshot = function (snapshotId, $event) { $('.active').removeClass('active'); $($event.currentTarget).find('span').addClass('active'); $scope.currentSnapshot = snapshotId; }; }]);
angular.module('myapp') .controller('HomeController', ['$scope', '$timeout', 'SnapshotServices', function ($scope, $timeout, SnapshotServices) { $scope.listSnapshot = []; $scope.currentSnapshot = ""; $scope.getSnapshots = function () { SnapshotServices.getSnapshots().then(function (data) { $scope.listSnapshot = data['snapshots']; }); }; $scope.backupDatabase = function () { $scope.showLoading(); SnapshotServices.backupDatabase(function () { $timeout(function () { $scope.hideLoading(); }, 500); $scope.getSnapshots(); }).then(function (data) { if (data.status == "success") { } else { } }); }; $scope.restoreDatabase = function () { if ($scope.currentSnapshot) { $scope.showLoading() SnapshotServices.restoreDatabase($scope.currentSnapshot, function () { $timeout(function () { $scope.hideLoading(); }, 500); }).then(function (data) { if (data.status == "success") { $scope.currentSnapshot = ""; } else { } }); } }; $scope.chooseSnapshot = function (snapshotId, $event) { $('.active').removeClass('active'); $($event.currentTarget).find('span').addClass('active'); $scope.currentSnapshot = snapshotId; // console.log($scope.currentSnapshot) }; }]);
Return Pubmed title and abstract
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
Use list comprehensions to format all errors where message is not a dict
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
Move from deprecated HttpKernel's to Debug's FlattenException.
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\StepupBundle\Controller; use Surfnet\StepupBundle\Exception\Art; use Symfony\Bundle\FrameworkBundle\Controller\Controller as FrameworkController; use Symfony\Component\Debug\Exception\FlattenException; use Symfony\Component\HttpFoundation\Response; class ExceptionController extends FrameworkController { public function showAction(FlattenException $exception) { $statusCode = $exception->getStatusCode(); if ($statusCode == 404) { $template = 'SurfnetStepupBundle:Exception:error404.html.twig'; } else { $template = 'SurfnetStepupBundle:Exception:error.html.twig'; } return $this->render($template, [ 'exception' => $exception, 'art' => Art::forFlattenException($exception), 'statusCode' => $statusCode, 'statusText' => isset(Response::$statusTexts[$statusCode]) ? Response::$statusTexts[$statusCode] : '', ]); } }
<?php /** * Copyright 2014 SURFnet bv * * 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. */ namespace Surfnet\StepupBundle\Controller; use Surfnet\StepupBundle\Exception\Art; use Symfony\Bundle\FrameworkBundle\Controller\Controller as FrameworkController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\FlattenException; class ExceptionController extends FrameworkController { public function showAction(FlattenException $exception) { $statusCode = $exception->getStatusCode(); if ($statusCode == 404) { $template = 'SurfnetStepupBundle:Exception:error404.html.twig'; } else { $template = 'SurfnetStepupBundle:Exception:error.html.twig'; } return $this->render($template, [ 'exception' => $exception, 'art' => Art::forFlattenException($exception), 'statusCode' => $statusCode, 'statusText' => isset(Response::$statusTexts[$statusCode]) ? Response::$statusTexts[$statusCode] : '', ]); } }
FIX method POST on login_check
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { /** * @param Request $request * @return \Symfony\Component\HttpFoundation\Response * * @Route("/login", * name="app_security_login", * methods={"GET"}) */ public function loginAction(Request $request) { $authenticationUtils = $this->get('security.authentication_utils'); // Login error if there is one $error = $authenticationUtils->getLastAuthenticationError(); // Last username entered by the user $lastUsername = $authenticationUtils->getLastUsername(); return $this->render('security/login.html.twig', array('error' => $error, 'lastUserName' => $lastUsername)); } /** * @Route("/login/check", * name="app_security_login_check", * methods={"POST"}) */ public function loginCheckAction() { // Never be executed } /** * @Route("/logout", * name="app_security_logout", * methods={"GET"}) */ public function logoutAction() { // Never be executed } }
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { /** * @param Request $request * @return \Symfony\Component\HttpFoundation\Response * * @Route("/login", * name="app_security_login", * methods={"GET"}) */ public function loginAction(Request $request) { $authenticationUtils = $this->get('security.authentication_utils'); // Login error if there is one $error = $authenticationUtils->getLastAuthenticationError(); // Last username entered by the user $lastUsername = $authenticationUtils->getLastUsername(); return $this->render('security/login.html.twig', array('error' => $error, 'lastUserName' => $lastUsername)); } /** * @Route("/login/check", * name="app_security_login_check", * methods={"GET"}) */ public function loginCheckAction() { // Never be executed } /** * @Route("/logout", * name="app_security_logout", * methods={"GET"}) */ public function logoutAction() { // Never be executed } }
Rewrite get() to be less repetitive but still stupid
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri self.url_opener = url_opener self.sleep_time = sleep_time self.max_tries = max_tries def get (self, **kwargs): class SpecialNull: pass result = SpecialNull i = 1 while result is SpecialNull: try: result = self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) if i == self.max_tries: result = b"" else: i += 1 return result @staticmethod def utf8 (str_or_bytes): if isinstance(str_or_bytes, bytes): return str_or_bytes.decode("utf_8") else: return str_or_bytes def __open_uri (self, kwargs): with self.url_opener(self.uri(**kwargs)) as response: result = self.utf8(response.read()) return result
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from time import sleep class APIQuerier: def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0): self.uri = uri self.url_opener = url_opener self.sleep_time = sleep_time self.max_tries = max_tries def get (self, **kwargs): try: return self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) i = 1 while i != self.max_tries: i += 1 try: return self.__open_uri(kwargs) except ConnectionError: sleep(self.sleep_time) return b"" @staticmethod def utf8 (str_or_bytes): if isinstance(str_or_bytes, bytes): return str_or_bytes.decode("utf_8") else: return str_or_bytes def __open_uri (self, kwargs): with self.url_opener(self.uri(**kwargs)) as response: result = self.utf8(response.read()) return result
Add LegalRepresentativeProofOfIdentity to legal user
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) return properties
Update community to use new lib namespace
import sys from lib.core import Tokenizer from lib.utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response.get('subscribers_count', 0) stargazers_count = json_response.get('stargazers_count', 0) forks = json_response.get('forks', 0) result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
import sys from core import Tokenizer from utilities import url_to_json def run(project_id, repo_path, cursor, **options): t_sub = options.get('sub') t_star = options.get('star') t_forks = options.get('forks') cursor.execute(''' SELECT url FROM projects WHERE id = {0} '''.format(project_id)) record = cursor.fetchone() tokenizer = Tokenizer() full_url = tokenizer.tokenize(record[0].rstrip()) json_response = url_to_json(full_url) subscribers_count = json_response.get('subscribers_count', 0) stargazers_count = json_response.get('stargazers_count', 0) forks = json_response.get('forks', 0) result = False if ( (subscribers_count >= t_sub and stargazers_count >= t_star) or (stargazers_count >= t_star and forks >= t_forks) or (subscribers_count >= t_sub and forks >= t_forks) ): result = True return ( result, { 'sub': subscribers_count, 'star': stargazers_count, 'forks': forks } ) if __name__ == '__main__': print('Attribute plugins are not meant to be executed directly.') sys.exit(1)
Use compatible release versions for all dependencies
import os from setuptools import setup, find_packages import glob VERSION = "0.6.3" src_dir = os.path.dirname(__file__) install_requires = [ "troposphere~=1.8.0", "boto3~=1.3.1", "botocore~=1.4.38", "PyYAML~=3.11", "awacs~=0.6.0", "colorama~=0.3.7", ] tests_require = [ "nose~=1.0", "mock~=2.0.0", "stacker_blueprints~=0.6.0", "moto~=0.4.25", "testfixtures~=4.10.0", ] def read(filename): full_path = os.path.join(src_dir, filename) with open(full_path) as fd: return fd.read() if __name__ == "__main__": setup( name="stacker", version=VERSION, author="Michael Barrett", author_email="[email protected]", license="New BSD license", url="https://github.com/remind101/stacker", description="Opinionated AWS CloudFormation Stack manager", long_description=read("README.rst"), packages=find_packages(), scripts=glob.glob(os.path.join(src_dir, "scripts", "*")), install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", )
import os from setuptools import setup, find_packages import glob VERSION = "0.6.3" src_dir = os.path.dirname(__file__) install_requires = [ "troposphere>=1.8.0", "boto3>=1.3.1", "botocore>=1.4.38", "PyYAML>=3.11", "awacs>=0.6.0", "colorama==0.3.7", ] tests_require = [ "nose>=1.0", "mock==1.0.1", "stacker_blueprints", "moto", "testfixtures", ] def read(filename): full_path = os.path.join(src_dir, filename) with open(full_path) as fd: return fd.read() if __name__ == "__main__": setup( name="stacker", version=VERSION, author="Michael Barrett", author_email="[email protected]", license="New BSD license", url="https://github.com/remind101/stacker", description="Opinionated AWS CloudFormation Stack manager", long_description=read("README.rst"), packages=find_packages(), scripts=glob.glob(os.path.join(src_dir, "scripts", "*")), install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", )
Update pagesavehook for new fields
<?php namespace Tev\Tev\Hook; use Tev\Tev\Url\Cache; /** * Hook for saving pages. */ class PageSaveHook { /** * After a page is saved, check if it is new or if its RealURL config has * been changed. * * If it has, clear the RealURL config cache. * * @param string $status 'new' for new entities, 'update' for existing entities * @param string $table Database table name being saved * @param int $id UID of New ID of entity being saved * @param array $fieldArray Array of fields being updated * @param \TYPO3\CMS\Core\DataHandling\DataHandler $pObj * @return void */ public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, &$pObj) { if ($table === 'pages') { if (($status === 'new') || isset($fieldArray['tx_tev_realurl_extbase_extension']) || isset($fieldArray['tx_tev_realurl_extbase_plugin']) || isset($fieldArray['tx_tev_realurl_extbase_inc_controller']) || isset($fieldArray['tx_tev_realurl_extbase_inc_action']) || isset($fieldArray['tx_tev_realurl_extbase_args']) ) { (new Cache)->clear(); } } } }
<?php namespace Tev\Tev\Hook; use Tev\Tev\Url\Cache; /** * Hook for saving pages. */ class PageSaveHook { /** * After a page is saved, check if it is new or if its RealURL config has * been changed. * * If it has, clear the RealURL config cache. * * @param string $status 'new' for new entities, 'update' for existing entities * @param string $table Database table name being saved * @param int $id UID of New ID of entity being saved * @param array $fieldArray Array of fields being updated * @param \TYPO3\CMS\Core\DataHandling\DataHandler $pObj * @return void */ public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, &$pObj) { if ($table === 'pages') { if (($status === 'new') || isset($fieldArray['tx_tev_postvars']) || isset($fieldArray['tx_tev_childpostvars'])) { $urlCache = new Cache; $urlCache->clear(); } } } }
Modify filter to show new computational sample templates.
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', margin: true, templates: this.templates.filter(t => t.process_type === 'create') }, { title: 'TRANSFORMATION', cssClass: 'mc-transform-color', icon: 'fa-exclamation-triangle', templates: this.templates.filter(t => t.process_type === 'transform') }, { title: 'MEASUREMENT', cssClass: 'mc-measurement-color', icon: 'fa-circle', templates: this.templates.filter(t => t.process_type === 'measurement') }, { title: 'ANALYSIS', cssClass: 'mc-analysis-color', icon: 'fa-square', templates: this.templates.filter(t => t.process_type === 'analysis') } ]; } chooseTemplate(t) { if (this.onSelected) { this.onSelected({templateId: t.name, processId: ''}); } } } angular.module('materialscommons').component('mcWorkflowProcessTemplates', { templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html', controller: MCWorkflowProcessTemplatesComponentController, bindings: { onSelected: '&' } });
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', margin: true, templates: this.templates.filter(t => t.process_type === 'create' && t.name === 'Create Samples') }, { title: 'TRANSFORMATION', cssClass: 'mc-transform-color', icon: 'fa-exclamation-triangle', templates: this.templates.filter(t => t.process_type === 'transform' && t.name !== 'Create Samples') }, { title: 'MEASUREMENT', cssClass: 'mc-measurement-color', icon: 'fa-circle', templates: this.templates.filter(t => t.process_type === 'measurement') }, { title: 'ANALYSIS', cssClass: 'mc-analysis-color', icon: 'fa-square', templates: this.templates.filter(t => t.process_type === 'analysis') } ]; } chooseTemplate(t) { if (this.onSelected) { this.onSelected({templateId: t.name, processId: ''}); } } } angular.module('materialscommons').component('mcWorkflowProcessTemplates', { templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html', controller: MCWorkflowProcessTemplatesComponentController, bindings: { onSelected: '&' } });
Add methods to linked list.
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self, val): '''Insert new Node at head of Linked List.''' self.head = Node(val, self.head) self.length += 1 return None def pop(self): '''Pop the first Node from the head of Linked List, return val''' if self.head is None: raise IndexError else: to_return = self.head self.head = to_return.next self.length -= 1 return to_return.val def size(self): '''Return current length of Linked List.''' return len(self) def search(self, search): '''Return given node of Linked List if present, else None.''' for node in self: if node.val == search: return node else: return None def remove(self, search): '''Remove given node from Linked List, return None.''' for node in self: if node.next == search: node.next = node.next.next return None def display(self): '''Display Linked List as string.''' return repr(self)
class Node(object): def __init__(self, val, next=None): self.val = val self.next = next def __repr__(self): return '{val}'.format(val=self.val) class LinkedList(object): def __init__(self, iterable=()): self._current = None self.head = None self.length = 0 for val in reversed(iterable): self.insert(val) def __repr__(self): '''Print string representation of Linked List.''' node = self.head output = '' for node in self: output += '{!r}'.format(node.val) return '({})'.format(output.rstrip(' ,')) def __len__(self): return self.length def __iter__(self): if self.head is not None: self._current = self.head return self def next(self): if self._current is None: raise StopIteration node = self._current self._current = self._current.next return node def insert(self): pass def size(self): pass def search(self): pass def display(self): pass def remove(self): pass def pop(self): pass
Use substrings rather than prefixes
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var colorMapping = { 'blocked': 'rgb(199, 37, 67)', 'needs ': 'rgb(199, 37, 67)' }; function colorLabelNodes(labels) { Object.keys(colorMapping).forEach(function(labelKeyword) { Array.prototype.filter.call(labels, function(label) { return label.textContent.indexOf(labelKeyword) >= 0; }).forEach(function(label) { label.style.color = colorMapping[labelKeyword]; }); }); } var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) { if (typeof addedNode.getElementsByClassName !== 'undefined') { var previews = addedNode.getElementsByClassName('preview'); if (previews.length === 0) { return; } var labels = Array.prototype.filter.call(previews, function(preview) { return preview.getElementsByClassName !== 'undefined'; }).map(function(preview) { return Array.prototype.slice.call(preview.getElementsByClassName('label')); }); colorLabelNodes(Array.prototype.concat.apply([], labels)); } }); }); }); // configuration of the observer: var config = { childList: true, subtree: true }; observer.observe(document, config); } }, 10); });
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var colorMapping = { 'blocked': 'rgb(199, 37, 67)', 'needs ': 'rgb(199, 37, 67)' }; function colorLabelNodes(labels) { Object.keys(colorMapping).forEach(function(labelKeyword) { Array.prototype.filter.call(labels, function(label) { return label.textContent.indexOf(labelKeyword) === 0 }).forEach(function(label) { label.style.color = colorMapping[labelKeyword]; }); }); } var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) { if (typeof addedNode.getElementsByClassName !== 'undefined') { var previews = addedNode.getElementsByClassName('preview'); if (previews.length === 0) { return; } var labels = Array.prototype.filter.call(previews, function(preview) { return preview.getElementsByClassName !== 'undefined'; }).map(function(preview) { return Array.prototype.slice.call(preview.getElementsByClassName('label')); }); colorLabelNodes(Array.prototype.concat.apply([], labels)); } }); }); }); // configuration of the observer: var config = { childList: true, subtree: true }; observer.observe(document, config); } }, 10); });
Update test to ignore refund-payments for admins
<?php declare(strict_types=1); namespace Tests\Feature; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; use Tests\TestCase; class PermissionsAndRolesTest extends TestCase { public function testPermissionsLoadedInDatabase(): void { $allPermissions = Permission::all(); // phpcs:disable $this->assertGreaterThan(0, $allPermissions->count(), 'The permissions table appears to be '. 'empty, which means the database configuration for testing is not working, or a database dump was generated incorrectly (see https://github.com/RoboJackets/apiary/issues/1801). Are you running `composer run '. 'test`?'); // phpcs:enable } /** * Ensure that the admin role has all permissions. */ public function testAdminRoleHasAllPermissions(): void { $permissions = Role::where('name', 'admin')->first()->permissions; $allPermissions = Permission::where('name', '!=', 'refund-payments')->get(); $this->assertCount(0, $permissions->diff($allPermissions)); $this->assertCount(0, $allPermissions->diff($permissions)); } /** * Ensure the member and non-member roles have the same permissions. */ public function testMemberAndNonMemberAreSame(): void { $nonmember = Role::where('name', 'non-member')->first()->permissions; $member = Role::where('name', 'member')->first()->permissions; $this->assertCount(0, $nonmember->diff($member)); $this->assertCount(0, $member->diff($nonmember)); } }
<?php declare(strict_types=1); namespace Tests\Feature; use Spatie\Permission\Models\Permission; use Spatie\Permission\Models\Role; use Tests\TestCase; class PermissionsAndRolesTest extends TestCase { public function testPermissionsLoadedInDatabase(): void { $allPermissions = Permission::all(); // phpcs:disable $this->assertGreaterThan(0, $allPermissions->count(), 'The permissions table appears to be '. 'empty, which means the database configuration for testing is not working, or a database dump was generated incorrectly (see https://github.com/RoboJackets/apiary/issues/1801). Are you running `composer run '. 'test`?'); // phpcs:enable } /** * Ensure that the admin role has all permissions. */ public function testAdminRoleHasAllPermissions(): void { $permissions = Role::where('name', 'admin')->first()->permissions; $allPermissions = Permission::all(); $this->assertCount(0, $permissions->diff($allPermissions)); $this->assertCount(0, $allPermissions->diff($permissions)); } /** * Ensure the member and non-member roles have the same permissions. */ public function testMemberAndNonMemberAreSame(): void { $nonmember = Role::where('name', 'non-member')->first()->permissions; $member = Role::where('name', 'member')->first()->permissions; $this->assertCount(0, $nonmember->diff($member)); $this->assertCount(0, $member->diff($nonmember)); } }
Change global to node compatible
const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const WebpackAutoInject = require('webpack-auto-inject-version'); module.exports = { entry: { 'typedjson': './src/typedjson.ts', 'typedjson.min': './src/typedjson.ts', }, devtool: 'source-map', module: { rules: [ { test: /\.[jt]s$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: [ '.ts', '.js' ], }, output: { filename: '[name].js', path: path.resolve(__dirname, 'js'), library: 'typedjson', libraryTarget: 'umd', umdNamedDefine: true, globalObject: `(typeof self !== 'undefined' ? self : this)`, }, optimization: { minimizer: [ new UglifyJsPlugin({ include: /\.min\.js$/, sourceMap: true, }) ], }, plugins: [ new WebpackAutoInject({ SHORT: 'typedjson', components: { AutoIncreaseVersion: false, }, componentsOptions: { InjectAsComment: { tag: 'Version: {version} - {date}', dateFormat: 'isoDate', }, }, }), ], mode: "production", };
const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const WebpackAutoInject = require('webpack-auto-inject-version'); module.exports = { entry: { 'typedjson': './src/typedjson.ts', 'typedjson.min': './src/typedjson.ts', }, devtool: 'source-map', module: { rules: [ { test: /\.[jt]s$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: [ '.ts', '.js' ], }, output: { filename: '[name].js', path: path.resolve(__dirname, 'js'), library: 'typedjson', libraryTarget: 'umd', umdNamedDefine: true, }, optimization: { minimizer: [ new UglifyJsPlugin({ include: /\.min\.js$/, sourceMap: true, }) ], }, plugins: [ new WebpackAutoInject({ SHORT: 'typedjson', components: { AutoIncreaseVersion: false, }, componentsOptions: { InjectAsComment: { tag: 'Version: {version} - {date}', dateFormat: 'isoDate', }, }, }), ], mode: "production", };
Fix `protocol not supported` on Windows
import sys import zmq from crankycoin import config, logger WIN32 = 'win32' in sys.platform class Queue(object): QUEUE_BIND_IN = config['user']['queue_bind_in'] if not WIN32 else config['user']['win_queue_bind_in'] QUEUE_BIND_OUT = config['user']['queue_bind_out'] if not WIN32 else config['user']['win_queue_bind_out'] QUEUE_PROCESSING_WORKERS = config['user']['queue_processing_workers'] @classmethod def start_queue(cls): try: context = zmq.Context(1) # Socket facing producers frontend = context.socket(zmq.PULL) frontend.bind(cls.QUEUE_BIND_IN) # Socket facing consumers backend = context.socket(zmq.PUSH) backend.bind(cls.QUEUE_BIND_OUT) zmq.proxy(frontend, backend) except Exception as e: logger.error("could not start queue: %s", e) raise @classmethod def enqueue(cls, msg): context = zmq.Context() socket = context.socket(zmq.PUSH) socket.connect(cls.QUEUE_BIND_IN) socket.send_json(msg) @classmethod def dequeue(cls): context = zmq.Context() socket = context.socket(zmq.PULL) socket.connect(cls.QUEUE_BIND_OUT) return socket.recv_json()
import zmq from crankycoin import config, logger class Queue(object): QUEUE_BIND_IN = config['user']['queue_bind_in'] QUEUE_BIND_OUT = config['user']['queue_bind_out'] QUEUE_PROCESSING_WORKERS = config['user']['queue_processing_workers'] @classmethod def start_queue(cls): try: context = zmq.Context(1) # Socket facing producers frontend = context.socket(zmq.PULL) frontend.bind(cls.QUEUE_BIND_IN) # Socket facing consumers backend = context.socket(zmq.PUSH) backend.bind(cls.QUEUE_BIND_OUT) zmq.proxy(frontend, backend) except Exception as e: logger.error("could not start queue: %s", e.message) raise @classmethod def enqueue(cls, msg): context = zmq.Context() socket = context.socket(zmq.PUSH) socket.connect(cls.QUEUE_BIND_IN) socket.send_json(msg) @classmethod def dequeue(cls): context = zmq.Context() socket = context.socket(zmq.PULL) socket.connect(cls.QUEUE_BIND_OUT) return socket.recv_json()
Update schema to handle null and default for datatime
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <[email protected]> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('email', 'string', ['length' => 128]); $this->table->addColumn('displayname', 'string', ['length' => 32, 'notnull' => false]); $this->table->addColumn('enabled', 'boolean', ['default' => 0]); $this->table->addColumn('roles', 'json_array', ['length' => 1024, 'notnull' => false]); $this->table->addColumn('lastseen', 'datetime', ['notnull' => false, 'default' => null]); $this->table->addColumn('lastip', 'string', ['length' => 32, 'notnull' => false]); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addUniqueIndex(['email']); $this->table->addIndex(['enabled']); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['guid']); } }
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account table. * * @author Gawain Lynch <[email protected]> */ class Account extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('email', 'string', ['length' => 128]); $this->table->addColumn('displayname', 'string', ['length' => 32, 'notnull' => false]); $this->table->addColumn('enabled', 'boolean', ['default' => 0]); $this->table->addColumn('roles', 'json_array', ['length' => 1024, 'notnull' => false]); $this->table->addColumn('lastseen', 'datetime', ['default' => '']); $this->table->addColumn('lastip', 'string', ['length' => 32, 'notnull' => false]); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addUniqueIndex(['email']); $this->table->addIndex(['enabled']); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['guid']); } }
Add timezone to programme date format
<?php namespace XmlTv\Tv; class Programme { const DATE_FORMAT = 'YmdHis O'; /** * @var string */ public $start; /** * @var string */ public $stop; /** * @var string */ public $channel; /** * @var string */ public $title; /** * @var string */ public $subTitle; /** * @var string */ public $desc; /** * @var Category[] */ private $categories = []; /** * Programme constructor. * * @param string $start * @param string $stop * @param string $channel */ public function __construct(string $start, string $stop, string $channel) { $this->start = $start; $this->stop = $stop; $this->channel = $channel; } /** * Add a category. * * @param Category $category */ public function addCategory(Category $category) { array_push($this->categories, $category); } /** * Get all categories. * * @return array */ public function getCategories() { return $this->categories; } }
<?php namespace XmlTv\Tv; class Programme { const DATE_FORMAT = 'YmdHis'; /** * @var string */ public $start; /** * @var string */ public $stop; /** * @var string */ public $channel; /** * @var string */ public $title; /** * @var string */ public $subTitle; /** * @var string */ public $desc; /** * @var Category[] */ private $categories = []; /** * Programme constructor. * * @param string $start * @param string $stop * @param string $channel */ public function __construct(string $start, string $stop, string $channel) { $this->start = $start; $this->stop = $stop; $this->channel = $channel; } /** * Add a category. * * @param Category $category */ public function addCategory(Category $category) { array_push($this->categories, $category); } /** * Get all categories. * * @return array */ public function getCategories() { return $this->categories; } }
Load language from cookie if exist
<?php namespace ContentTranslator; class Switcher { public static $cookieKey = 'wp_content_translator_language'; public static $currentLanguage; public function __construct() { if ($lang = $this->getRequestedLang()) { $this->switchToLanguage($lang); } } public function getRequestedLang() { if (isset($_GET['lang']) && !empty($_GET['lang'])) { return $_GET['lang']; } if (isset($_COOKIE[self::$cookieKey]) && !empty($_COOKIE[self::$cookieKey])) { return $_COOKIE[self::$cookieKey]; } return false; } /** * Switches language and sets user cookie * @param string $code Code of language to swtich to * @return bool */ public function switchToLanguage(string $code) : bool { if (!\ContentTranslator\Language::isActive($code)) { $lang = \ContentTranslator\Language::find($code); throw new \Exception("WP Content Translator: Can't switch language to '" . $lang->name . "' because it's not activated.", 1); } self::$currentLanguage = \ContentTranslator\Language::find($code); if (self::$currentLanguage !== false) { setcookie(self::$cookieKey, $code, time() + (3600 * 24 * 30), '/', COOKIE_DOMAIN); } return true; } /** * Checks if language is set * Also available as public function: wp_content_translator_is_language_set() * @return boolean */ public static function isLanguageSet() { return isset(self::$currentLanguage) && !is_null(self::$currentLanguage) && !empty(self::$currentLanguage); } }
<?php namespace ContentTranslator; class Switcher { public static $currentLanguage; public function __construct() { if (isset($_GET['lang']) && !empty($_GET['lang'])) { $this->switchToLanguage($_GET['lang']); } } /** * Switches language and sets user cookie * @param string $code Code of language to swtich to * @return bool */ public function switchToLanguage(string $code) : bool { if (!\ContentTranslator\Language::isActive($code)) { $lang = \ContentTranslator\Language::find($code); throw new \Exception("WP Content Translator: Can't switch language to '" . $lang->name . "' because it's not activated.", 1); } self::$currentLanguage = \ContentTranslator\Language::find($code); if (self::$currentLanguage !== false) { setcookie('wp_content_translator_language', $code, MONTH_IN_SECONDS, '/', COOKIE_DOMAIN); } return true; } /** * Checks if language is set * Also available as public function: wp_content_translator_is_language_set() * @return boolean */ public static function isLanguageSet() { return isset(self::$currentLanguage) && !is_null(self::$currentLanguage) && !empty(self::$currentLanguage); } }
Fix to can receive notification by Hook
(function(){ var onMessageCreated = function(session, store) { return function(data) { store.find('message', data.message.id).then(function(message) { var room = message.get('room'), title = message.get('senderName') + ' > ' + room.get('organization.slug') + ' / ' + room.get('name'); var isSameId = message.get('senderId') === Number(session.get('user.id')), byHuman = message.get('senderType') === 'User'; if (isSameId) { if (byHuman) return; } else { notification = new Notification(title, { body: message.get('bodyPlain'), icon: message.get('senderIconUrl') }); notification.addEventListener('click', function() { var app = Ember.Namespace.NAMESPACES.find(function(a) { return a instanceof Ember.Application; }); var router = app.__container__.lookup('router:main'); if (!router.isActive('main')) return; router.transitionTo('room', message.get('room')); }); } }); } }; window.addEventListener('ready.idobata', function(e) { var container = e.detail.container; var pusher = container.lookup('pusher:main'), session = container.lookup('service:session'), store = container.lookup('service:store'); pusher.bind('message:created', onMessageCreated(session, store)); }); })();
(function(){ var onMessageCreated = function(session, store) { return function(data) { store.find('message', data.message.id).then(function(message) { var room = message.get('room'), title = message.get('senderName') + ' > ' + room.get('organization.slug') + ' / ' + room.get('name'); var byCurrentUser = message.get('senderId') === Number(session.get('user.id')), byHuman = message.get('senderType') === 'User'; if (!byCurrentUser && byHuman) { notification = new Notification(title, { body: message.get('bodyPlain'), icon: message.get('senderIconUrl') }); notification.addEventListener('click', function() { var app = Ember.Namespace.NAMESPACES.find(function(a) { return a instanceof Ember.Application; }); var router = app.__container__.lookup('router:main'); if (!router.isActive('main')) return; router.transitionTo('room', message.get('room')); }); } }); } }; window.addEventListener('ready.idobata', function(e) { var container = e.detail.container; var pusher = container.lookup('pusher:main'), session = container.lookup('service:session'), store = container.lookup('service:store'); pusher.bind('message:created', onMessageCreated(session, store)); }); })();
Make tree builder with root node (fix deprecation) Make tree builder with root node (fix deprecation in symfony 4.2) and maintain backwards compatibility
<?php namespace Corley\MaintenanceBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { if (method_exists(TreeBuilder::class, 'getRootNode')) { $treeBuilder = new TreeBuilder('corley_maintenance'); $rootNode = $treeBuilder->getRootNode(); } else { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('corley_maintenance'); } $rootNode ->children() ->scalarNode("page")->defaultValue(__DIR__ . "/../Resources/views/maintenance.html")->end() ->scalarNode("web")->defaultValue('%kernel.root_dir%/../web')->end() ->scalarNode("soft_lock")->defaultValue('soft.lock')->end() ->scalarNode("hard_lock")->defaultValue('hard.lock')->end() ->booleanNode("symlink")->defaultFalse()->end() ->arrayNode("whitelist") ->addDefaultsIfNotSet() ->children() ->variableNode('paths') ->defaultValue(array()) ->end() ->variableNode('ips') ->defaultValue(array()) ->end() ->end() ->end() ->end(); return $treeBuilder; } }
<?php namespace Corley\MaintenanceBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('corley_maintenance'); $rootNode ->children() ->scalarNode("page")->defaultValue(__DIR__ . "/../Resources/views/maintenance.html")->end() ->scalarNode("web")->defaultValue('%kernel.root_dir%/../web')->end() ->scalarNode("soft_lock")->defaultValue('soft.lock')->end() ->scalarNode("hard_lock")->defaultValue('hard.lock')->end() ->booleanNode("symlink")->defaultFalse()->end() ->arrayNode("whitelist") ->addDefaultsIfNotSet() ->children() ->variableNode('paths') ->defaultValue(array()) ->end() ->variableNode('ips') ->defaultValue(array()) ->end() ->end() ->end() ->end(); return $treeBuilder; } }
Use $eval to maintain state
<?php #YOLO namespace yolo; function yolisp($swag, array $env = []) { if (!is_array($swag)) { if (isset($env[$swag])) { return $env[$swag]; } else if (function_exists($swag)) { return $swag; } else { throw new \Exception("Could not find $swag in environment"); } } $eval = function ($swag) use ($env) { return yolisp($swag, $env); }; $command = $swag[0]; $args = array_slice($swag, 1); switch ($command) { case 'quote': return $args[0]; case 'lambda': list($arg_names, $body) = $args; return function (...$args) use ($arg_names, $body, $env) { foreach ($arg_names as $i => $arg_name) { $env[$arg_name] = $args[$i]; } return yolisp($body, $env); }; case 'new': list($class_name, $constructor_args) = $args; $evaluated_args = array_map($eval, $constructor_args); return new $class_name(...$evaluated_args); default: $func = $eval($command); $evaluated_args = array_map($eval, $args); return $func(...$evaluated_args); } }
<?php #YOLO namespace yolo; function yolisp($swag, array $env = []) { if (!is_array($swag)) { if (isset($env[$swag])) { return $env[$swag]; } else if (function_exists($swag)) { return $swag; } else { throw new \Exception("Could not find $swag in environment"); } } $command = $swag[0]; $args = array_slice($swag, 1); switch ($command) { case 'quote': return $args[0]; case 'lambda': list($arg_names, $body) = $args; return function (...$args) use ($arg_names, $body, $env) { foreach ($arg_names as $i => $arg_name) { $env[$arg_name] = $args[$i]; } return yolisp($body, $env); }; case 'new': list($class_name, $constructor_args) = $args; $evaluated_args = array_map('yolo\yolisp', $constructor_args); return new $class_name(...$evaluated_args); default: $func = yolisp($command); $evaluated_args = array_map('yolo\yolisp', $args); return $func(...$evaluated_args); } }
Return unicode from the server Fixes #18
import os import aiohttp import json from aiohttp import web from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR async def serve_api(request): url = '{}/{}/?{}'.format( KUDAGO_API_BASE_URL, request.match_info['path'], request.query_string, ) response = await aiohttp.get(url) body = await response.json() if isinstance(body, dict): for field in ('next', 'previous'): value = body.get(field) if value: body[field] = value.replace(KUDAGO_API_BASE_URL, '/api') return web.Response( text=json.dumps(body, ensure_ascii=False), content_type='application/json' ) async def serve_client(request): filepath = os.path.join(CLIENT_DIR, 'index.html') stat = os.stat(filepath) chunk_size = 256 * 1024 response = web.StreamResponse() response.content_type = 'text/html' response.last_modified = stat.st_mtime response.content_length = stat.st_size response.start(request) with open(filepath, 'rb') as f: chunk = f.read(chunk_size) while chunk: response.write(chunk) chunk = f.read(chunk_size) return response
import os import aiohttp import json from aiohttp import web from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR async def serve_api(request): url = '{}/{}/?{}'.format( KUDAGO_API_BASE_URL, request.match_info['path'], request.query_string, ) response = await aiohttp.get(url) body = await response.json() if isinstance(body, dict): for field in ('next', 'previous'): value = body.get(field) if value: body[field] = value.replace(KUDAGO_API_BASE_URL, '/api') return web.Response( text=json.dumps(body), content_type='application/json' ) async def serve_client(request): filepath = os.path.join(CLIENT_DIR, 'index.html') stat = os.stat(filepath) chunk_size = 256 * 1024 response = web.StreamResponse() response.content_type = 'text/html' response.last_modified = stat.st_mtime response.content_length = stat.st_size response.start(request) with open(filepath, 'rb') as f: chunk = f.read(chunk_size) while chunk: response.write(chunk) chunk = f.read(chunk_size) return response
Add aiohttpClient plus example usage Closes #20
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.rst', 'r', 'utf-8') as f: __README = f.read() with codecs_open('HISTORY.rst', 'r', 'utf-8') as f: __HISTORY = f.read() setup( name='jsonrpcclient', version='2.2.4', description='Send JSON-RPC requests', long_description=__README+'\n\n'+__HISTORY, author='Beau Barker', author_email='[email protected]', url='https://jsonrpcclient.readthedocs.io/', license='MIT', packages=['jsonrpcclient'], package_data={'jsonrpcclient': ['response-schema.json']}, include_package_data=True, install_requires=['future', 'jsonschema'], extras_require={ 'aiohttp': ['aiohttp'], 'requests': ['requests'], 'requests_security': ['requests[security]'], 'tornado': ['tornado'], 'unittest': ['requests', 'pyzmq', 'tornado', 'responses', \ 'testfixtures', 'mock'] 'websockets': ['websockets'], 'zmq': ['pyzmq'], }, classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ], )
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.rst', 'r', 'utf-8') as f: __README = f.read() with codecs_open('HISTORY.rst', 'r', 'utf-8') as f: __HISTORY = f.read() setup( name='jsonrpcclient', version='2.2.4', description='Send JSON-RPC requests', long_description=__README+'\n\n'+__HISTORY, author='Beau Barker', author_email='[email protected]', url='https://jsonrpcclient.readthedocs.io/', license='MIT', packages=['jsonrpcclient'], package_data={'jsonrpcclient': ['response-schema.json']}, include_package_data=True, install_requires=['future', 'jsonschema'], extras_require={ 'requests': ['requests'], 'requests_security': ['requests[security]'], 'zmq': ['pyzmq'], 'tornado': ['tornado'], 'unittest': ['requests', 'pyzmq', 'tornado', 'responses', \ 'testfixtures', 'mock'] }, classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ], )
Increase blog slug max length
from datetime import datetime from django import forms from django.utils.translation import ugettext_lazy as _ from pinax.apps.blog.models import Post class BlogForm(forms.ModelForm): slug = forms.SlugField( max_length = 40, help_text = _("a short version of the title consisting only of letters, numbers, underscores and hyphens."), ) class Meta: model = Post exclude = [ "author", "creator_ip", "created_at", "updated_at", "publish", ] def __init__(self, user=None, *args, **kwargs): self.user = user super(BlogForm, self).__init__(*args, **kwargs) def clean_slug(self): if not self.instance.pk: if Post.objects.filter(author=self.user, slug=self.cleaned_data["slug"]).exists(): raise forms.ValidationError(u"This field must be unique") return self.cleaned_data["slug"] try: post = Post.objects.get( author = self.user, created_at__month = self.instance.created_at.month, created_at__year = self.instance.created_at.year, slug = self.cleaned_data["slug"] ) if post != self.instance: raise forms.ValidationError(u"This field must be unique") except Post.DoesNotExist: pass return self.cleaned_data["slug"]
from datetime import datetime from django import forms from django.utils.translation import ugettext_lazy as _ from pinax.apps.blog.models import Post class BlogForm(forms.ModelForm): slug = forms.SlugField( max_length = 20, help_text = _("a short version of the title consisting only of letters, numbers, underscores and hyphens."), ) class Meta: model = Post exclude = [ "author", "creator_ip", "created_at", "updated_at", "publish", ] def __init__(self, user=None, *args, **kwargs): self.user = user super(BlogForm, self).__init__(*args, **kwargs) def clean_slug(self): if not self.instance.pk: if Post.objects.filter(author=self.user, slug=self.cleaned_data["slug"]).exists(): raise forms.ValidationError(u"This field must be unique") return self.cleaned_data["slug"] try: post = Post.objects.get( author = self.user, created_at__month = self.instance.created_at.month, created_at__year = self.instance.created_at.year, slug = self.cleaned_data["slug"] ) if post != self.instance: raise forms.ValidationError(u"This field must be unique") except Post.DoesNotExist: pass return self.cleaned_data["slug"]
Correct the name of the spider
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem class SuperAmericaSpider(scrapy.Spider): name = "speedway" allowed_domains = ["www.speedway.com"] start_urls = ( 'https://www.speedway.com/GasPriceSearch', ) def parse(self, response): yield scrapy.Request( 'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity', callback=self.parse_search, method='POST', body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}', headers={ 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json', } ) def parse_search(self, response): data = json.loads(response.body_as_unicode()) for store in data: properties = { 'addr:full': store['address'], 'addr:city': store['city'], 'addr:state': store['state'], 'addr:postcode': store['zip'], 'phone': store['phoneNumber'], 'ref': store['costCenterId'], } lon_lat = [ store['longitude'], store['latitude'], ] yield GeojsonPointItem( properties=properties, lon_lat=lon_lat, )
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem class SuperAmericaSpider(scrapy.Spider): name = "superamerica" allowed_domains = ["superamerica.com"] start_urls = ( 'https://www.speedway.com/GasPriceSearch', ) def parse(self, response): yield scrapy.Request( 'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity', callback=self.parse_search, method='POST', body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}', headers={ 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json', } ) def parse_search(self, response): data = json.loads(response.body_as_unicode()) for store in data: properties = { 'addr:full': store['address'], 'addr:city': store['city'], 'addr:state': store['state'], 'addr:postcode': store['zip'], 'phone': store['phoneNumber'], 'ref': store['costCenterId'], } lon_lat = [ store['longitude'], store['latitude'], ] yield GeojsonPointItem( properties=properties, lon_lat=lon_lat, )
Set BroadCastConfig width and height to Integers, and check for null values; return -1 if null. This allows us to avoid the problem of ints defaulting to 0 which messes up the default settings for screen width/height
package io.cine.android; import android.util.Log; /** * Created by thomas on 1/16/15. */ public class BroadcastConfig { private Integer width; private Integer height; private String requestedCamera; private String lockedOrientation; public int getWidth() { if (width == null){ return -1; }else{ return width; } } public void setWidth(int width) { this.width = width; } public int getHeight() { if (height == null){ return -1; }else{ return height; } } public void setHeight(int height) { this.height = height; } public String getLockedOrientation() { return lockedOrientation; } public void lockOrientation(String lockedOrientation) { if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){ this.lockedOrientation = lockedOrientation; } else { throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\""); } } public String getRequestedCamera() { return requestedCamera; } public void selectCamera(String camera) { if(camera.equals("back") || camera.equals("front") || camera == null){ this.requestedCamera = camera; } else { throw new RuntimeException("Camera must be \"front\" or \"back\""); } } }
package io.cine.android; import android.util.Log; /** * Created by thomas on 1/16/15. */ public class BroadcastConfig { private int width; private int height; private String requestedCamera; private String lockedOrientation; public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getLockedOrientation() { return lockedOrientation; } public void lockOrientation(String lockedOrientation) { if(lockedOrientation.equals("landscape") || lockedOrientation.equals("portrait") || lockedOrientation == null){ this.lockedOrientation = lockedOrientation; } else { throw new RuntimeException("Orientation must be \"landscape\" or \"portrait\""); } } public String getRequestedCamera() { return requestedCamera; } public void selectCamera(String camera) { if(camera.equals("back") || camera.equals("front") || camera == null){ this.requestedCamera = camera; } else { throw new RuntimeException("Camera must be \"front\" or \"back\""); } } }
Stop rendering after delay on first slide
/*global shower*/ // Start the app require( ['detector', 'app', 'container', 'renderer'], function ( Detector, app, container, renderer ) { if ( ! Detector.webgl ) { Detector.addGetWebGLMessage(); container.innerHTML = ""; } app.init(); app.draw(); var lastSlideNumber = -1; var rendering = false; var tick = function() { window.requestAnimationFrame( tick ); if ( shower.isSlideMode() ) { var slideNumber = shower.getCurrentSlideNumber(); if ( slideNumber !== lastSlideNumber ) { // Have changed slide lastSlideNumber = slideNumber; // Check for presence of threejs container in new slide var slideId = shower.getSlideHash( slideNumber ).slice( 1 ); var c = document.querySelector( "[id='" + slideId + "'] .threejs-container" ); if ( c ) { rendering = true; renderer.setContainer( c ); } else { rendering = false; } // Set parameters for specific slide if ( slideNumber === 0 ) { app.spin = true; } if ( slideNumber === 1 ) { setTimeout( function() { rendering = false; }, 1500 ); app.spin = false; } } if ( rendering ) { app.draw(); } } }; tick(); } );
/*global shower*/ // Start the app require( ['detector', 'app', 'container', 'renderer'], function ( Detector, app, container, renderer ) { if ( ! Detector.webgl ) { Detector.addGetWebGLMessage(); container.innerHTML = ""; } app.init(); app.draw(); var lastSlideNumber = -1; var rendering = false; var tick = function() { window.requestAnimationFrame( tick ); if ( shower.isSlideMode() ) { var slideNumber = shower.getCurrentSlideNumber(); if ( slideNumber !== lastSlideNumber ) { // Have changed slide lastSlideNumber = slideNumber; // Check for presence of threejs container in new slide var slideId = shower.getSlideHash( slideNumber ).slice( 1 ); var c = document.querySelector( "[id='" + slideId + "'] .threejs-container" ); if ( c ) { rendering = true; renderer.setContainer( c ); } else { rendering = false; } // Set parameters for specific slide if ( slideNumber === 0 ) { app.spin = true; } if ( slideNumber === 1 ) { app.spin = false; } } if ( rendering ) { app.draw(); } } }; tick(); } );
Add else to search listener function in Search Service for readability.
'use strict'; module.exports = function(app) { app.factory('SearchService', ['$rootScope', function($rs) { let searchResults = []; let searchListener = function(prop, searchArray, $input) { let inputStr; let matchFound = false; let matchExists = false; let objIndex; $input.on('keyup', () => { searchArray.filter((obj) => { inputStr = $input.val().toUpperCase(); objIndex = searchResults.indexOf(obj); obj[prop] = obj[prop].toUpperCase(); obj[prop].indexOf(inputStr) > -1 ? matchFound = true : matchFound = false; objIndex > -1 ? matchExists = true : matchExists = false; $rs.$apply(() => { if (inputStr.length < 1) { return searchResults.forEach((result) => { searchResults.splice(searchResults.indexOf(result), 1); }); } if (matchFound === false && matchExists) searchResults.splice(objIndex, 1); if (matchFound) { if (matchExists) return; else searchResults.push(obj); } }); }); }); }; return { searchListener: searchListener, searchResults: searchResults, } }]); };
'use strict'; module.exports = function(app) { app.factory('SearchService', ['$rootScope', function($rs) { let searchResults = []; let searchListener = function(prop, searchArray, $input) { let inputStr; let matchFound = false; let matchExists = false; let objIndex; $input.on('keyup', () => { searchArray.filter((obj) => { inputStr = $input.val().toUpperCase(); objIndex = searchResults.indexOf(obj); obj[prop] = obj[prop].toUpperCase(); obj[prop].indexOf(inputStr) > -1 ? matchFound = true : matchFound = false; objIndex > -1 ? matchExists = true : matchExists = false; $rs.$apply(() => { if (inputStr.length < 1) { return searchResults.forEach((result) => { searchResults.splice(searchResults.indexOf(result), 1); }); } if (matchFound === false && matchExists) searchResults.splice(objIndex, 1); if (matchFound) { if (matchExists) return; searchResults.push(obj); } }); }); }); }; return { searchListener: searchListener, searchResults: searchResults, } }]); };
Fix for crazy routes issue
<?php namespace Chula\ControllerProvider; use Silex\Application; use Silex\ControllerProviderInterface; use \Michelf\Markdown; use Chula\Tools\Encryption; class HomePage implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/', function () use ($app) { if (isset($app['config']['homepage_type']) && $app['config']['homepage_type'] != 'list') { return $app['twig']->render('user_home.twig'); } // grab all items in our content dir $pageNames = array(); if (file_exists($app['config']['location']['published'])) { $pageNames = array_diff(scandir($app['config']['location']['published']), array('..', '.')); } $pages = array(); //@todo this should be in a service foreach ($pageNames as $page) { $content = file_get_contents($app['config']['location']['published'].'/'.$page); if ($app['config']['encrypt']) { // Need to decrypt the content first if we're set to use encryption $content = Encryption::decrypt($content); } $html = Markdown::defaultTransform($content); $pages[$page]['slug'] = $page; $pages[$page]['content'] = $html; } return $app['twig']->render('user_home.twig', array('pages' => $pages)); })->bind('home'); return $controllers; } }
<?php namespace Chula\ControllerProvider; use Silex\Application; use Silex\ControllerProviderInterface; use \Michelf\Markdown; use Chula\Tools\Encryption; class HomePage implements ControllerProviderInterface { public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get('/', function () use ($app) { if (isset($app['config']['homepage_type']) && $app['config']['homepage_type'] != 'list') { return $app['twig']->render('user_home.twig'); } // grab all items in our content dir $pageNames = array(); if (file_exists($app['config']['location']['published'])) { $pageNames = array_diff(scandir($app['config']['location']['published']), array('..', '.')); } $pages = array(); //@todo this should be in a service foreach ($pageNames as $page) { $content = file_get_contents($app['config']['location']['published'].'/'.$page); if ($app['config']['encrypt']) { // Need to decrypt the content first if we're set to use encryption $content = Encryption::decrypt($content); } $html = Markdown::defaultTransform($content); $pages[$page]['slug'] = $page; $pages[$page]['content'] = $html; } return $app['twig']->render('user_home.twig', array('pages' => $pages)); })->bind('admin'); return $controllers; } }
Fix deleting S3 files after they are uploaded
(function(Rubeus) { Rubeus.cfg.s3 = { uploadMethod: 'PUT', uploadUrl: null, uploadAdded: function(file, item) { var self = this; var parent = self.getByID(item.parentID); var name = file.name; // Make it possible to upload into subfolders while (parent.depth > 1 && !parent.isAddonRoot) { name = parent.name + '/' + name; parent = self.getByID(parent.parentID); } file.destination = name; self.dropzone.options.signedUrlFrom = parent.urls.upload; }, uploadSending: function(file, formData, xhr) { xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream'); xhr.setRequestHeader('x-amz-acl', 'private'); }, uploadSuccess: function(file, item, data) { // Update the added item's urls and permissions item.urls = { 'delete': nodeApiUrl + 's3/delete/' + file.destination + '/', 'download': nodeApiUrl + 's3/download/' + file.destination + '/', 'view': '/' + nodeId + '/s3/view/' + file.destination + '/' }; var parent = this.getByID(item.parentID); item.permissions = parent.permissions; this.updateItem(item); } }; })(Rubeus);
(function(Rubeus) { Rubeus.cfg.s3 = { uploadMethod: 'PUT', uploadUrl: null, uploadAdded: function(file, item) { var self = this; var parent = self.getByID(item.parentID); var name = file.name; // Make it possible to upload into subfolders while (parent.depth > 1 && !parent.isAddonRoot) { name = parent.name + '/' + name; parent = self.getByID(parent.parentID); } file.destination = name; self.dropzone.options.signedUrlFrom = parent.urls.upload; }, uploadSending: function(file, formData, xhr) { xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream'); xhr.setRequestHeader('x-amz-acl', 'private'); }, uploadSuccess: function(file, item, data) { item.urls = { 'delete': nodeApiUrl + 's3/delete/' + file.destination + '/', 'download': nodeApiUrl + 's3/download/' + file.destination + '/', 'view': '/' + nodeId + '/s3/view/' + file.destination + '/' } } }; })(Rubeus);
Return data as list if field is unset
import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] try: field = terms[1] except: field = None url = os.getenv('VAULT_ADDR') if not url: raise AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (key)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise AnsibleError('Unable to read %s from vault: %s' % (key, e)) except: raise AnsibleError('Unable to read %s from vault' % key) result = json.loads(response.read()) return [result['data'][field]] if field is not None else [result['data']]
import os import urllib2 import json import sys from urlparse import urljoin from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): key = terms[0] try: field = terms[1] except: field = None url = os.getenv('VAULT_ADDR') if not url: raise AnsibleError('VAULT_ADDR environment variable is missing') token = os.getenv('VAULT_TOKEN') if not token: raise AnsibleError('VAULT_TOKEN environment variable is missing') request_url = urljoin(url, "v1/%s" % (key)) try: headers = { 'X-Vault-Token' : token } req = urllib2.Request(request_url, None, headers) response = urllib2.urlopen(req) except urllib2.HTTPError as e: raise AnsibleError('Unable to read %s from vault: %s' % (key, e)) except: raise AnsibleError('Unable to read %s from vault' % key) result = json.loads(response.read()) return [result['data'][field]] if field is not None else result['data']
Complete the data print interface.
#!/usr/bin/env python # -*- coding: utf-8 -* # # @author XU Kai([email protected]) # @date 2016-12-04 星期日 # # # #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息 # # # import os import sys import math import codecs import serial sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1) def convert(hexVal): return codecs.encode(hexVal, 'hex') while True: data = sensor.read(size=1) if (data == b'\x55'): print('Get the data !') sensor.read(size=10) break print('trying', data) try: while True: data = sensor.read(size=11) if not len(data) == 11: print('Byte error !') break if data[1] == b'\x50': # print(convert(data[7])) pass # Angle Output. if (data[1] == b'\x53'): hexVal = [] for i in range(11): hexVal.append(convert(data[i])) print(hexVal) except KeyboardInterrupt: sensor.close() print('Close the sensor !')
#!/usr/bin/env python # -*- coding: utf-8 -* # # @author XU Kai([email protected]) # @date 2016-12-04 星期日 # # # #fileOverview 树莓派串口操作事件,用来输入和输出陀螺仪数据信息 # # # import os import sys import math import codecs import serial sensor = serial.Serial(port='/dev/ttyAMA0', baudrate='9600', timeout=1) def convert(hexVal): return int(codecs.encode(hexVal, 'hex'), 16) while True: data = sensor.read(size=1) if (data == b'\x55'): print('Get the data !') sensor.read(size=10) break print('trying', data) try: while True: data = sensor.read(size=11) if not len(data) == 11: print('Byte error !') break if data[1] == b'\x50': print(convert(data[7])) # Angle Output. if (data[1] == b'\x53'): pass ''' if data[1] == b'\x54': x = convert(data[2:4]) y = convert(data[4:6]) z = convert(data[6:8]) # print("Magnetic output:{}, {}, {}".format(x, y, z)) #Angle ''' # print("----", data[0], data[1]) except KeyboardInterrupt: sensor.close() print('Close the sensor !')
Add parsing of simple key-value query params (sort, filter, etc.)
import Ember from 'ember'; export default Ember.Mixin.create({ /** Parse the links in the JSONAPI response and convert to a meta-object */ normalizeQueryResponse(store, clazz, payload) { const result = this._super(...arguments); result.meta = result.meta || {}; if (payload.links) { result.meta.pagination = this.createPageMeta(payload.links); } return result; }, /** Transforms link URLs to objects containing metadata E.g. links: { previous: '/streets?page[number]=1&page[size]=10&sort=name next: '/streets?page[number]=3&page[size]=10&sort=name } will be converted to meta: { previous: { number: 1, size: 10 }, next: { number: 3, size: 10 }, sort: 'name' } */ createPageMeta(data) { let meta = {}; Object.keys(data).forEach(type => { const link = data[type]; meta[type] = {}; let a = document.createElement('a'); a.href = link; a.search.slice(1).split('&').forEach(pairs => { const [param, value] = pairs.split('='); if (param === 'page[number]') { meta[type].number = parseInt(value); } else if (param === 'page[size]') { meta[type].size = parseInt(value); } else { meta[param] = value; } }); a = null; }); return meta; } });
import Ember from 'ember'; export default Ember.Mixin.create({ /** Parse the links in the JSONAPI response and convert to a meta-object */ normalizeQueryResponse(store, clazz, payload) { const result = this._super(...arguments); result.meta = result.meta || {}; if (payload.links) { result.meta.pagination = this.createPageMeta(payload.links); } return result; }, /** Transforms link URLs to objects containing metadata E.g. links: { previous: '/streets?page[number]=1&page[size]=10 next: '/streets?page[number]=3&page[size]=10 } will be converted to meta: { previous: { number: 1, size: 10 }, next: { number: 3, size: 10 } } */ createPageMeta(data) { let meta = {}; Object.keys(data).forEach(type => { const link = data[type]; meta[type] = {}; let a = document.createElement('a'); a.href = link; a.search.slice(1).split('&').forEach(pairs => { const [param, value] = pairs.split('='); if (param === 'page[number]') { meta[type].number = parseInt(value); } if (param === 'page[size]') { meta[type].size = parseInt(value); } }); a = null; }); return meta; } });
Fix mconsole options array values
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules' => 'array', ]; /** * Get option value by its key * * @param string $key * @return mixed */ public static function getByKey($key) { if ($option = self::getCached()->where('key', $key)->first()) { if (count($option->options) >= 2) { if (isset($option->options[0]) && isset($option->options[1])) { switch ($option->value) { case '1': return true; case '0': return false; } } else { return $option->value; } } else { if (is_array($option->rules) && in_array('integer', $option->rules)) { return (int) $option->value; } else { return $option->value; } } } else { return null; } } }
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules' => 'array', ]; /** * Get option value by its key * * @param string $key * @return mixed */ public static function getByKey($key) { if ($option = self::getCached()->where('key', $key)->first()) { if (count($option->options) == 2) { if (isset($option->options[0]) && isset($option->options[1])) { switch ($option->value) { case '1': return true; case '0': return false; } } else { return $option->value; } } else { if (in_array('integer', $option->rules)) { return (int) $option->value; } else { return $option->value; } } } else { return null; } } }
Add index assertion during segment exit and fix segment cleanup logic
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) def __getitem__(self, item): print('\tGET<{}> {}: {}'.format(self.idx, item, self.data[item][1])) return self.data[item][1] def __contains__(self, item): return item in self.data def __iter__(self): for key, value in self.data.items(): yield key, value def enter(self): print('\tINCR<{}> -> <{}>'.format(self.idx, self.idx + 1)) self.idx += 1 def exit(self): assert self.idx > 0, 'Cannot exit lowest stack segment' print('\tDECR<{}> -> <{}>'.format(self.idx, self.idx - 1)) self.data = { key: value for key, value in self.data.items() if value[1] != self.idx key: value for key, value in self.data.items() if value[0] != self.idx } self.idx -= 1 class StackFrameTerminator(object): def __init__(self, target_arg=None): self.target_arg = target_arg class StackScopeTerminator(object): pass
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) def __getitem__(self, item): print('\tGET<{}> {}: {}'.format(self.idx, item, self.data[item][1])) return self.data[item][1] def __contains__(self, item): return item in self.data def __iter__(self): for key, value in self.data.items(): yield key, value def enter(self): print('\tINCR<{}> -> <{}>'.format(self.idx, self.idx + 1)) self.idx += 1 def exit(self): print('\tDECR<{}> -> <{}>'.format(self.idx, self.idx - 1)) self.data = { key: value for key, value in self.data.items() if value[1] != self.idx } self.idx -= 1 class StackFrameTerminator(object): def __init__(self, target_arg=None): self.target_arg = target_arg class StackScopeTerminator(object): pass
Save message before send sms has been added
const Factories = use('core/factories'); const Config = use('config'); const NotificationSmsFactory = Factories('NotificationSms'); class NotificationSms { constructor() { this.provider = require(`./providers/${Config.smsGate.providers[Config.smsGate.active].name}`); } send({ accounts_senders_id = null, sender_title = 'automatic message', body, recipient_phone, accounts_recipient_id = null, type = 'automatic' }) { let saveData = { accounts_senders_id : accounts_senders_id, body : body, recipient_phone : recipient_phone, accounts_recipient_id : accounts_recipient_id, type : type, sender_title : sender_title }; return NotificationSmsFactory.new(saveData) .then((notificationSms) => { return notificationSms.save(); }) .then((notificationSms)=>{ return this.provider.sendSms(recipient_phone, body) .then(response => { notificationSms.status = response.status; notificationSms.provider_sms_id = response.providerSmsId; return notificationSms.save(); }); }); } getStatus(id) { return this.provider.getSmsStatus(id) .then(response => NotificationSmsFactory.get({provider_sms_id: id})) .then((notificationSms) => { notificationSms.status = response[0].status; return notificationSms.save(); }); } getSmsBalance() { return this.provider.getSmsBalance(); } } module.exports = NotificationSms;
const Factories = use('core/factories'); const Config = use('config'); const NotificationSmsFactory = Factories('NotificationSms'); class NotificationSms { constructor() { this.provider = require(`./providers/${Config.smsGate.providers[Config.smsGate.active].name}`); } send({ accounts_senders_id = null, sender_title = 'automatic message', body, recipient_phone, accounts_recipient_id = null, type = 'automatic' }) { return this.provider.sendSms(recipient_phone, body) .then(response => { let saveData = { status : response.status, accounts_senders_id : accounts_senders_id, provider_sms_id : response.providerSmsId, body : body, recipient_phone : recipient_phone, accounts_recipient_id : accounts_recipient_id, type : type, sender_title : sender_title }; return NotificationSmsFactory .new(saveData) .then((notificationSms) => notificationSms.save()); }); } getStatus(id) { return this.provider.getSmsStatus(id) .then(response => NotificationSmsFactory.get({provider_sms_id: id})) .then((notificationSms) => { notificationSms.status = response[0].status; return notificationSms.save(); }); } getSmsBalance() { return this.provider.getSmsBalance(); } } module.exports = NotificationSms;
Fix catalog proptype on homepage
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Link from '../link' import Section from './section' import CatalogPreview from '../catalog-preview' const Catalogs = ({ catalogs, t }) => ( <Section title={t('catalogsSectionTitle')}> <div className='catalogs'> {catalogs.map(catalog => ( <div key={catalog._id} className='catalog'> <CatalogPreview catalog={catalog} /> </div> ))} </div> <Link href='/catalogs'> <a>{t('catalogsLink')}</a> </Link> <style jsx>{` @import 'colors'; .catalogs { display: flex; flex-wrap: wrap; justify-content: center; } .catalog { margin: 10px 20px; @media (max-width: 551px) { margin: 10px 0; flex-grow: 1; } } a { color: $darkgrey; display: block; margin-top: 1em; &:focus, &:hover { color: $black; } } `}</style> </Section> ) Catalogs.propTypes = { catalogs: PropTypes.arrayOf(PropTypes.shape({ _id: PropTypes.string.isRequired })).isRequired, t: PropTypes.func.isRequired } export default translate('home')(Catalogs)
import React from 'react' import PropTypes from 'prop-types' import { translate } from 'react-i18next' import Link from '../link' import Section from './section' import CatalogPreview from '../catalog-preview' const Catalogs = ({ catalogs, t }) => ( <Section title={t('catalogsSectionTitle')}> <div className='catalogs'> {catalogs.map(catalog => ( <div key={catalog._id} className='catalog'> <CatalogPreview catalog={catalog} /> </div> ))} </div> <Link href='/catalogs'> <a>{t('catalogsLink')}</a> </Link> <style jsx>{` @import 'colors'; .catalogs { display: flex; flex-wrap: wrap; justify-content: center; } .catalog { margin: 10px 20px; @media (max-width: 551px) { margin: 10px 0; flex-grow: 1; } } a { color: $darkgrey; display: block; margin-top: 1em; &:focus, &:hover { color: $black; } } `}</style> </Section> ) Catalogs.propTypes = { catalogs: PropTypes.arrayOf({ _id: PropTypes.string.isRequired }).isRequired, t: PropTypes.func.isRequired } export default translate('home')(Catalogs)
Use ~/.snakewatch/default.json if exists, fallback on built-in.
import json import os import importlib class Config(object): available_actions = {} def __init__(self, cfg, *args): if isinstance(cfg, str): fp = open(cfg, 'r') self.cfg = json.load(fp) fp.close() elif isinstance(cfg, list): self.cfg = cfg self.actions = [] self.check_actions() def check_actions(self): for entry in self.cfg: name = entry['action'] module = importlib.import_module('actions.%s' % name) if name not in Config.available_actions: action = '%sAction' % name Config.available_actions[name] = getattr(module, action) self.actions.append(Config.available_actions[name](entry)) def match(self, line): for action in self.actions: if action.matches(line): result = action.run_on(line) if result is None: return '' return result return line class DefaultConfig(Config): def __init__(self): user_default = os.path.expanduser(os.path.join('~', '.snakewatch', 'default.json')) if os.path.exists(user_default): cfg = user_default else: cfg = [ { 'regex': '.*', 'action': 'Print', }, ] super(DefaultConfig, self).__init__(cfg)
import json import importlib class Config(object): available_actions = {} def __init__(self, cfg, *args): if isinstance(cfg, str): fp = open(cfg, 'r') self.cfg = json.load(fp) fp.close() elif isinstance(cfg, list): self.cfg = cfg self.actions = [] self.check_actions() def check_actions(self): for entry in self.cfg: name = entry['action'] module = importlib.import_module('actions.%s' % name) if name not in Config.available_actions: action = '%sAction' % name Config.available_actions[name] = getattr(module, action) self.actions.append(Config.available_actions[name](entry)) def match(self, line): for action in self.actions: if action.matches(line): result = action.run_on(line) if result is None: return '' return result return line class DefaultConfig(Config): def __init__(self): super(DefaultConfig, self).__init__([ { 'regex': '.*', 'action': 'Print', }, ])
Use searchRoute property instead of function
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' + '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>'; return { restrict: 'E', transclude: true, scope: { subject: '=', configuration: '=' }, template: tpl, controller: function($scope, $http, $attrs) { // Get the object by search term $scope.getObject = function(term) { return $http.get(Routing.generate($scope.configuration.searchRoute, [], true), { params: { term: term } }).then(function(response){ return response.data.map(function(item){ return item; }); }); }; // Select the object $scope.onSelect = function(item, model, label) { if (angular.isUndefined($scope.subject.right.value)) { $scope.subject.right.value = []; } if ($scope.subject.right.value.indexOf(item.id) == -1) { $scope.subject.right.value.push(item.id); $scope.configuration.add(item); } $scope.search = null; }; } }; }) ;
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' + '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>'; return { restrict: 'E', transclude: true, scope: { subject: '=', configuration: '=' }, template: tpl, controller: function($scope, $http, $attrs) { // Get the object by search term $scope.getObject = function(term) { return $http.get(Routing.generate($scope.configuration.searchRoute(), [], true), { params: { term: term } }).then(function(response){ return response.data.map(function(item){ return item; }); }); }; // Select the object $scope.onSelect = function(item, model, label) { if (angular.isUndefined($scope.subject.right.value)) { $scope.subject.right.value = []; } if ($scope.subject.right.value.indexOf(item.id) == -1) { $scope.subject.right.value.push(item.id); $scope.configuration.add(item); } $scope.search = null; }; } }; }) ;
Check media_type instead of class type The `parsers` list should contain instances, not classes.
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': '[email protected]'}, content_type='text/plain')) parser = negotiation.select_parser(requestWithQueryParam, parsers) assert parser.media_type == 'application/x-www-form-urlencoded' requestWithoutQueryParam = Request( factory.post('/', {'email': '[email protected]'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': '[email protected]'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': '[email protected]'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': '[email protected]'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': '[email protected]'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
Fix clean logs script wrong date parsing
#!/usr/bin/env python # encoding: utf-8 import os import datetime from config import USER_DIRECTORY, LOG_DIRECTORY_NAME, STORE_LOGS NOW = datetime.datetime.now() def clean_log(filepath): delete = False with open(filepath) as fp: line = fp.readline() try: date_str = ' '.join(line.split()[:2]) log_start = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S,%f') except StandardError: delete = True else: log_age = NOW - log_start if log_age.hours >= STORE_LOGS: delete = True if delete: print "Deleting {}".format(filepath) os.remove(filepath) def main(): for username in os.listdir(USER_DIRECTORY): log_dir = os.path.join(USER_DIRECTORY, username, LOG_DIRECTORY_NAME) if not os.path.exists(log_dir): continue for log in os.listdir(log_dir): clean_log(os.path.join(log_dir, log)) if __name__ == '__main__': main()
#!/usr/bin/env python # encoding: utf-8 import os import datetime from config import USER_DIRECTORY, LOG_DIRECTORY_NAME, STORE_LOGS NOW = datetime.datetime.now() def clean_log(filepath): delete = False with open(filepath) as fp: line = fp.readline() try: date_str = ' '.join(line.split()[:1]) log_start = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S,%f') except StandardError: delete = True else: log_age = NOW - log_start if log_age.hours >= STORE_LOGS: delete = True if delete: print "Deleting {}".format(filepath) os.remove(filepath) def main(): for username in os.listdir(USER_DIRECTORY): log_dir = os.path.join(USER_DIRECTORY, username, LOG_DIRECTORY_NAME) if not os.path.exists(log_dir): continue for log in os.listdir(log_dir): clean_log(os.path.join(log_dir, log)) if __name__ == '__main__': main()
Remove extra wait time in set volume
const Effect = require('./Effect'); /** * Affect the volume of an effect chain. */ class VolumeEffect extends Effect { /** * Default value to set the Effect to when constructed and when clear'ed. * @const {number} */ get DEFAULT_VALUE () { return 100; } /** * Return the name of the effect. * @type {string} */ get name () { return 'volume'; } /** * Initialize the Effect. * Effects start out uninitialized. Then initialize when they are first set * with some value. * @throws {Error} throws when left unimplemented */ initialize () { this.inputNode = this.audioEngine.audioContext.createGain(); this.outputNode = this.inputNode; this.initialized = true; } /** * Set the effects value. * @private * @param {number} value - new value to set effect to */ _set (value) { this.value = value; const {gain} = this.outputNode; const {currentTime, DECAY_DURATION} = this.audioEngine; gain.linearRampToValueAtTime(value / 100, currentTime + DECAY_DURATION); } /** * Clean up and disconnect audio nodes. */ dispose () { if (!this.initialized) { return; } this.outputNode.disconnect(); this.inputNode = null; this.outputNode = null; this.target = null; this.initialized = false; } } module.exports = VolumeEffect;
const Effect = require('./Effect'); /** * Affect the volume of an effect chain. */ class VolumeEffect extends Effect { /** * Default value to set the Effect to when constructed and when clear'ed. * @const {number} */ get DEFAULT_VALUE () { return 100; } /** * Return the name of the effect. * @type {string} */ get name () { return 'volume'; } /** * Initialize the Effect. * Effects start out uninitialized. Then initialize when they are first set * with some value. * @throws {Error} throws when left unimplemented */ initialize () { this.inputNode = this.audioEngine.audioContext.createGain(); this.outputNode = this.inputNode; this.initialized = true; } /** * Set the effects value. * @private * @param {number} value - new value to set effect to */ _set (value) { this.value = value; const {gain} = this.outputNode; const {currentTime, DECAY_WAIT, DECAY_DURATION} = this.audioEngine; gain.linearRampToValueAtTime(value / 100, currentTime + DECAY_WAIT + DECAY_DURATION); } /** * Clean up and disconnect audio nodes. */ dispose () { if (!this.initialized) { return; } this.outputNode.disconnect(); this.inputNode = null; this.outputNode = null; this.target = null; this.initialized = false; } } module.exports = VolumeEffect;
Stop looping to do nothing, just pass.
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
Add replaceable slot tag, for upgrades that can be replaced without returning the existing upgrade
package com.elmakers.mine.bukkit.wand; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.Mage; public class WandUpgradeSlot { private final String slotType; private boolean hidden = false; private boolean swappable = false; private boolean replaceable = false; private Wand slotted; public WandUpgradeSlot(String slotType) { this.slotType = slotType; } public WandUpgradeSlot(String configKey, ConfigurationSection config) { slotType = config.getString("type", configKey); hidden = config.getBoolean("hidden", false); swappable = config.getBoolean("swappable", false); replaceable = config.getBoolean("replaceable", false); } public Wand getSlotted() { return slotted; } public boolean addSlotted(Wand upgrade, Mage mage) { String slotType = upgrade.getSlot(); if (slotType == null || slotType.isEmpty()) { return false; } if (!slotType.equals(slotType)) { return false; } if (slotted == null || replaceable) { slotted = upgrade; return true; } if (!swappable || mage == null) { return false; } mage.giveItem(slotted.getItem()); slotted = upgrade; return true; } public boolean isHidden() { return hidden; } public String getType() { return slotType; } }
package com.elmakers.mine.bukkit.wand; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.magic.Mage; public class WandUpgradeSlot { private final String slotType; private boolean hidden = false; private boolean swappable = false; private Wand slotted; public WandUpgradeSlot(String slotType) { this.slotType = slotType; } public WandUpgradeSlot(String configKey, ConfigurationSection config) { slotType = config.getString("type", configKey); hidden = config.getBoolean("hidden", false); swappable = config.getBoolean("swappable", false); } public Wand getSlotted() { return slotted; } public boolean addSlotted(Wand upgrade, Mage mage) { String slotType = upgrade.getSlot(); if (slotType == null || slotType.isEmpty()) { return false; } if (!slotType.equals(slotType)) { return false; } if (slotted == null) { slotted = upgrade; return true; } if (!swappable || mage == null) { return false; } mage.giveItem(slotted.getItem()); slotted = upgrade; return true; } public boolean isHidden() { return hidden; } public String getType() { return slotType; } }
Allow passing of a hostname for the docs server.
module.exports = function(grunt) { 'use strict'; var host = grunt.option('host') || 'localhost'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-traceur'); grunt.initConfig({ connect: { docs: { options: { keepalive: true, hostname: host, open: 'http://' + host + ':8000/docs' } } }, karma: { all: { options: { browsers: ['PhantomJS'], files: [ 'dist/skate.js', 'tests/skate.js' ], frameworks: ['mocha', 'sinon-chai'], singleRun: true } } }, traceur: { options: { blockBinding: true }, all: { files: { 'dist/skate.js': 'src/skate.js' } } }, uglify: { all: { files: { 'dist/skate.min.js': 'dist/skate.js' } } }, watch: { test: { files: ['src/*.js'], tasks: ['dist'] } } }); grunt.registerTask('build', 'Runs the tests and builds the dist.', ['test']); grunt.registerTask('dist', 'Builds the dist.', ['traceur', 'uglify']); grunt.registerTask('docs', 'Runs the docs server.', ['connect:docs']) grunt.registerTask('test', 'Runs the tests.', ['dist', 'karma']); };
module.exports = function(grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-traceur'); grunt.initConfig({ connect: { docs: { options: { keepalive: true, open: 'http://localhost:8000/docs' } } }, karma: { all: { options: { browsers: ['PhantomJS'], files: [ 'dist/skate.js', 'tests/skate.js' ], frameworks: ['mocha', 'sinon-chai'], singleRun: true } } }, traceur: { options: { blockBinding: true }, all: { files: { 'dist/skate.js': 'src/skate.js' } } }, uglify: { all: { files: { 'dist/skate.min.js': 'dist/skate.js' } } }, watch: { test: { files: ['src/*.js'], tasks: ['dist'] } } }); grunt.registerTask('build', 'Runs the tests and builds the dist.', ['test']); grunt.registerTask('dist', 'Builds the dist.', ['traceur', 'uglify']); grunt.registerTask('docs', 'Runs the docs server.', ['connect:docs']) grunt.registerTask('test', 'Runs the tests.', ['dist', 'karma']); };
Fix bug with text/plain response
import random import yaml from flask import jsonify, Response, render_template class Which(object): def __init__(self, mime_type, args): self.mime_type = mime_type self.args = args @property def _excuse(self): stream = open("excuses.yaml", 'r') excuses = yaml.load(stream) return random.choice(excuses["excuses"]) def get_response(self): if self.mime_type == "application/json": return jsonify({ "excuse": self._excuse }), "/json/" elif self.mime_type == "application/xml": return Response( render_template('xml.xml', excuse=self._excuse), mimetype='text/xml' ), "/xml/" elif self.mime_type == "application/javascript" or "jsonp" in self.args: return Response( render_template('jsonp.js', excuse=self._excuse), mimetype='application/javascript' ), "/jsonp/" elif self.mime_type == "text/plain": return Response(self._excuse, mimetype='text/plain'), "/text/" else: return render_template('html.html', excuse=self._excuse), "/html/"
import random import yaml from flask import jsonify, Response, render_template class Which(object): def __init__(self, mime_type, args): self.mime_type = mime_type self.args = args @property def _excuse(self): stream = open("excuses.yaml", 'r') excuses = yaml.load(stream) return random.choice(excuses["excuses"]) def get_response(self): if self.mime_type == "application/json": return jsonify({ "excuse": self._excuse }), "/json/" elif self.mime_type == "application/xml": return Response( render_template('xml.xml', excuse=self._excuse), mimetype='text/xml' ), "/xml/" elif self.mime_type == "application/javascript" or "jsonp" in self.args: return Response( render_template('jsonp.js', excuse=self._excuse), mimetype='application/javascript' ), "/jsonp/" elif self.mime_type == "text/plain": return Response("Hello world", mimetype='text/plain'), "/text/" else: return render_template('html.html', excuse=self._excuse), "/html/"
Change content type when execute command
package com.decker.Essentials; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.decker.Essentials.Category.Category; import com.decker.Essentials.User.User; public class Center extends org.sipc.se.plugin.PluginImpl { Category category; public Center() { super(); this.category=Category.getInstance(); } @Override public void getResponse(HttpServletRequest request, HttpServletResponse response) { String url = request.getRequestURI(); String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1); OutputStream stream; try { stream = response.getOutputStream(); byte[] resource=null; if (target.matches(".*.exec")) { //dynamic generate User current=new User(request.getCookies()); response.setContentType("application/json"); resource = Command.Execute(current,request,response); } else { //static resource resource = ResourceManager.getInstance().getResource("Content/"+target); } if (resource.length == 0) { response.setStatus(404); } stream.write(resource); } catch (IOException e) { } } @Override public String getUrl() { return "Essentials"; } @Override public boolean onEnable() { // TODO Auto-generated method stub return true; } }
package com.decker.Essentials; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.decker.Essentials.Category.Category; import com.decker.Essentials.User.User; public class Center extends org.sipc.se.plugin.PluginImpl { Category category; public Center() { super(); this.category=Category.getInstance(); } @Override public void getResponse(HttpServletRequest request, HttpServletResponse response) { String url = request.getRequestURI(); String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1); OutputStream stream; try { stream = response.getOutputStream(); byte[] resource=null; if (target.matches(".*.exec")) { //dynamic generate User current=new User(request.getCookies()); resource = Command.Execute(current,request,response); } else { //static resource resource = ResourceManager.getInstance().getResource("Content/"+target); } if (resource.length == 0) { response.setStatus(404); } stream.write(resource); } catch (IOException e) { } } @Override public String getUrl() { return "Essentials"; } @Override public boolean onEnable() { // TODO Auto-generated method stub return true; } }
Add fileio.TextFile and use it when reading and writing text files in RDD and Context.
from __future__ import absolute_import, unicode_literals import logging from io import BytesIO, StringIO from . import codec from .file import File log = logging.getLogger(__name__) class TextFile(File): """ Derived from :class:`pysparkling.fileio.File`. :param file_name: Any text file name. Supports the schemes ``http://``, ``s3://`` and ``file://``. """ def __init__(self, file_name): File.__init__(self, file_name) def load(self, encoding='utf8'): """ Load the data from a file. :param encoding: (optional) The character encoding of the file. :returns: An ``io.StringIO`` instance. Use ``getvalue()`` to get a string. """ if type(self.codec) == codec.Codec and \ getattr(self.fs, 'load_text'): print(self.codec) stream = self.fs.load_text() else: stream = self.fs.load() stream = StringIO( self.codec.decompress(stream).read().decode(encoding) ) return stream def dump(self, stream=None, encoding='utf8'): """ Writes a stream to a file. :param stream: An ``io.StringIO`` instance. :param encoding: (optional) The character encoding of the file. :returns: self """ if stream is None: stream = StringIO() stream = self.codec.compress( BytesIO(stream.read().encode(encoding)) ) self.fs.dump(stream) return self
from __future__ import absolute_import, unicode_literals import logging from io import StringIO from . import codec from .file import File log = logging.getLogger(__name__) class TextFile(File): """ Derived from :class:`pysparkling.fileio.File`. :param file_name: Any text file name. Supports the schemes ``http://``, ``s3://`` and ``file://``. """ def __init__(self, file_name): File.__init__(self, file_name) def load(self, encoding='utf8'): """ Load the data from a file. :param encoding: (optional) The character encoding of the file. :returns: An ``io.StringIO`` instance. Use ``getvalue()`` to get a string. """ if type(self.codec) == codec.Codec and \ getattr(self.fs, 'load_text'): print(self.codec) stream = self.fs.load_text() else: stream = self.fs.load() stream = StringIO( self.codec.decompress(stream).read().decode(encoding) ) return stream def dump(self, stream=None, encoding='utf8'): """ Writes a stream to a file. :param stream: An ``io.StringIO`` instance. :param encoding: (optional) The character encoding of the file. :returns: self """ if stream is None: stream = StringIO() stream = self.codec.compress(stream.read().encode(encoding)) self.fs.dump(stream) return self
Check cb is a function before calling it
/* * stompit.connect * Copyright (c) 2013 Graham Daws <[email protected]> * MIT licensed */ var net = require('net'); var util = require('./util'); var Client = require('./client'); function connect(){ var args = net._normalizeConnectArgs(arguments); var options = util.extend({ host: 'localhost', connectHeaders: {} }, args[0]); if(options.port === undefined || typeof options.port === 'function'){ options.port = 61613; } var cb = args[1]; var client, socket, timeout; var cleanup = function(){ if(timeout){ clearTimeout(timeout); } client.removeListener('error', onError); client.removeListener('connect', onConnected); }; var onError = function(error){ cleanup(); if(typeof cb === "function"){ cb(error); } }; var onConnected = function(){ cleanup(); client.emit('socket-connect'); client.connect(util.extend({host: options.host}, options.connectHeaders), cb); }; if(options.hasOwnProperty('timeout')){ var timeout = setTimeout(function(){ client.destroy(client.createTransportError('connect timed out')); }, options.timeout); } socket = net.connect(options, onConnected); client = new Client(socket, options); client.on('error', onError); return client; } module.exports = connect;
/* * stompit.connect * Copyright (c) 2013 Graham Daws <[email protected]> * MIT licensed */ var net = require('net'); var util = require('./util'); var Client = require('./client'); function connect(){ var args = net._normalizeConnectArgs(arguments); var options = util.extend({ host: 'localhost', connectHeaders: {} }, args[0]); if(options.port === undefined || typeof options.port === 'function'){ options.port = 61613; } var cb = args[1]; var client, socket, timeout; var cleanup = function(){ if(timeout){ clearTimeout(timeout); } client.removeListener('error', onError); client.removeListener('connect', onConnected); }; var onError = function(error){ cleanup(); cb(error); }; var onConnected = function(){ cleanup(); client.emit('socket-connect'); client.connect(util.extend({host: options.host}, options.connectHeaders), cb); }; if(options.hasOwnProperty('timeout')){ var timeout = setTimeout(function(){ client.destroy(client.createTransportError('connect timed out')); }, options.timeout); } socket = net.connect(options, onConnected); client = new Client(socket, options); client.on('error', onError); return client; } module.exports = connect;
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <[email protected]>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
Return 400 for inexistant accounts
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) try: owner = Account.objects.get(slug=slug) except Account.DoesNotExist: return HttpResponse('Unknown account/slug', status=400) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, owner=owner, ) if not created: notification.processed = False notification.save() if not settings.MERCADOPAGO_ASYNC: notification.process() # TODO: Else add to some queue? return HttpResponse("<h1>200 OK</h1>", status=201)
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) owner = Account.objects.get(slug=slug) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, owner=owner, ) if not created: notification.processed = False notification.save() if not settings.MERCADOPAGO_ASYNC: notification.process() # TODO: Else add to some queue? return HttpResponse("<h1>200 OK</h1>", status=201)
Check if app is installed for user before displying Summary: Fixes T11595. Previously if a user didn't have permissions to view an application it would still appear in the application typeahead in various menus. This change will prevent that by checking if the app is installed for the viewer before displaying it as an option Test Plan: I went to the "Pin Applications" menu and typed in "Conpherence" and saw it appear as an option. I then went to the "Edit Policies" menu as an admin and removed permissions for my user to use Conpherence. Once I did that, it no longer showed up in the typeahead menu Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: Korvin, epriestley, yelirekim Maniphest Tasks: T11595 Differential Revision: https://secure.phabricator.com/D16518
<?php final class PhabricatorApplicationDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Applications'); } public function getPlaceholderText() { return pht('Type an application name...'); } public function getDatasourceApplicationClass() { return 'PhabricatorApplicationsApplication'; } public function loadResults() { $viewer = $this->getViewer(); $raw_query = $this->getRawQuery(); $results = array(); $applications = PhabricatorApplication::getAllInstalledApplications(); foreach ($applications as $application) { $uri = $application->getTypeaheadURI(); if (!$uri) { continue; } $is_installed = PhabricatorApplication::isClassInstalledForViewer( get_class($application), $viewer); if (!$is_installed) { continue; } $name = $application->getName().' '.$application->getShortDescription(); $img = 'phui-font-fa phui-icon-view '.$application->getIcon(); $results[] = id(new PhabricatorTypeaheadResult()) ->setName($name) ->setURI($uri) ->setPHID($application->getPHID()) ->setPriorityString($application->getName()) ->setDisplayName($application->getName()) ->setDisplayType($application->getShortDescription()) ->setPriorityType('apps') ->setImageSprite('phabricator-search-icon '.$img) ->setIcon($application->getIcon()) ->addAttribute($application->getShortDescription()); } return $this->filterResultsAgainstTokens($results); } }
<?php final class PhabricatorApplicationDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Applications'); } public function getPlaceholderText() { return pht('Type an application name...'); } public function getDatasourceApplicationClass() { return 'PhabricatorApplicationsApplication'; } public function loadResults() { $viewer = $this->getViewer(); $raw_query = $this->getRawQuery(); $results = array(); $applications = PhabricatorApplication::getAllInstalledApplications(); foreach ($applications as $application) { $uri = $application->getTypeaheadURI(); if (!$uri) { continue; } $name = $application->getName().' '.$application->getShortDescription(); $img = 'phui-font-fa phui-icon-view '.$application->getIcon(); $results[] = id(new PhabricatorTypeaheadResult()) ->setName($name) ->setURI($uri) ->setPHID($application->getPHID()) ->setPriorityString($application->getName()) ->setDisplayName($application->getName()) ->setDisplayType($application->getShortDescription()) ->setPriorityType('apps') ->setImageSprite('phabricator-search-icon '.$img) ->setIcon($application->getIcon()) ->addAttribute($application->getShortDescription()); } return $this->filterResultsAgainstTokens($results); } }
Fix bug with reloading on Login page
(() => { 'use strict'; angular .module('app') .controller('LoginController', LoginController); LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints']; function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints) { const vm = this; vm.data = {}; vm.login = login; activate(); //// function activate() { let authorizationToken = TokenService.get(); if (authorizationToken) { TokenService.save(authorizationToken); $window.location.pathname = '/app/'; } } function login() { let req = { email: vm.data.email, password: vm.data.password }; let config = { 'Content-Type': 'application/json', 'Accept': 'application/json' }; let response = (res) => { if (res.status == 200) { if (res.data.success) { TokenService.save(res.data.data.token); window.localStorage.setItem('token', res.data.data.token); $window.location.pathname = '/app/'; } else { growl.info(res.data.data.message); } } vm.form.$setUntouched(); vm.form.$setPristine(); vm.form.$setDirty(); }; $http.post(Endpoints.AUTH, req, config).then(response); } } })();
(() => { 'use strict'; angular .module('app') .controller('LoginController', LoginController); LoginController.$inject = ['growl', '$window', '$http', '$routeSegment', 'TokenService', 'Endpoints']; function LoginController(growl, $window, $http, $routeSegment, TokenService, Endpoints) { const vm = this; vm.data = {}; vm.login = login; activate(); //// function activate() { let authorizationToken = TokenService.get(); if (authorizationToken) { TokenService.save(authorizationToken); $window.location.pathname = '/app/'; } } function login() { let req = { email: vm.data.email, password: vm.data.password }; let config = { 'Content-Type': 'application/json', 'Accept': 'application/json' }; let response = (res) => { if (res.status == 200) { if (res.data.success) { TokenService.save(res.data.data.token); window.localStorage.setItem('token', res.data.data.token); $window.location.pathname = '/app/'; } else { growl.info(res.data.data.message); $routeSegment.chain[0].reload(); } } vm.form.$setUntouched(); vm.form.$setPristine(); vm.form.$setDirty(); }; $http.post(Endpoints.AUTH, req, config).then(response); } } })();
Increase coverage base to 100%
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 100, statements: 100 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'], options: { jshintrc: '.jshintrc', } }, mochacli: { all: ['test/**/*.js'], options: { reporter: 'spec', ui: 'tdd' } }, 'mocha_istanbul': { coveralls: { src: [ 'test/lib', 'test/lib/utils' ], options: { coverage: true, legend: true, check: { lines: 98, statements: 99 }, root: './lib', reportFormats: ['lcov'] } } } }) grunt.event.on('coverage', function(lcov, done){ require('coveralls').handleInput(lcov, function(error) { if (error) { console.log(error) return done(error) } done() }) }) // Load the plugins grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-mocha-cli') grunt.loadNpmTasks('grunt-mocha-istanbul') // Configure tasks grunt.registerTask('coveralls', ['mocha_istanbul:coveralls']) grunt.registerTask('default', ['test']) grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls']) }
Fix the issue when use with multiple cursors and scroll the view when selected
import sublime_plugin class SelectExactMatchCommand(sublime_plugin.TextCommand): last_selection = None def run(self, edit): selections = self.view.sel() words_selection = False for selection in selections: if selection.empty(): words_selection = True region = self.view.word(selection) selections.add(region) self.view.show(region) if words_selection: return word = self.view.substr(self.view.word(selections[-1])) pattern = "\\b%s\\b" % (word) region = self.view.find(pattern, selections[-1].end()) if not region: region = self.view.find( pattern, self.last_selection.end() if self.last_selection else 0 ) if region: self.last_selection = region else: self.last_selection = None if region: selections.add(region) self.view.show(region) def description(): return "Select Exact Match" class SelectAllExactMatchesCommand(sublime_plugin.TextCommand): def run(self, edit): selections = self.view.sel() if selections[-1].empty(): selections.add(self.view.word(selections[-1])) word = self.view.substr(self.view.word(selections[-1])) pattern = "\\b%s\\b" % (word) selections.add_all(self.view.find_all(pattern)) def description(): return "Select All Exact Matches"
import sublime_plugin class SelectExactMatchCommand(sublime_plugin.TextCommand): last_selection = None def run(self, edit): selections = self.view.sel() if selections[0].empty(): selections.add(self.view.word(selections[0])) return word = self.view.substr(self.view.word(selections[0])) pattern = "\\b%s\\b" % (word) region = self.view.find(pattern, selections[-1].end()) if not region: region = self.view.find( pattern, self.last_selection.end() if self.last_selection else 0 ) if region: self.last_selection = region else: self.last_selection = None if region: selections.add(region) def description(): return "Select Exact Match" class SelectAllExactMatchesCommand(sublime_plugin.TextCommand): def run(self, edit): selections = self.view.sel() if selections[0].empty(): selections.add(self.view.word(selections[0])) word = self.view.substr(self.view.word(selections[0])) pattern = "\\b%s\\b" % (word) selections.add_all(self.view.find_all(pattern)) def description(): return "Select All Exact Matches"
Add helper classes to the event row
<table> <thead> <tr> <th scope="col" class="date">Time</th> <th scope="col" class="title">Event Title</th> </tr> </thead> <tbody class="vcalendar"> <?php $oddrow = false; foreach ($context as $eventinstance) { //Start building an array of row classes $row_classes = array('vevent'); if ($oddrow) { //Add an alt class to odd rows $row_classes[] = 'alt'; } if ($eventinstance->isAllDay()) { $row_classes[] = 'all-day'; } if ($eventinstance->isInProgress()) { $row_classes[] = 'in-progress'; } if ($eventinstance->isOnGoing()) { $row_classes[] = 'ongoing'; } //Invert oddrow $oddrow = !$oddrow; ?> <tr class="<?php echo implode(' ', $row_classes) ?>"> <td class="date"> <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?> </td> <td> <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?> </td> </tr> <?php } ?> </tbody> </table>
<table> <thead> <tr> <th scope="col" class="date">Time</th> <th scope="col" class="title">Event Title</th> </tr> </thead> <tbody class="vcalendar"> <?php $oddrow = false; foreach ($context as $eventinstance) { //Start building an array of row classes $row_classes = array('vevent'); if ($oddrow) { //Add an alt class to odd rows $row_classes[] = 'alt'; } //Invert oddrow $oddrow = !$oddrow; ?> <tr class="<?php echo implode(' ', $row_classes) ?>"> <td class="date"> <?php echo $savvy->render($eventinstance, 'EventInstance/Date.tpl.php') ?> </td> <td> <?php echo $savvy->render($eventinstance, 'EventInstance/Summary.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Location.tpl.php') ?> <?php echo $savvy->render($eventinstance, 'EventInstance/Description.tpl.php') ?> </td> </tr> <?php } ?> </tbody> </table>
Make some fixes in the Character component methods
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = 'http://placehold.it/250x250'; if(this.props.character.thumbnail) { var path = this.props.character.thumbnail.path; var extension = this.props.character.thumbnail.extension; image = path+'.'+extension; } return ( <img className="character-image" src={image}/> ) }, getName: function() { return ( <span className="character-name"> {this.props.character.name} </span> ); }, getDescription: function() { var description = this.props.character.description || 'No description'; return ( <p> {description} </p> ) }, getLinks: function() { return ( <p> <a href={this.props.character.urls[0].url}>Wiki</a>| <a href={this.props.character.urls[1].url}>More details</a> </p> ) }, render: function () { return ( <div className="character"> <div className="col-xs-12 col-sm-3"> <div className="thumbnail"> {this.getThumbnail()} <div className="caption"> <span className="character-name">{this.getName()}</span> <div className="character-description"> {this.getDescription()} {this.getLinks()} </div> </div> </div> </div> </div> ); } }); module.exports = Character;
var React = require('react'); var Character = React.createClass({ getThumbnail: function() { var image = 'http://placehold.it/250x250'; if(this.props.character.thumbnail) { image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension; } return ( <img className="character-image" src={image}/> ) }, getName: function() { return ( <span className="character-name"> {this.props.character.name} </span> ); }, getDescription: function() { var description = this.props.character.description ? this.props.character.description : 'No description' return ( <p> {description} </p> ) }, getLinks: function() { return ( <p> <a href={this.props.character.urls[0].url}>Wiki</a>| <a href={this.props.character.urls[1].url}>More details</a> </p> ) }, render: function () { return ( <div className="character"> <div className="col-xs-12 col-sm-3"> <div className="thumbnail"> {this.getThumbnail()} <div className="caption"> <span className="character-name">{this.getName()}</span> <div className="character-description"> {this.getDescription()} {this.getLinks()} </div> </div> </div> </div> </div> ); } }); module.exports = Character;
Simplify and make better :) Removed deep watch because it broke on when using scopes. Instead it now sets a series of getters on the scope for each property found on the given scope. Also it's much more performant.
angular.module('drg.ngIncludeScope', []) .directive( 'ngIncludeScope', function() { 'use strict'; return { restrict: 'A', link : function( scope, elem, attrs ) { var keys = []; scope.$watch( attrs.ngIncludeScope, function( newScope, oldScope ) { var key; keys = Object.keys( newScope ); // set getters angular.forEach( keys, function(key) { if( newScope.hasOwnProperty( key ) && angular.isUndefined( scope[ key ] ) ) { Object.defineProperty( scope, key, { get: function() { return !!~keys.indexOf( key ) ? scope.$eval( attrs.ngIncludeScope + "['" + key.replace("'", "\\'") + "']" ) : undefined; } } ); } } ); } ); } }; });
angular.module('drg.ngIncludeScope', []) .directive( 'ngIncludeScope', function() { 'use strict'; return { restrict: 'A', link : function( scope, elem, attrs ) { scope.$watch( attrs.ngIncludeScope, function( newScope, oldScope ) { var key, newKeys = Object.keys( newScope ), oldKeys = Object.keys( oldScope ); // update values for( key in newKeys ) { key = newKeys[ key ]; if( newScope.hasOwnProperty( key ) ) { scope[ key ] = newScope[ key ]; } } // remove old values for( key in oldKeys ) { key = oldKeys[ key ]; if( typeof newScope[ key ] === 'undefined' ) { delete scope[ key ]; } } }, true ); } }; });
Add SVT options to plotting script.
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), markers=('plot traces of these markers', 'option'), spline=('interpolate data with a spline of this order', 'option', None, int), accuracy=('fit spline with this accuracy', 'option', None, float), svt_threshold=('trajectory-SVT threshold', 'option', None, float), svt_frames=('number of trajectory-SVT frames', 'option', None, int), ) def main(root, pattern='*/*block00/*circuit00.csv.gz', markers='r-fing-index l-fing-index r-heel r-knee', spline=None, accuracy=0.01, svt_threshold=1000, svt_frames=5): with plots.space() as ax: for t in source.Experiment(root).trials_matching(pattern): if spline: t.normalize(order=spline, accuracy=accuracy) else: t.reindex() t.svt(svt_threshold, accuracy, svt_frames) for i, marker in enumerate(markers.split()): df = t.trajectory(marker) ax.plot(np.asarray(df.x), np.asarray(df.z), zs=np.asarray(df.y), color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
import climate import lmj.plot import numpy as np import source import plots @climate.annotate( root='load experiment data from this directory', pattern=('plot data from files matching this pattern', 'option'), markers=('plot traces of these markers', 'option'), spline=('interpolate data with a spline of this order', 'option', None, int), accuracy=('fit spline with this accuracy', 'option', None, float), ) def main(root, pattern='*/*block00/*circuit00.csv.gz', markers='r-fing-index l-fing-index r-heel r-knee', spline=1, accuracy=1): with plots.space() as ax: for t in source.Experiment(root).trials_matching(pattern): t.normalize(order=spline, accuracy=accuracy) for i, marker in enumerate(markers.split()): df = t.trajectory(marker) ax.plot(np.asarray(df.x), np.asarray(df.z), zs=np.asarray(df.y), color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
Make stop words a set for speed optimization.
import os from operator import itemgetter import re from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore with open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU') as f: STOP_WORDS = set(f.read().splitlines()) def recent_entries(max_entries=20): return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries] def popular_words(max_entries=20, max_words=25): sqs = recent_entries(max_entries) # Generate tag cloud from content of returned entries words = {} for entry in sqs: text = re.sub(ur'[^\w\s]', '', entry.object.content.lower()) for x in text.split(): if x not in STOP_WORDS: words[x] = 1 + words.get(x, 0) wordlist = [] for word in words: wordlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) wordlist.sort(key=itemgetter('weight'), reverse=True) return wordlist[:max_words]
import os from operator import itemgetter import re from haystack.query import SearchQuerySet from pombola.hansard import models as hansard_models BASEDIR = os.path.dirname(__file__) # normal english stop words and hansard-centric words to ignore STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitlines() def recent_entries(max_entries=20): return SearchQuerySet().models(hansard_models.Entry).order_by('-sitting_start_date')[:max_entries] def popular_words(max_entries=20, max_words=25): sqs = recent_entries(max_entries) # Generate tag cloud from content of returned entries words = {} for entry in sqs: text = re.sub(ur'[^\w\s]', '', entry.object.content.lower()) for x in text.split(): if x not in STOP_WORDS: words[x] = 1 + words.get(x, 0) wordlist = [] for word in words: wordlist.append( { "text": word, "weight": words.get(word), "link": "/search/hansard/?q=%s" % word, } ) wordlist.sort(key=itemgetter('weight'), reverse=True) return wordlist[:max_words]
refactor: Remove unnecessary reference from webpack dev build.
// For output.filename configuration: // // CHANGE "component-name" in this file to your real component name! // DO NOT CHANGE "[name]", which denotes the entry property names that webpack automatically inserts for you! module.exports = { entry: { dev: ['webpack/hot/dev-server', './demo/demo.js'], dist: ['./main.js'] }, output: { path: './', filename: 'build/[name].component-name.js', libraryTarget: 'umd' }, devtool: 'cheap-module-source-map', externals: [ { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, { 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } ], contentBase: './demo', // for webpack dev server module: { preLoaders: [ { test: /\.js$/, loader: 'eslint', exclude: /node_modules/ } ], loaders: [ { test: /\.scss$/, loader: 'style!css!sass' // sass -> css -> javascript -> inline style }, { test: /\.js$/, loader: 'babel', query: { cacheDirectory: true, presets: ['es2015', 'react', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ] } };
// For output.filename configuration: // // Change "component-name" in this file to your real component name! // DO NOT CHANGE "[name]", which denotes the entry property names that webpack automatically inserts for you! module.exports = { entry: { dev: ['webpack/hot/dev-server', './main.js', './demo/demo.js'], dist: ['./main.js'] }, output: { path: './', filename: 'build/[name].component-name.js', libraryTarget: 'umd' }, devtool: 'cheap-module-source-map', externals: [ { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, { 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } ], contentBase: './demo', // for webpack dev server module: { preLoaders: [ { test: /\.js$/, loader: 'eslint', exclude: /node_modules/ } ], loaders: [ { test: /\.scss$/, loader: 'style!css!sass' // sass -> css -> javascript -> inline style }, { test: /\.js$/, loader: 'babel', query: { cacheDirectory: true, presets: ['es2015', 'react', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ] } };
Update default value of mode
/* Toast notification popup jQuery plugin (c) 2016 Nupin Mathew <[email protected]> License: MIT */ $(function () { /*Method to show a toast notification like popup with a message which will be closed after a fixed time*/ $.fn.showToast = function (options) { var defaults = { message: 'This is a toast notification!', timeout: 1500, mode: 'info' }; var settings = $.extend({}, defaults, options); var self = this; var margin = 100; $(self).css("width", "auto"); $(self).text(settings.message); var windowWidth = window.innerWidth; var toastWidth = $(self).innerWidth() + margin; if (toastWidth >= windowWidth) { toastWidth = windowWidth - margin; $(self).css("width", toastWidth); } else { toastWidth = $(self).innerWidth(); } var left = (windowWidth - toastWidth) / 2.0; var leftInPercentage = left * 100 / windowWidth; $(self).css("left", leftInPercentage + "%"); $(self).fadeIn(400); $(self).removeClass("success warning error"); if (settings.mode == "success") { $(self).addClass('success'); } else if (settings.mode == "warning") { $(self).addClass('warning'); } else if (settings.mode == "error") { $(self).addClass('error'); } setTimeout(function () { $(self).fadeOut(600); }, settings.timeout); }; });
/* Toast notification popup jQuery plugin (c) 2016 Nupin Mathew <[email protected]> License: MIT */ $(function () { /*Method to show a toast notification like popup with a message which will be closed after a fixed time*/ $.fn.showToast = function (options) { var defaults = { message: 'This is a toast notification!', timeout: 1500 }; var settings = $.extend({}, defaults, options); var self = this; var margin = 100; $(self).css("width", "auto"); $(self).text(settings.message); var windowWidth = window.innerWidth; var toastWidth = $(self).innerWidth() + margin; if (toastWidth >= windowWidth) { toastWidth = windowWidth - margin; $(self).css("width", toastWidth); } else { toastWidth = $(self).innerWidth(); } var left = (windowWidth - toastWidth) / 2.0; var leftInPercentage = left * 100 / windowWidth; $(self).css("left", leftInPercentage + "%"); $(self).fadeIn(400); $(self).removeClass("success warning error"); if (settings.mode == "success") { $(self).addClass('success'); } else if (settings.mode == "warning") { $(self).addClass('warning'); } else if (settings.mode == "error") { $(self).addClass('error'); } setTimeout(function () { $(self).fadeOut(600); }, settings.timeout); }; });
Change js coverage report format for jenkins
module.exports = function(config) { config.set({ basePath: '../../', files: [ 'web/js/vendor/angular.js', 'web/js/vendor/angular-*.js', 'test/lib/angular/angular-mocks.js', 'web/js/vendor/jquery*.js', 'web/js/**/*.js', 'test/unit/**/*.js' ], autoWatch: false, singleRun: true, browsers: ['PhantomJS', 'Firefox'], frameworks: ["jasmine"], reporters: ['dots', 'junit', 'coverage'], preprocessors: { // source files, that you wanna generate coverage for // do not include tests or libraries // (these files will be instrumented by Istanbul) 'web/js/*.js': ['coverage'] }, junitReporter: { outputFile: 'app/build/logs/js_unit.xml', suite: 'unit' }, coverageReporter: { type : 'cobertura', dir : 'app/build/jscoverage/' }, reportSlowerThan: 500, }); };
module.exports = function(config) { config.set({ basePath: '../../', files: [ 'web/js/vendor/angular.js', 'web/js/vendor/angular-*.js', 'test/lib/angular/angular-mocks.js', 'web/js/vendor/jquery*.js', 'web/js/**/*.js', 'test/unit/**/*.js' ], autoWatch: false, singleRun: true, browsers: ['PhantomJS', 'Firefox'], frameworks: ["jasmine"], reporters: ['dots', 'junit', 'coverage'], preprocessors: { // source files, that you wanna generate coverage for // do not include tests or libraries // (these files will be instrumented by Istanbul) 'web/js/*.js': ['coverage'] }, junitReporter: { outputFile: 'app/build/logs/js_unit.xml', suite: 'unit' }, coverageReporter: { type : 'html', dir : 'app/build/jscoverage/' }, reportSlowerThan: 500, }); };
Svgo: Remove unused property `_multiPass`, `settings.multipass` is used instead.
"use strict"; var SvgFile = require('./svg-file'); class Svgo extends require('./worker-messenger') { constructor() { super('js/svgo-worker.js'); this._abortOnNextIteration = false; this._currentJob = Promise.resolve(); } load(svgText) { return this._requestResponse({ action: 'load', data: svgText }).then(({width, height}) => { return new SvgFile(svgText, width, height); }); } process(settings, iterationCallback) { return this._currentJob = this.abortCurrent().then(async _ => { this._abortOnNextIteration = false; var result = await this._requestResponse({ action: 'process', settings }); var resultFile = new SvgFile(result.data, result.dimensions.width, result.dimensions.height); iterationCallback(resultFile); if (settings.multipass) { while (result = await this.nextPass()) { if (this._abortOnNextIteration) { throw Error('abort'); } resultFile = new SvgFile(result.data, result.dimensions.width, result.dimensions.height); iterationCallback(resultFile); } } // return final result return resultFile; }); } nextPass() { return this._requestResponse({ action: 'nextPass' }); } async abortCurrent() { this._abortOnNextIteration = true; try { await this._currentJob; } catch(e){} } } module.exports = Svgo;
"use strict"; var SvgFile = require('./svg-file'); class Svgo extends require('./worker-messenger') { constructor() { super('js/svgo-worker.js'); this._multiPass = false; this._abortOnNextIteration = false; this._currentJob = Promise.resolve(); } load(svgText) { return this._requestResponse({ action: 'load', data: svgText }).then(({width, height}) => { return new SvgFile(svgText, width, height); }); } process(settings, iterationCallback) { return this._currentJob = this.abortCurrent().then(async _ => { this._abortOnNextIteration = false; var result = await this._requestResponse({ action: 'process', settings }); var resultFile = new SvgFile(result.data, result.dimensions.width, result.dimensions.height); iterationCallback(resultFile); if (settings.multipass) { while (result = await this.nextPass()) { if (this._abortOnNextIteration) { throw Error('abort'); } resultFile = new SvgFile(result.data, result.dimensions.width, result.dimensions.height); iterationCallback(resultFile); } } // return final result return resultFile; }); } nextPass() { return this._requestResponse({ action: 'nextPass' }); } async abortCurrent() { this._abortOnNextIteration = true; try { await this._currentJob; } catch(e){} } } module.exports = Svgo;
Allow manifest output name to be configured
/** * A Rollup plugin to generate a manifest of chunk names to their filenames * (including their content hash). This manifest is then used by the template * to point to the currect URL. * @return {Object} */ export default function (config) { if (!config) { config = {}; } const manifest = { files: [], entries: {}, }; const trimPrefix = config.trimPrefix || /^.*[/]/; return { name: 'manifest', generateBundle(options, bundle) { for (const [fileName, chunk] of Object.entries(bundle)) { if (chunk.type === 'asset') { // Skip assets for now continue; } if (chunk.isEntry || chunk.isDynamicEntry) { const facadeModuleId = chunk.facadeModuleId; const name = facadeModuleId ? facadeModuleId.replace(trimPrefix, '/') : chunk.name; if (manifest.entries[name]) { console.log(`Duplicate chunk name: ${name}`); } manifest.entries[name] = { file: fileName, dependencies: chunk.imports, }; } manifest.files.push(fileName); } this.emitFile({ type: 'asset', fileName: config.output || (options.compact ? 'manifest.min.json' : 'manifest.json'), source: JSON.stringify(manifest, null, 2), }); }, }; }
/** * A Rollup plugin to generate a manifest of chunk names to their filenames * (including their content hash). This manifest is then used by the template * to point to the currect URL. * @return {Object} */ export default function (config) { const manifest = { files: [], entries: {}, }; const trimPrefix = (config && config.trimPrefix) || /^.*[/]/; return { name: 'manifest', generateBundle(options, bundle) { for (const [fileName, chunk] of Object.entries(bundle)) { if (chunk.type === 'asset') { // Skip assets for now continue; } if (chunk.isEntry || chunk.isDynamicEntry) { const facadeModuleId = chunk.facadeModuleId; const name = facadeModuleId ? facadeModuleId.replace(trimPrefix, '/') : chunk.name; if (manifest.entries[name]) { console.log(`Duplicate chunk name: ${name}`); } manifest.entries[name] = { file: fileName, dependencies: chunk.imports, }; } manifest.files.push(fileName); } this.emitFile({ type: 'asset', fileName: options.compact ? 'manifest.min.json' : 'manifest.json', source: JSON.stringify(manifest, null, 2), }); }, }; }
Allow loading of external urls specified in the swagger resource location resolves #843
$(function() { var springfox = { "baseUrl": function() { var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href); return urlMatches[1]; }, "securityConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/security", function(data) { cb(data); }); }, "uiConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/ui", function(data) { cb(data); }); } }; window.springfox = springfox; window.oAuthRedirectUrl = springfox.baseUrl() + '/o2c.html' $('#select_baseUrl').change(function() { window.swaggerUi.headerView.trigger('update-swagger-ui', { url: $('#select_baseUrl').val() }); }); function maybePrefix(location, withRelativePath) { var pat = /^https?:\/\//i; if (pat.test(location)) { return location; } return withRelativePath + location; } $(document).ready(function() { var relativeLocation = springfox.baseUrl(); $('#input_baseUrl').hide(); $.getJSON(relativeLocation + "/swagger-resources", function(data) { var $urlDropdown = $('#select_baseUrl'); $urlDropdown.empty(); $.each(data, function(i, resource) { var option = $('<option></option>') .attr("value", maybePrefix(resource.location, relativeLocation)) .text(resource.name + " (" + resource.location + ")"); $urlDropdown.append(option); }); $urlDropdown.change(); }); }); });
$(function() { var springfox = { "baseUrl": function() { var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href); return urlMatches[1]; }, "securityConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/security", function(data) { cb(data); }); }, "uiConfig": function(cb) { $.getJSON(this.baseUrl() + "/configuration/ui", function(data) { cb(data); }); } }; window.springfox = springfox; window.oAuthRedirectUrl = springfox.baseUrl() + '/o2c.html' $('#select_baseUrl').change(function() { window.swaggerUi.headerView.trigger('update-swagger-ui', { url: $('#select_baseUrl').val() }); }); $(document).ready(function() { var relativeLocation = springfox.baseUrl(); $('#input_baseUrl').hide(); $.getJSON(relativeLocation + "/swagger-resources", function(data) { var $urlDropdown = $('#select_baseUrl'); $urlDropdown.empty(); $.each(data, function(i, resource) { var option = $('<option></option>') .attr("value", relativeLocation + resource.location) .text(resource.name + " (" + resource.location + ")"); $urlDropdown.append(option); }); $urlDropdown.change(); }); }); });
Fix how we calculate total to really account for deleted objects
from django.contrib import admin from django.core.exceptions import ValidationError from django import forms from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(forms.BaseInlineFormSet): def clean(self): super(FeeLinesInlineFormSet, self).clean() total = 0 for form in self.forms: if not form.is_valid() or form.cleaned_data.get('DELETE'): continue # there are other errors in the form or the item was deleted total += form.cleaned_data.get('amount', 0) self.instance.total_amount = total class FeeLineForm(forms.ModelForm): def clean(self): if self.cleaned_data['date_start'] > self.cleaned_data['date_end']: raise ValidationError(_("Date start must be before date end")) class FeeLinesInline(admin.TabularInline): form = FeeLineForm model = FeeLine formset = FeeLinesInlineFormSet extra = 1 def get_extra (self, request, obj=None, **kwargs): # Don't add any extra forms if the related object already exists. if obj: return 0 return self.extra class ReceiptAdmin(admin.ModelAdmin): readonly_fields = ['total_amount'] inlines = [FeeLinesInline] admin.site.register(Receipt, ReceiptAdmin)
from django.contrib import admin from django.core.exceptions import ValidationError from django.forms import BaseInlineFormSet, ModelForm from django.utils.translation import ugettext_lazy as _ from revenue.models import Receipt, FeeLine class FeeLinesInlineFormSet(BaseInlineFormSet): def clean(self): super(FeeLinesInlineFormSet, self).clean() total = 0 for form in self.forms: if not form.is_valid() or form.cleaned_data.get('DELETE'): return # there are other errors in the form or the item was deleted total += form.cleaned_data.get('amount', 0) self.instance.total_amount = total print(self.instance) class FeeLineForm(ModelForm): def clean(self): if self.cleaned_data['date_start'] > self.cleaned_data['date_end']: raise ValidationError(_("Date start must be before date end")) class FeeLinesInline(admin.TabularInline): form = FeeLineForm model = FeeLine formset = FeeLinesInlineFormSet extra = 1 def get_extra (self, request, obj=None, **kwargs): # Don't add any extra forms if the related object already exists. if obj: return 0 return self.extra class ReceiptAdmin(admin.ModelAdmin): readonly_fields = ['total_amount'] inlines = [FeeLinesInline] admin.site.register(Receipt, ReceiptAdmin)
Make coverage php version option verbose
<?php namespace Phug\DevTool\Command; use Phug\DevTool\AbstractCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class CoverageReportCommand extends AbstractCommand { protected function configure() { $this->setName('coverage:report') ->addArgument( 'input-file', InputArgument::REQUIRED, 'The XML file to report coverage from' ) ->addOption( 'php-version', null, InputOption::VALUE_OPTIONAL, 'If specified, the report is only send for the given PHP version' ) ->setDescription('Reports coverage.') ->setHelp('This command reports coverage'); } protected function execute(InputInterface $input, OutputInterface $output) { $xmlFile = realpath($input->getArgument('input-file')); $phpVersion = $input->getOption('php-version'); if (!empty($phpVersion)) { if (!preg_match('/^'.preg_quote($phpVersion).'(\D.*)?$/', PHP_VERSION)) { $output->writeln('Test report ignored since PHP version ('.PHP_VERSION.') does not match '.$phpVersion.'.'); return 0; } $output->writeln('<fg=green>Proceed test report since PHP version ('.PHP_VERSION.') matches '.$phpVersion.'.</>'); } $this->getApplication()->runVendorCommand('test-reporter', [ "--coverage-report $xmlFile", ]); return 0; } }
<?php namespace Phug\DevTool\Command; use Phug\DevTool\AbstractCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class CoverageReportCommand extends AbstractCommand { protected function configure() { $this->setName('coverage:report') ->addArgument( 'input-file', InputArgument::REQUIRED, 'The XML file to report coverage from' ) ->addOption( 'php-version', null, InputOption::VALUE_OPTIONAL, 'If specified, the report is only send for the given PHP version' ) ->setDescription('Reports coverage.') ->setHelp('This command reports coverage'); } protected function execute(InputInterface $input, OutputInterface $output) { $xmlFile = realpath($input->getArgument('input-file')); $phpVersion = $input->getOption('php-version'); if (empty($phpVersion) || preg_match('/^'.preg_quote($phpVersion).'(\D.*)?$/', PHP_VERSION)) { $this->getApplication()->runVendorCommand('test-reporter', [ "--coverage-report $xmlFile", ]); } return 0; } }
Remove whitespace from campaign text area
class CampaignView { constructor(){ } getIndex(campaigns) { console.log('Campaign View: Get index'); var campaignHTML = `<h1>Campaign Index<h1>`; for(let i = 0; i < campaigns.length; i++) { campaignHTML += `<button class='campaign_show' data-id='${campaigns[i].id}'>Campaign ${campaigns[i].name}</button>`; } campaignHTML += `<button id='campaign_new'>New</button>`; return campaignHTML; } new() { return `<h1>New Campaign<h1> <p>This is the new campaign view<p> <form name='form_campaign_new'> <label for='name'>Campaign Name</label> <input name='name' id='name'/> <label for='description'>Description</label> <textarea name='description' id='description'></textarea> <label for='expiry'>Expiry Date</label> <input name='expiry' id='expiry' type='date' /> <label for='dailyPosts'>Daily Posts</label> <input name='dailyPosts' id='dailyPosts' type='number' min='0' max='10'/> <button id='campaign_save'>Save</button> <button id='campaign_index'>Cancel</button> </form>`; } show(campaign) { return `<h1>Show Campaign<h1> <p>This is the show campaign view. ID: ${campaign.id}<p>`; } edit(campaign) { return `<h1>Edit Campaign<h1> <p>This is the edit campaign view<p>`; } }
class CampaignView { constructor(){ } getIndex(campaigns) { console.log('Campaign View: Get index'); var campaignHTML = `<h1>Campaign Index<h1>`; for(let i = 0; i < campaigns.length; i++) { campaignHTML += `<button class='campaign_show' data-id='${campaigns[i].id}'>Campaign ${campaigns[i].name}</button>`; } campaignHTML += `<button id='campaign_new'>New</button>`; return campaignHTML; } new() { return `<h1>New Campaign<h1> <p>This is the new campaign view<p> <form name='form_campaign_new'> <label for='name'>Campaign Name</label> <input name='name' id='name'/> <label for='description'>Description</label> <textarea name='description' id='description'> </textarea> <label for='expiry'>Expiry Date</label> <input name='expiry' id='expiry' type='date' /> <label for='dailyPosts'>Daily Posts</label> <input name='dailyPosts' id='dailyPosts' type='number' /> <button id='campaign_save'>Save</button> <button id='campaign_index'>Cancel</button> </form>`; } show(campaign) { return `<h1>Show Campaign<h1> <p>This is the show campaign view. ID: ${campaign.id}<p>`; } edit(campaign) { return `<h1>Edit Campaign<h1> <p>This is the edit campaign view<p>`; } }
Use MySQLi interface for example
<?php require('json-rpc/json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } $link = new mysqli('localhost', 'user', 'password', 'db_name'); class MysqlDemo { public function query($query) { global $link; if (preg_match("/create|drop/", $query)) { throw new Exception("Sorry you are not allowed to execute '" . $query . "'"); } if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) { throw new Exception("Sorry you can't execute '" . $query . "' you are only allowed to select, insert, delete " . "or update 'test' table"); } if ($res = $link->query($query)) { if ($res === true) { return true; } if ($res->num_rows > 0) { while ($row = $res->fetch_array(MYSQLI_NUM)) { $result[] = $row; } return $result; } else { return array(); } } else { throw new Exception("MySQL Error: " . mysql_error()); } } } handle_json_rpc(new MysqlDemo()); ?>
<?php require('json-rpc/json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } @mysql_connect('localhost', 'user', 'password'); @mysql_select_db('database_name'); class MysqlDemo { public function query($query) { if (preg_match("/create|drop/", $query)) { throw new Exception("Sorry you are not allowed to execute '" . $query . "'"); } if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) { throw new Exception("Sorry you can't execute '" . $query . "' you are only allowed to select, insert, delete " . "or update 'test' table"); } if ($res = mysql_query($query)) { if ($res === true) { return true; } if (mysql_num_rows($res) > 0) { while ($row = mysql_fetch_row($res)) { $result[] = $row; } return $result; } else { return array(); } } else { throw new Exception("MySQL Error: " . mysql_error()); } } } handle_json_rpc(new MysqlDemo()); ?>
Fix issue with "load more" button status
'use strict'; angular .module('lwControllers') .controller('Posts', function($rootScope, $scope, $routeParams, $location, Article, Analytics, Admin) { $rootScope.title = 'Posts — LilyMandarin'; Analytics.page(); $rootScope.tab = 'posts'; $scope.posts = []; // Fetches and appends a new batch of posts $scope.load = function() { $scope.loadStatus = 'loading'; var params = { categories: 'post', count: 20 }; var length = $scope.posts.length; if (!length) { // First load params.validatedBefore = '0'; params.validatedOnly = !Admin; } else { // Subsequent loads params.validatedBefore = $scope.posts[length - 1].firstValidationTimeNano; params.validatedOnly = true; } Article.query(params, function(posts) { // This is efficient because Angular will not recreate DOM elements for the // already-appended posts in $scope.posts $scope.posts = $scope.posts.concat(posts); if (posts.length < params.count || posts.length && !posts[posts.length - 1].validated) { $scope.loadStatus = 'ended'; } else { $scope.loadStatus = 'ready'; } }); }; $scope.load(); } );
'use strict'; angular .module('lwControllers') .controller('Posts', function($rootScope, $scope, $routeParams, $location, Article, Analytics, Admin) { $rootScope.title = 'Posts — LilyMandarin'; Analytics.page(); $rootScope.tab = 'posts'; $scope.posts = []; // Fetches and appends a new batch of posts $scope.load = function() { $scope.loadStatus = 'loading'; var params = { categories: 'post', count: 20 }; var length = $scope.posts.length; if (length) { params.validatedBefore = $scope.posts[length - 1].firstValidationTimeNano; // Only get non-validated articles on the first load, otherwise they will end up // duplicated! params.validatedOnly = true; } else { params.validatedBefore = '0'; params.validatedOnly = !Admin; } Article.query(params, function(posts) { // This is efficient because Angular will not recreate DOM elements for the // already-appended posts in $scope.posts $scope.posts = $scope.posts.concat(posts); $scope.loadStatus = posts.length < params.count ? 'ended' : 'ready'; }); }; $scope.load(); } );
ALign with the relevant code
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( _token, index >= 0 ? index + newToken.length : 0 ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( _token, index >= 0 ? index + newToken.length : 0 ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
Use get_profile_for_user() in profile signal handler
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_user_fieldname, get_profile_for_user from mezzanine.conf import settings from mezzanine.utils.models import lazy_model_ops __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): # This will be called when class_prepared signal has been sent # for both the profile and user model. def wait_for_models(profile_model, user_model): user_field = get_profile_user_fieldname(profile_model, user_model) def create_profile(sender, instance, created, **_): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=user_model, weak=False) lazy_model_ops.add(wait_for_models, settings.AUTH_PROFILE_MODULE, settings.AUTH_USER_MODEL)
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_user_fieldname from mezzanine.conf import settings from mezzanine.utils.models import lazy_model_ops __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): # This will be called when class_prepared signal has been sent # for both the profile and user model. def wait_for_models(profile_model, user_model): user_field = get_profile_user_fieldname(profile_model, user_model) def create_profile(sender, instance, created, **kwargs): if created: try: kwargs = {str(user_field): instance} profile_model.objects.create(**kwargs) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=user_model, weak=False) lazy_model_ops.add(wait_for_models, settings.AUTH_PROFILE_MODULE, settings.AUTH_USER_MODEL)
Simplify indexes for managed installs
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Managedinstalls extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('managedinstalls', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->string('name'); $table->string('display_name'); $table->string('version')->nullable(); $table->integer('size')->nullable(); $table->integer('installed'); $table->string('status'); $table->string('type'); $table->index('display_name'); $table->index('name'); $table->index(['name', 'version']); $table->index('serial_number'); $table->index('status'); $table->index('type'); $table->index('version'); // $table->timestamps(); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('managedinstalls'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Managedinstalls extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('managedinstalls', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->string('name'); $table->string('display_name'); $table->string('version')->nullable(); $table->integer('size')->nullable(); $table->integer('installed'); $table->string('status'); $table->string('type'); $table->index('display_name', 'managedinstalls_display_name'); $table->index('name', 'managedinstalls_name'); $table->index(['name', 'version'], 'managedinstalls_name_version'); $table->index('serial_number', 'managedinstalls_serial_number'); $table->index('status', 'managedinstalls_status'); $table->index('type', 'managedinstalls_type'); $table->index('version', 'managedinstalls_version'); // $table->timestamps(); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('managedinstalls'); } }
Add condition to only launch server if -s or --server is specified Now you can launch client, server or updater on its own, launch nothing, or launch the whole thing altogether!
import os import sys import time from multiprocessing import Process, Event import mfhclient import server import update from arguments import parse from settings import HONEYPORT, HIVEPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfhclient_process", target=mfhclient.main, ) server_process = Process( args=(args, update_event,), name="server_process", target=server.main, ) if args.client is not None: mfhclient_process.start() if args.client is not None: server_process.start() if args.updater: trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive() or server_process.is_alive(): time.sleep(5) else: if args.updater: # update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT main()
import os import sys import time from multiprocessing import Process, Event import mfhclient import server import update from arguments import parse from settings import HONEYPORT def main(): update_event = Event() mfhclient_process = Process( args=(args, update_event,), name="mfhclient_process", target=mfhclient.main, ) server_process = Process( args=(args, update_event,), name="server_process", target=server.main, ) if args.client is not None: mfhclient_process.start() server_process.start() if args.updater: trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive(): time.sleep(5) else: if args.updater: update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT main()
Update url patterns - accept only exact patterns
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib.staticfiles.views import serve from django.views.decorators.csrf import csrf_exempt from .graphql.api import schema from .graphql.views import GraphQLView from .plugins.views import handle_plugin_webhook from .product.views import digital_product urlpatterns = [ url(r"^graphql/$", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"), url( r"^digital-download/(?P<token>[0-9A-Za-z_\-]+)/$", digital_product, name="digital-product", ), url( r"plugins/(?P<plugin_id>[.0-9A-Za-z_\-]+)/", handle_plugin_webhook, name="plugins", ), ] if settings.DEBUG: import warnings from .core import views try: import debug_toolbar except ImportError: warnings.warn( "The debug toolbar was not installed. Ignore the error. \ settings.py should already have warned the user about it." ) else: urlpatterns += [ url(r"^__debug__/", include(debug_toolbar.urls)) # type: ignore ] urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [ url(r"^static/(?P<path>.*)$", serve), url(r"^", views.home, name="home"), ]
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib.staticfiles.views import serve from django.views.decorators.csrf import csrf_exempt from .graphql.api import schema from .graphql.views import GraphQLView from .plugins.views import handle_plugin_webhook from .product.views import digital_product urlpatterns = [ url(r"^graphql/", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"), url( r"^digital-download/(?P<token>[0-9A-Za-z_\-]+)/$", digital_product, name="digital-product", ), url( r"plugins/(?P<plugin_id>[.0-9A-Za-z_\-]+)/", handle_plugin_webhook, name="plugins", ), ] if settings.DEBUG: import warnings from .core import views try: import debug_toolbar except ImportError: warnings.warn( "The debug toolbar was not installed. Ignore the error. \ settings.py should already have warned the user about it." ) else: urlpatterns += [ url(r"^__debug__/", include(debug_toolbar.urls)) # type: ignore ] urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [ url(r"^static/(?P<path>.*)$", serve), url(r"^", views.home, name="home"), ]
Fix error due to path not found When the project does not have the /bin directory in the root this error appears: [PhpGitHooks\Module\JsonLint\Contract\Exception\JsonLintViolationsException] Could not open input file: bin/jsonlint But it does exist in /vendor/bin. This fix tries to find it in both paths.
<?php namespace PhpGitHooks\Infrastructure\Tool; class ToolPathFinder { const COMPOSER_VENDOR_DIR = '/../../../'; const COMPOSER_INSTALLED_FILE = 'composer/installed.json'; /** @var array */ private $tools = array( 'phpcs' => 'squizlabs/php_codesniffer', 'php-cs-fixer' => 'friendsofphp/php-cs-fixer', 'phpmd' => 'phpmd/phpmd', 'phpunit' => 'phpunit/phpunit', 'phpunit-randomizer' => 'fiunchinho/phpunit-randomizer', 'jsonlint' => 'seld/jsonlint', ); /** @var array */ private $installedPackages = array(); /** * @param string $tool * * @return string */ public function find($tool) { if (isset($this->installedPackages[$this->tools[$tool]])) { $package = $this->installedPackages[$this->tools[$tool]]; foreach ($package['bin'] as $bin) { if (preg_match("#${tool}$#", $bin)) { return dirname(__FILE__).self::COMPOSER_VENDOR_DIR.$package['name'].DIRECTORY_SEPARATOR.$bin; } } } $binToolPath = 'bin'.DIRECTORY_SEPARATOR.$tool; if (file_exists($binToolPath) && is_file($binToolPath)) { return $binToolPath; } return 'vendor'.DIRECTORY_SEPARATOR.$binToolPath; } }
<?php namespace PhpGitHooks\Infrastructure\Tool; class ToolPathFinder { const COMPOSER_VENDOR_DIR = '/../../../'; const COMPOSER_INSTALLED_FILE = 'composer/installed.json'; /** @var array */ private $tools = array( 'phpcs' => 'squizlabs/php_codesniffer', 'php-cs-fixer' => 'friendsofphp/php-cs-fixer', 'phpmd' => 'phpmd/phpmd', 'phpunit' => 'phpunit/phpunit', 'phpunit-randomizer' => 'fiunchinho/phpunit-randomizer', 'jsonlint' => 'seld/jsonlint', ); /** @var array */ private $installedPackages = array(); /** * @param string $tool * * @return string */ public function find($tool) { if (isset($this->installedPackages[$this->tools[$tool]])) { $package = $this->installedPackages[$this->tools[$tool]]; foreach ($package['bin'] as $bin) { if (preg_match("#${tool}$#", $bin)) { return dirname(__FILE__).self::COMPOSER_VENDOR_DIR.$package['name'].DIRECTORY_SEPARATOR.$bin; } } } return 'bin'.DIRECTORY_SEPARATOR.$tool; } }