text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix unit tests for python2
from rdflib import Graph, URIRef, Literal, BNode from rdflib.plugins.sparql import prepareQuery from rdflib.compare import isomorphic import unittest from nose.tools import eq_ class TestConstructInitBindings(unittest.TestCase): def test_construct_init_bindings(self): """ This is issue https://github.com/RDFLib/rdflib/issues/1001 """ g1 = Graph() q_str = (""" PREFIX : <urn:ns1:> CONSTRUCT { ?uri :prop1 ?val1; :prop2 ?c . } WHERE { bind(uri(concat("urn:ns1:", ?a)) as ?uri) bind(?b as ?val1) } """) q_prepared = prepareQuery(q_str) expected = [ (URIRef('urn:ns1:A'),URIRef('urn:ns1:prop1'), Literal('B')), (URIRef('urn:ns1:A'),URIRef('urn:ns1:prop2'), Literal('C')) ] results = g1.query(q_prepared, initBindings={ 'a': Literal('A'), 'b': Literal('B'), 'c': Literal('C') }) eq_(sorted(results, key=lambda x: str(x[1])), expected)
from rdflib import Graph, URIRef, Literal, BNode from rdflib.plugins.sparql import prepareQuery from rdflib.compare import isomorphic import unittest class TestConstructInitBindings(unittest.TestCase): def test_construct_init_bindings(self): """ This is issue https://github.com/RDFLib/rdflib/issues/1001 """ g1 = Graph() q_str = (""" PREFIX : <urn:ns1:> CONSTRUCT { ?uri :prop1 ?val1; :prop2 ?c . } WHERE { bind(uri(concat("urn:ns1:", ?a)) as ?uri) bind(?b as ?val1) } """) q_prepared = prepareQuery(q_str) expected = [ (URIRef('urn:ns1:A'),URIRef('urn:ns1:prop1'), Literal('B')), (URIRef('urn:ns1:A'),URIRef('urn:ns1:prop2'), Literal('C')) ] results = g1.query(q_prepared, initBindings={ 'a': Literal('A'), 'b': Literal('B'), 'c': Literal('C') }) self.assertCountEqual(list(results), expected)
Fix error handling to show error messages We removed this during a refactor, but it means we get very generic messages in the UI instead of the actual error string.
"""Helpers for capturing requests exceptions.""" from functools import wraps from requests import RequestException, exceptions from via.exceptions import BadURL, UnhandledException, UpstreamServiceError REQUESTS_BAD_URL = ( exceptions.MissingSchema, exceptions.InvalidSchema, exceptions.InvalidURL, exceptions.URLRequired, ) REQUESTS_UPSTREAM_SERVICE = ( exceptions.ConnectionError, exceptions.Timeout, exceptions.TooManyRedirects, exceptions.SSLError, ) def _get_message(err): return err.args[0] if err.args else None def handle_errors(inner): """Translate errors into our application errors.""" @wraps(inner) def deco(*args, **kwargs): try: return inner(*args, **kwargs) except REQUESTS_BAD_URL as err: raise BadURL(_get_message(err)) from err except REQUESTS_UPSTREAM_SERVICE as err: raise UpstreamServiceError(_get_message(err)) from err except RequestException as err: raise UnhandledException(_get_message(err)) from err return deco def iter_handle_errors(inner): """Translate errors into our application errors.""" @wraps(inner) def deco(*args, **kwargs): try: yield from inner(*args, **kwargs) except REQUESTS_BAD_URL as err: raise BadURL(_get_message(err)) from None except REQUESTS_UPSTREAM_SERVICE as err: raise UpstreamServiceError(_get_message(err)) from None except RequestException as err: raise UnhandledException(_get_message(err)) from None return deco
"""Helpers for capturing requests exceptions.""" from functools import wraps from requests import RequestException, exceptions from via.exceptions import BadURL, UnhandledException, UpstreamServiceError REQUESTS_BAD_URL = ( exceptions.MissingSchema, exceptions.InvalidSchema, exceptions.InvalidURL, exceptions.URLRequired, ) REQUESTS_UPSTREAM_SERVICE = ( exceptions.ConnectionError, exceptions.Timeout, exceptions.TooManyRedirects, exceptions.SSLError, ) def handle_errors(inner): """Translate errors into our application errors.""" @wraps(inner) def deco(*args, **kwargs): try: return inner(*args, **kwargs) except REQUESTS_BAD_URL as err: raise BadURL() from err except REQUESTS_UPSTREAM_SERVICE as err: raise UpstreamServiceError() from err except RequestException as err: raise UnhandledException() from err return deco def iter_handle_errors(inner): """Translate errors into our application errors.""" @wraps(inner) def deco(*args, **kwargs): try: yield from inner(*args, **kwargs) except REQUESTS_BAD_URL as err: raise BadURL(err.args[0]) from None except REQUESTS_UPSTREAM_SERVICE as err: raise UpstreamServiceError(err.args[0]) from None except RequestException as err: raise UnhandledException(err.args[0]) from None return deco
Sort inheritance map written to file
package net.md_5.specialsource; import com.google.common.base.Joiner; import java.io.File; import java.io.PrintWriter; import java.util.*; public class InheritanceMap { private final Map<String, ArrayList<String>> inheritanceMap = new HashMap<String, ArrayList<String>>(); public void generate(List<IInheritanceProvider> inheritanceProviders, Collection<String> classes) { for (String className : classes) { ArrayList<String> parents = getParents(inheritanceProviders, className); if (parents == null) { System.out.println("No inheritance information found for "+className); } else { inheritanceMap.put(className, parents); } } } private ArrayList<String> getParents(List<IInheritanceProvider> inheritanceProviders, String className) { for (IInheritanceProvider inheritanceProvider : inheritanceProviders) { // // ask each provider for inheritance information on the class, until one responds // TODO: refactor with JarRemapper tryClimb? List<String> parents = inheritanceProvider.getParents(className); if (parents != null) { return (ArrayList<String>) parents; } } return null; } public void save(PrintWriter writer) { List<String> classes = new ArrayList<String>(inheritanceMap.keySet()); Collections.sort(classes); for (String className : classes) { writer.print(className); writer.print(' '); List<String> parents = inheritanceMap.get(className); writer.println(Joiner.on(' ').join(parents)); } } }
package net.md_5.specialsource; import com.google.common.base.Joiner; import java.io.File; import java.io.PrintWriter; import java.util.*; public class InheritanceMap { private final Map<String, ArrayList<String>> inheritanceMap = new HashMap<String, ArrayList<String>>(); public void generate(List<IInheritanceProvider> inheritanceProviders, Collection<String> classes) { for (String className : classes) { ArrayList<String> parents = getParents(inheritanceProviders, className); if (parents == null) { System.out.println("No inheritance information found for "+className); } else { inheritanceMap.put(className, parents); } } } private ArrayList<String> getParents(List<IInheritanceProvider> inheritanceProviders, String className) { for (IInheritanceProvider inheritanceProvider : inheritanceProviders) { // // ask each provider for inheritance information on the class, until one responds // TODO: refactor with JarRemapper tryClimb? List<String> parents = inheritanceProvider.getParents(className); if (parents != null) { return (ArrayList<String>) parents; } } return null; } public void save(PrintWriter writer) { for (String className : inheritanceMap.keySet()) { writer.print(className); writer.print(' '); List<String> parents = inheritanceMap.get(className); writer.println(Joiner.on(' ').join(parents)); } } }
Fix closure for team filteR
<?php namespace App\Nova\Filters; use App\Team; use Illuminate\Http\Request; use Laravel\Nova\Filters\Filter; class UserTeam extends Filter { /** * The filter's component. * * @var string */ public $component = 'select-filter'; /** * Apply the filter to the given query. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $value * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Request $request, $query, $value) { return $query->whereHas('teams', function ($query) use ($value) { $query->where('id', '=', $value); }); } /** * Get the filter's available options. * * @param \Illuminate\Http\Request $request * @return array */ public function options(Request $request) { $teams = []; if ($request->user()->can('read-teams')) { $teams = Team::where('attendable', 1) ->when($request->user()->cant('read-teams-hidden'), function ($query) { $query->where('visible', 1); })->get() ->mapWithKeys(function ($item) { return [$item['name'] => $item['id']]; })->toArray(); } return $teams; } }
<?php namespace App\Nova\Filters; use App\Team; use Illuminate\Http\Request; use Laravel\Nova\Filters\Filter; class UserTeam extends Filter { /** * The filter's component. * * @var string */ public $component = 'select-filter'; /** * Apply the filter to the given query. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $value * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Request $request, $query, $value) { return $query->whereHas('teams', function ($query) { $query->where('id', '=', $value); }); } /** * Get the filter's available options. * * @param \Illuminate\Http\Request $request * @return array */ public function options(Request $request) { $teams = []; if ($request->user()->can('read-teams')) { $teams = Team::where('attendable', 1) ->when($request->user()->cant('read-teams-hidden'), function ($query) { $query->where('visible', 1); })->get() ->mapWithKeys(function ($item) { return [$item['name'] => $item['id']]; })->toArray(); } return $teams; } }
Fix delete free response subclass response deletion on rotation bug
package org.adaptlab.chpir.android.survey.QuestionFragments; import org.adaptlab.chpir.android.survey.QuestionFragment; import org.adaptlab.chpir.android.survey.R; import android.text.Editable; import android.text.TextWatcher; import android.view.ViewGroup; import android.widget.EditText; public class FreeResponseQuestionFragment extends QuestionFragment { private String mText = ""; private EditText mFreeText; // This is used to restrict allowed input in subclasses. protected void beforeAddViewHook(EditText editText) { } @Override public void createQuestionComponent(ViewGroup questionComponent) { mFreeText = new EditText(getActivity()); beforeAddViewHook(mFreeText); mFreeText.setHint(R.string.free_response_edittext); mFreeText.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { mText = s.toString(); saveResponse(); } // Required by interface public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); questionComponent.addView(mFreeText); } @Override protected String serialize() { return mText; } @Override protected void deserialize(String responseText) { mFreeText.setText(responseText); } }
package org.adaptlab.chpir.android.survey.QuestionFragments; import org.adaptlab.chpir.android.survey.QuestionFragment; import org.adaptlab.chpir.android.survey.R; import android.text.Editable; import android.text.TextWatcher; import android.view.ViewGroup; import android.widget.EditText; public class FreeResponseQuestionFragment extends QuestionFragment { private String mText = ""; private EditText mFreeText; // This is used to restrict allowed input in subclasses. protected void beforeAddViewHook(EditText editText) { } @Override public void createQuestionComponent(ViewGroup questionComponent) { mFreeText = new EditText(getActivity()); mFreeText.setHint(R.string.free_response_edittext); mFreeText.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { mText = s.toString(); saveResponse(); } // Required by interface public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); beforeAddViewHook(mFreeText); questionComponent.addView(mFreeText); } @Override protected String serialize() { return mText; } @Override protected void deserialize(String responseText) { mFreeText.setText(responseText); } }
Fix unescaped content in training progress description templatetag This template tag was using content from entry notes directly. In cases of some users this messed up the display of label in the templates.
from django import template from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(escape(progress.notes)) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
from django import template from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' else: switch = { 'n': 'warning', 'f': 'danger', 'p': 'success', } additional_label = switch[progress.state] fmt = 'label label-{}'.format(additional_label) return mark_safe(fmt) @register.simple_tag def progress_description(progress): assert isinstance(progress, TrainingProgress) text = '{discarded}{state} {type}<br />{evaluated_by}<br />on {day}.{notes}'.format( discarded='discarded ' if progress.discarded else '', state=progress.get_state_display(), type=progress.requirement, evaluated_by=('evaluated by {}'.format( progress.evaluated_by.full_name) if progress.evaluated_by is not None else 'submitted'), day=progress.created_at.strftime('%A %d %B %Y at %H:%M'), notes='<br />Notes: {}'.format(progress.notes) if progress.notes else '', ) text = text[0].upper() + text[1:] return mark_safe(text)
Fix class names in strings
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Notification; use Flarum\Event\ConfigureNotificationTypes; use Flarum\Foundation\AbstractServiceProvider; use Flarum\User\User; use ReflectionClass; class NotificationServiceProvider extends AbstractServiceProvider { /** * {@inheritdoc} */ public function boot() { $this->registerNotificationTypes(); } /** * Register notification types. */ public function registerNotificationTypes() { $blueprints = [ 'Flarum\Notification\Blueprint\DiscussionRenamedBlueprint' => ['alert'] ]; $this->app->make('events')->fire( new ConfigureNotificationTypes($blueprints) ); foreach ($blueprints as $blueprint => $enabled) { Notification::setSubjectModel( $type = $blueprint::getType(), $blueprint::getSubjectModel() ); User::addPreference( User::getNotificationPreferenceKey($type, 'alert'), 'boolval', in_array('alert', $enabled) ); if ((new ReflectionClass($blueprint))->implementsInterface('Flarum\Notification\MailableInterface')) { User::addPreference( User::getNotificationPreferenceKey($type, 'email'), 'boolval', in_array('email', $enabled) ); } } } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Notification; use Flarum\Event\ConfigureNotificationTypes; use Flarum\Foundation\AbstractServiceProvider; use Flarum\User\User; use ReflectionClass; class NotificationServiceProvider extends AbstractServiceProvider { /** * {@inheritdoc} */ public function boot() { $this->registerNotificationTypes(); } /** * Register notification types. */ public function registerNotificationTypes() { $blueprints = [ 'Flarum\Notification\Notification\DiscussionRenamedBlueprint' => ['alert'] ]; $this->app->make('events')->fire( new ConfigureNotificationTypes($blueprints) ); foreach ($blueprints as $blueprint => $enabled) { Notification::setSubjectModel( $type = $blueprint::getType(), $blueprint::getSubjectModel() ); User::addPreference( User::getNotificationPreferenceKey($type, 'alert'), 'boolval', in_array('alert', $enabled) ); if ((new ReflectionClass($blueprint))->implementsInterface('Flarum\Notification\Notification\MailableInterface')) { User::addPreference( User::getNotificationPreferenceKey($type, 'email'), 'boolval', in_array('email', $enabled) ); } } } }
Add classname prop to render
import React from 'react'; import cx from 'classnames'; import Col from './Col'; import Icon from './Icon'; class Navbar extends React.Component { constructor(props) { super(props); this.renderSideNav = this.renderSideNav.bind(this); } componentDidMount() { if ($ !== undefined) { $('.button-collapse').sideNav(); } } renderSideNav() { return ( <ul id="nav-mobile" className="side-nav"> {this.props.children} </ul> ); } render() { let {brand, className, ...props} = this.props; let classes = { right: this.props.right, 'hide-on-med-and-down': true }; let brandClasses = { 'brand-logo': true, right: this.props.left }; return ( <nav className={className}> <div className='nav-wrapper'> <Col s={12}> <a href='/' className={cx(brandClasses)}>{brand}</a> <ul className={cx(className, classes)}> {this.props.children} </ul> {this.renderSideNav()} <a className='button-collapse' href='#' data-activates='nav-mobile'> <Icon>view_headline</Icon> </a> </Col> </div> </nav> ); } } Navbar.propTypes = { brand: React.PropTypes.node, children: React.PropTypes.node, className: React.PropTypes.string, left: React.PropTypes.bool, right: React.PropTypes.bool }; export default Navbar;
import React from 'react'; import cx from 'classnames'; import Col from './Col'; import Icon from './Icon'; class Navbar extends React.Component { constructor(props) { super(props); this.renderSideNav = this.renderSideNav.bind(this); } componentDidMount() { if ($ !== undefined) { $('.button-collapse').sideNav(); } } render() { let {brand, className, ...props} = this.props; let classes = { right: this.props.right, 'hide-on-med-and-down': true }; let brandClasses = { 'brand-logo': true, right: this.props.left }; return ( <nav> <div className='nav-wrapper'> <Col s={12}> <a href='/' className={cx(brandClasses)}>{brand}</a> <ul className={cx(className, classes)}> {this.props.children} </ul> {this.renderSideNav()} <a className='button-collapse' href='#' data-activates='nav-mobile'> <Icon>view_headline</Icon> </a> </Col> </div> </nav> ); } renderSideNav() { return ( <ul id="nav-mobile" className="side-nav"> {this.props.children} </ul> ); } } Navbar.propTypes = { brand: React.PropTypes.node, right: React.PropTypes.bool, left: React.PropTypes.bool, } export default Navbar;
Test blank keys are not allowed.
from document import Document import unittest class TestDocument(unittest.TestCase): def _get_document(self): spec = { "author": "John Humphreys", "content": { "title": "How to make cookies", "text": "First start by pre-heating the oven..." }, "category": "cooking", "comments": [ { "commenter": "Julio Cesar", "email": "[email protected]", "comment": "Great post dude!" }, { "commenter": "Michael Andrews", "comment": "My wife loves these." } ], "tags": ["recipe", "cookies"] } return Document(spec) def test_create_with_invalid_key_names(self): with self.assertRaises(Exception): Document({'contains space': 34}) with self.assertRaises(Exception): Document({'': 45}) def test_creates_nested_document_tree(self): document = self._get_document() self.assertIsInstance(document['content'], Document) self.assertIsInstance(document['comments'][0], Document) def test_provides_attribute_getters(self): document = self._get_document() self.assertEqual("cooking", document.category) self.assertEqual("Julio Cesar", document.comments[0].commenter) def test_provides_attribute_setters(self): document = self._get_document() document.category = "baking" self.assertEqual("baking", document['category'])
from document import Document import unittest class TestDocument(unittest.TestCase): def _get_document(self): spec = { "author": "John Humphreys", "content": { "title": "How to make cookies", "text": "First start by pre-heating the oven..." }, "category": "cooking", "comments": [ { "commenter": "Julio Cesar", "email": "[email protected]", "comment": "Great post dude!" }, { "commenter": "Michael Andrews", "comment": "My wife loves these." } ], "tags": ["recipe", "cookies"] } return Document(spec) def test_create_with_invalid_key_names(self): with self.assertRaises(Exception): Document({'contains space': 34}) def test_creates_nested_document_tree(self): document = self._get_document() self.assertIsInstance(document['content'], Document) self.assertIsInstance(document['comments'][0], Document) def test_provides_attribute_getters(self): document = self._get_document() self.assertEqual("cooking", document.category) self.assertEqual("Julio Cesar", document.comments[0].commenter) def test_provides_attribute_setters(self): document = self._get_document() document.category = "baking" self.assertEqual("baking", document['category'])
BAP-15687: Test and merge - fixed failed builds
<?php namespace Oro\Bundle\DataAuditBundle\EventListener; use Oro\Bundle\DataAuditBundle\Provider\AuditConfigProvider; use Oro\Bundle\EntityBundle\Event\EntityStructureOptionsEvent; use Oro\Bundle\EntityBundle\Model\EntityStructure; class EntityStructureOptionsListener { const OPTION_NAME = 'auditable'; /** @var AuditConfigProvider */ protected $auditConfigProvider; /** * @param AuditConfigProvider $auditConfigProvider */ public function __construct(AuditConfigProvider $auditConfigProvider) { $this->auditConfigProvider = $auditConfigProvider; } /** * @param EntityStructureOptionsEvent $event */ public function onOptionsRequest(EntityStructureOptionsEvent $event) { $data = $event->getData(); foreach ($data as $entityStructure) { if (!$entityStructure instanceof EntityStructure) { continue; } $className = $entityStructure->getClassName(); $entityStructure->addOption( self::OPTION_NAME, $this->auditConfigProvider->isAuditableEntity($className) ); $fields = $entityStructure->getFields(); foreach ($fields as $field) { $field->addOption( self::OPTION_NAME, $this->auditConfigProvider->isAuditableField($className, $field->getName()) ); } } $event->setData($data); } }
<?php namespace Oro\Bundle\DataAuditBundle\EventListener; use Oro\Bundle\DataAuditBundle\Provider\AuditConfigProvider; use Oro\Bundle\EntityBundle\Event\EntityStructureOptionsEvent; use Oro\Bundle\EntityBundle\Model\EntityStructure; class EntityStructureOptionsListener { const OPTION_NAME = 'auditable'; /** @var AuditConfigProvider */ protected $auditConfigProvider; /** * @param AuditConfigProvider $auditConfigProvider */ public function __construct(AuditConfigProvider $auditConfigProvider) { $this->auditConfigProvider = $auditConfigProvider; } /** * @param EntityStructureOptionsEvent $event */ public function onOptionsRequest(EntityStructureOptionsEvent $event) { $data = $event->getData(); foreach ($data as $entityStructure) { if (!$entityStructure instanceof EntityStructure) { continue; } $className = $entityStructure->getClassName(); $entityStructure->addOption( self::OPTION_NAME, $this->auditConfigProvider->isAuditableEntity($className) ); $fields = $entityStructure->getFields(); foreach ($fields as $field) { $field->addOption( self::OPTION_NAME, $this->auditConfigProvider->isAuditableField($className, $field->getName()) ); } } $event->setData($data); } }
Revert thumbnail URL change as it costs too much bandwidth for 52Poké
<?php /** * Lazyload class */ class Lazyload { public static function LinkerMakeExternalImage(&$url, &$alt, &$img) { global $wgRequest; if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true; $url = preg_replace('/^(http|https):/', '', $url); $img = '<span class="external-image" alt="' . htmlentities($alt) . '" data-url="' . htmlentities($url) . '">&nbsp;</span>'; return false; } public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) { global $wgRequest, $wgTitle; if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true; if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true; $attribs['data-url'] = $attribs['src']; $attribs['src'] = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; if (isset($attribs['srcset'])) { $attribs['data-srcset'] = $attribs['srcset']; unset($attribs['srcset']); } return true; } public static function BeforePageDisplay($out, $skin) { $out->addModules( 'ext.lazyload' ); return true; } }
<?php /** * Lazyload class */ class Lazyload { public static function LinkerMakeExternalImage(&$url, &$alt, &$img) { global $wgRequest; if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true; $url = preg_replace('/^(http|https):/', '', $url); $img = '<span class="external-image" alt="' . htmlentities($alt) . '" data-url="' . htmlentities($url) . '">&nbsp;</span>'; return false; } public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) { global $wgRequest, $wgTitle; if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true; if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true; $attribs['data-url'] = $attribs['src']; $attribs['src'] = preg_replace('#/\d+px-#', '/10px-', $attribs['src']); if (isset($attribs['srcset'])) { $attribs['data-srcset'] = $attribs['srcset']; unset($attribs['srcset']); } return true; } public static function BeforePageDisplay($out, $skin) { $out->addModules( 'ext.lazyload' ); return true; } }
Add Framework :: Pelican :: Plugins classifer for PyPI
#!/usr/bin/env python import codecs from setuptools import setup with codecs.open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='pelican-extended-sitemap', description='sitemap generator plugin for pelican', # @see http://semver.org/ version='1.2.3', author='Alexander Herrmann', author_email='[email protected]', license='MIT', url='https://github.com/dArignac/pelican-extended-sitemap', long_description=long_description, packages=[ 'extended_sitemap', 'extended_sitemap.tests', ], package_data={ 'extended_sitemap': [ 'sitemap-stylesheet.xsl', 'tests/content/articles/*.md', 'tests/content/pages/*.md', 'tests/expected/*.xml', ], }, requires=[ 'pelican' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Framework :: Pelican :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Text Processing :: Markup' ] )
#!/usr/bin/env python import codecs from setuptools import setup with codecs.open('README.rst', encoding='utf-8') as f: long_description = f.read() setup( name='pelican-extended-sitemap', description='sitemap generator plugin for pelican', # @see http://semver.org/ version='1.2.3', author='Alexander Herrmann', author_email='[email protected]', license='MIT', url='https://github.com/dArignac/pelican-extended-sitemap', long_description=long_description, packages=[ 'extended_sitemap', 'extended_sitemap.tests', ], package_data={ 'extended_sitemap': [ 'sitemap-stylesheet.xsl', 'tests/content/articles/*.md', 'tests/content/pages/*.md', 'tests/expected/*.xml', ], }, requires=[ 'pelican' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Text Processing :: Markup' ] )
Add 'image' to the attrs for VersionDetails
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSummarySerializer, UserSummarySerializer, IdentitySummarySerializer, ImageSummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() # name, change_log, allow_imaging licenses = LicenseSummarySerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) image = ImageSummarySerializer(source='application') start_date = serializers.DateTimeField() end_date = serializers.DateTimeField(allow_null=True) class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'image', 'machines', 'allow_imaging', 'licenses', 'membership', 'user', 'identity', 'start_date', 'end_date')
from core.models import ApplicationVersion as ImageVersion from rest_framework import serializers from api.v2.serializers.summaries import ( LicenseSummarySerializer, UserSummarySerializer, IdentitySummarySerializer, ImageVersionSummarySerializer) from api.v2.serializers.fields import ProviderMachineRelatedField class ImageVersionSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for ApplicationVersion (aka 'image_version') """ # NOTE: Implicitly included via 'fields' # id, application parent = ImageVersionSummarySerializer() # name, change_log, allow_imaging licenses = LicenseSummarySerializer(many=True, read_only=True) # NEW membership = serializers.SlugRelatedField( slug_field='name', read_only=True, many=True) # NEW user = UserSummarySerializer(source='created_by') identity = IdentitySummarySerializer(source='created_by_identity') machines = ProviderMachineRelatedField(many=True) start_date = serializers.DateTimeField() end_date = serializers.DateTimeField(allow_null=True) class Meta: model = ImageVersion view_name = 'api:v2:providermachine-detail' fields = ('id', 'parent', 'name', 'change_log', 'machines', 'allow_imaging', 'licenses', 'membership', 'user', 'identity', 'start_date', 'end_date')
Remove _getRequestSID function and simplified the if statement in _checkAuthentication()
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); // save whole request to data property $_POST = (array)json_decode(file_get_contents('php://input')); } /** * Universal method to return JSON object in response * * @param boolean * @param mixed array | string * @return string (json) */ protected function _returnAjax($success, $data = []) { $return["success"] = $success; if ($success === false) { // data should be string now $return["error"] = ["message" => $data]; } else { $return["data"] = $data; } print json_encode($return); die(); } /** * Check if request is sent over proper request method * @param string ("get" | "post" | "put" | "delete") */ protected function _access($allowedMethod) { if ($this->input->method() !== $allowedMethod) { $this->_returnAjax(false, "Access restricted due to wrong request method."); } } /** * Check if client is authenticated */ protected function _checkAuthentication() { $loggedIn = $this->session->userdata("loggedIn"); if (isset($loggedIn)) { return true; } $this->_returnAjax(false, "Please authenticate first."); } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); // save whole request to data property $_POST = (array)json_decode(file_get_contents('php://input')); } /** * Universal method to return JSON object in response * * @param boolean * @param mixed array | string * @return string (json) */ protected function _returnAjax($success, $data = []) { $return["success"] = $success; if ($success === false) { // data should be string now $return["error"] = ["message" => $data]; } else { $return["data"] = $data; } print json_encode($return); die(); } /** * Check if request is sent over proper request method * @param string ("get" | "post" | "put" | "delete") */ protected function _access($allowedMethod) { if ($this->input->method() !== $allowedMethod) { $this->_returnAjax(false, "Access restricted due to wrong request method."); } } /** * Check if client is authenticated */ protected function _checkAuthentication() { $loggedIn = $this->session->userdata("loggedIn"); unset($_POST["sid"]); if (isset($loggedIn) === true && $loggedIn === true) { return true; } $this->_returnAjax(false, "Please authenticate first."); } protected function _getRequestSID() { if ($this->input->method() === "get") { return $this->input->get("sid"); } return $this->input->post("sid"); } }
Use let instead of var. Fix indentation
'use strict' const mongoose = require('mongoose'); const users = JSON.parse(require('fs').readFileSync(__dirname + '/users.json')); const domains = JSON.parse(require('fs').readFileSync(__dirname + '/domains.json')); if (mongoose.connection.readyState === 0) { mongoose.connect('mongodb://localhost/test'); } let domainId; mongoose.connection.once('open', function() { mongoose.connection.db.collection('domains', function(err, col){ if (err) { throw err; } for (let i in domains) { col.insert(domains[i], function(err, result){ if (err) { throw err; } if (!domainId) { domainId = mongoose.Types.ObjectId(result.ops[0]._id); } if (domains.length-1 == i) { mongoose.connection.db.collection('users', function(err, userCol){ if (err) { throw err; } for (let i in users) { users[i].domain = domainId; console.log(domainId); userCol.insert(users[i], function(err, result){ if (err) { throw err; } if (users.length-1 == i) { process.exit(); } }) } }); } }) } }); });
'use strict' const mongoose = require('mongoose'); const users = JSON.parse(require('fs').readFileSync(__dirname + '/users.json')); const domains = JSON.parse(require('fs').readFileSync(__dirname + '/domains.json')); if (mongoose.connection.readyState === 0) { mongoose.connect('mongodb://localhost/test'); } let domainId; mongoose.connection.once('open', function() { mongoose.connection.db.collection('domains', function(err, col){ if (err) { throw err; } for (var i in domains) { col.insert(domains[i], function(err, result){ if (err) { throw err; } if (!domainId) { domainId = mongoose.Types.ObjectId(result.ops[0]._id); } if (domains.length-1 == i) { mongoose.connection.db.collection('users', function(err, userCol){ if (err) { throw err; } for (var i in users) { users[i].domain = domainId; console.log(domainId); userCol.insert(users[i], function(err, result){ if (err) { throw err; } if (users.length-1 == i) { process.exit(); } }) } } ); } }) } }); });
Revert "Allow Django Evolution to install along with Django >= 1.7." This reverts commit 28b280bb04f806f614f6f2cd25ce779b551fef9e. This was committed to the wrong branch.
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='[email protected]', maintainer='Christian Hammond', maintainer_email='[email protected]', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10,<1.7.0', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='[email protected]', maintainer='Christian Hammond', maintainer_email='[email protected]', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Fix output error in make migration command.
<?php namespace Yarak\Commands; use Yarak\Config\Config; use Yarak\Migrations\MigrationCreator; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MakeMigration extends YarakCommand { /** * Configure the command. */ protected function configure() { $this->setName('make:migration') ->setDescription('Create a new migration file.') ->setHelp('This command allows you to make migration files.') ->addArgument( 'name', InputArgument::REQUIRED, 'The name of your migration, words separated by underscores.') ->addOption( 'create', 'c', InputOption::VALUE_REQUIRED, 'The name of the table to create.' ); } /** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $create = is_null($create = $input->getOption('create')) ? false : $create; $config = Config::getInstance($this->configArray); $creator = new MigrationCreator($config); $creator->create($name, $create); $output->writeln("<info>Successfully created migration {$name}.</info>"); } }
<?php namespace Yarak\Commands; use Yarak\Config\Config; use Yarak\Migrations\MigrationCreator; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MakeMigration extends YarakCommand { /** * Configure the command. */ protected function configure() { $this->setName('make:migration') ->setDescription('Create a new migration file.') ->setHelp('This command allows you to make migration files.') ->addArgument( 'name', InputArgument::REQUIRED, 'The name of your migration, words separated by underscores.') ->addOption( 'create', 'c', InputOption::VALUE_REQUIRED, 'The name of the table to create.' ); } /** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $create = is_null($create = $input->getOption('create')) ? false : $create; $config = Config::getInstance($this->configArray); $creator = new MigrationCreator($config); $creator->create($name, $create); $this->output->writeln("<info>Successfully created migration {$name}.</info>"); } }
Use correct GitHub header name when checking requests
'use strict'; const childProcess = require('child-process-promise'); const express = require('express'); const path = require('path'); const fs = require('fs'); const configPath = path.resolve(process.cwd(), process.argv.slice().pop()); const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); const app = express(); async function build (target, args) { const commands = args.commands; const options = { cwd: args.path, }; console.log(`Deploying ${ target }...`); for (let i = 0; i < commands.length; i++) { const date = (new Date()).toLocaleDateString('sv-SE', { hour: 'numeric', minute: 'numeric', second: 'numeric', }); console.log(`${ date } Running ${ commands[i] }...`); await childProcess.exec(commands[i], options); console.log('Done'); } } app.post('/', (req, res) => { const target = req.query.target; if (config.repos[target]) { if (req.get('x-github-event') && req.get('x-github-event') === 'push') { build(target, config.repos[target]); res.status(200).send(); } else { res.status(401).send(); } } else { res.status(400).send(); } }); app.listen(config.port, config.host);
'use strict'; const childProcess = require('child-process-promise'); const express = require('express'); const path = require('path'); const fs = require('fs'); const configPath = path.resolve(process.cwd(), process.argv.slice().pop()); const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); const app = express(); async function build (target, args) { const commands = args.commands; const options = { cwd: args.path, }; console.log(`Deploying ${ target }...`); for (let i = 0; i < commands.length; i++) { const date = (new Date()).toLocaleDateString('sv-SE', { hour: 'numeric', minute: 'numeric', second: 'numeric', }); console.log(`${ date } Running ${ commands[i] }...`); await childProcess.exec(commands[i], options); console.log('Done'); } } app.post('/', (req, res) => { const target = req.query.target; if (config.repos[target]) { if(req.get('HTTP_X_GITHUB_EVENT') && req.get('HTTP_X_GITHUB_EVENT') === 'push'){ build(target, config.repos[target]); res.status(200).send(); } else { res.status(401).send(); } } else { res.status(400).send(); } }); app.listen(config.port, config.host);
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's admin module. try: before_import_registry = copy.copy(site._registry) import_module('%s.admin' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'admin'): raise
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's admin module. try: before_import_registry = copy.copy(site._registry) import_module('%s.admin' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'admin'): raise
Add Logs + API Server Key Android notification
var gcm = require('node-gcm'); exports.sendNotification = function(db, title, messageNotif) { db.serialize(function() { db.all("SELECT notification_id from notification_client", function(err, results){ if(err) { console.log('Error while getting notifications clients : ' + err); return; } // create a message with default values var message = new gcm.Message(); // or with object values var message = new gcm.Message({ collapseKey: 'demo', delayWhileIdle: true, timeToLive: 3, data: { title: title, message: messageNotif } }); var sender = new gcm.Sender(process.env.ANDROID_SERVER_KEY); //TODO var notificationIds = []; for(var notif in results) { notificationIds.push(results[notif].notification_id); } /** * Params: message-literal, registrationIds-array, No. of retries, callback-function **/ sender.send(message, notificationIds, notificationIds.length, function (err, result) { console.log(result); }); }) }) }
var gcm = require('node-gcm'); exports.sendNotification = function(db, title, messageNotif) { db.serialize(function() { db.all("SELECT notification_id from notification_client", function(err, results){ if(err) { // TODO log error return; } // create a message with default values var message = new gcm.Message(); // or with object values var message = new gcm.Message({ collapseKey: 'demo', delayWhileIdle: true, timeToLive: 3, data: { title: title, message: messageNotif } }); var sender = new gcm.Sender('insert Google Server API Key here'); //TODO var notificationIds = []; for(var notif in results) { notificationIds.push(results[notif].notification_id); } /** * Params: message-literal, registrationIds-array, No. of retries, callback-function **/ sender.send(message, notificationIds, notificationIds.length, function (err, result) { console.log(result); }); }) }) }
Make code compatible with PHP < 8
<?php declare(strict_types = 1); namespace Rebing\GraphQL\Tests\Unit\Console; use Rebing\GraphQL\Console\SchemaConfigMakeCommand; use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait; use Rebing\GraphQL\Tests\TestCase; class SchemaConfigMakeCommandTest extends TestCase { use MakeCommandAssertionTrait; /** * @dataProvider dataForMakeCommand */ public function testCommand( string $inputName, string $expectedFilename, string $expectedClassDefinition ): void { $this->assertMakeCommand( 'Schema', SchemaConfigMakeCommand::class, $inputName, $expectedFilename, 'App\\\\GraphQL\\\\Schemas', $expectedClassDefinition, ); } public function dataForMakeCommand(): array { return [ 'Example' => [ 'inputName' => 'Example', 'expectedFilename' => 'GraphQL/Schemas/Example.php', 'expectedClassDefinition' => 'Example implements ConfigConvertible', ], 'ExampleSchema' => [ 'inputName' => 'ExampleSchema', 'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php', 'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible', ], ]; } }
<?php declare(strict_types = 1); namespace Rebing\GraphQL\Tests\Unit\Console; use Rebing\GraphQL\Console\SchemaConfigMakeCommand; use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait; use Rebing\GraphQL\Tests\TestCase; class SchemaConfigMakeCommandTest extends TestCase { use MakeCommandAssertionTrait; /** * @dataProvider dataForMakeCommand */ public function testCommand( string $inputName, string $expectedFilename, string $expectedClassDefinition, ): void { $this->assertMakeCommand( 'Schema', SchemaConfigMakeCommand::class, $inputName, $expectedFilename, 'App\\\\GraphQL\\\\Schemas', $expectedClassDefinition, ); } public function dataForMakeCommand(): array { return [ 'Example' => [ 'inputName' => 'Example', 'expectedFilename' => 'GraphQL/Schemas/Example.php', 'expectedClassDefinition' => 'Example implements ConfigConvertible', ], 'ExampleSchema' => [ 'inputName' => 'ExampleSchema', 'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php', 'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible', ], ]; } }
Make the usermode +i check for WHO slightly neater.
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): if channel: if channel.name not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): destination = udata["dest"] if destination[0] == "#": if destination not in user.channels and "i" in targetUser.mode: return {} if "i" in targetUser.mode: share_channel = False for chan in user.channels: if chan in targetUser.channels: share_channel = True break if not share_channel: return {} return udata class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.invisible_mode = None def spawn(self): self.invisible_mode = InvisibleMode() return { "modes": { "uni": self.invisible_mode }, "actions": { "wholinemodify": [self.invisible_mode.checkWhoVisible] } } def cleanup(self): self.ircd.removeMode("uni") self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible)
Fix for python 2.6 support
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import division, absolute_import, with_statement, print_function, unicode_literals try: import magic except: print("python-magic module not installed...") magic = False __author__ = "Drew Bonasera" __license__ = "MPL 2.0" TYPE = "Metadata" NAME = "libmagic" DEFAULTCONF = { 'magicfile':None, 'ENABLED': True } def check(conf=DEFAULTCONF): if not conf['ENABLED']: return False if magic: return True else: return False def scan(filelist, conf=DEFAULTCONF): if conf['magicfile']: try: maaagic = magic.Magic(magic_file=conf['magicfile']) except: print("ERROR: Failed to use magic file", conf['magicfile']) maaagic = magic.Magic() else: maaagic = magic.Magic() results = [] for fname in filelist: results.append((fname, maaagic.from_file(fname).decode('UTF-8', 'replace'))) metadata = {} metadata["Name"] = NAME metadata["Type"] = TYPE metadata["Include"] = False return (results, metadata)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import division, absolute_import, with_statement, print_function, unicode_literals try: import magic except: print("python-magic module not installed...") magic = False __author__ = "Drew Bonasera" __license__ = "MPL 2.0" TYPE = "Metadata" NAME = "libmagic" DEFAULTCONF = { 'magicfile':None, 'ENABLED': True } def check(conf=DEFAULTCONF): if not conf['ENABLED']: return False if magic: return True else: return False def scan(filelist, conf=DEFAULTCONF): if conf['magicfile']: try: maaagic = magic.Magic(magic_file=conf['magicfile']) except: print("ERROR: Failed to use magic file", conf['magicfile']) maaagic = magic.Magic() else: maaagic = magic.Magic() results = [] for fname in filelist: results.append((fname, maaagic.from_file(fname).decode(encoding='UTF-8', errors='replace'))) metadata = {} metadata["Name"] = NAME metadata["Type"] = TYPE metadata["Include"] = False return (results, metadata)
Remove reference to "job" from ThreadPool
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run thread with the next value value = next(values_iter) thread.run(func, value, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
import queue import threading from multiprocessing import Queue class ThreadPool(): def __init__(self, processes=20): self.processes = processes self.threads = [Thread() for _ in range(0, processes)] self.mp_queue = Queue() def yield_dead_threads(self): for thread in self.threads: if not thread.is_alive(): yield thread def map(self, func, values): completed_count = 0 values_iter = iter(values) while completed_count < len(values): try: self.mp_queue.get_nowait() completed_count += 1 except queue.Empty: pass for thread in self.yield_dead_threads(): try: # run next job job = next(values_iter) thread.run(func, job, self.mp_queue) except StopIteration: break def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): pass class Thread(): def __init__(self): self.thread = None def run(self, target, *args, **kwargs): self.thread = threading.Thread(target=target, args=args, kwargs=kwargs) self.thread.start() def is_alive(self): if self.thread: return self.thread.is_alive() else: return False
Remove usage of unused package in npmalerets.js
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var semver = require('semver'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
Remove check for network roaming
package org.mozilla.mozstumbler; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; final class NetworkUtils { private static final String LOGTAG = NetworkUtils.class.getName(); private NetworkUtils() { } @SuppressWarnings("deprecation") static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { Log.e(LOGTAG, "ConnectivityManager is null!"); return false; } if (!cm.getBackgroundDataSetting()) { Log.w(LOGTAG, "Background data is restricted!"); return false; } NetworkInfo network = cm.getActiveNetworkInfo(); if (network == null) { Log.w(LOGTAG, "No active network!"); return false; } if (!network.isAvailable()) { Log.w(LOGTAG, "Active network is not available!"); return false; } if (!network.isConnected()) { Log.w(LOGTAG, "Active network is not connected!"); return false; } return true; // Network is OK! } static String getUserAgentString(Context context) { String appName = context.getString(R.string.app_name); String appVersion = PackageUtils.getAppVersion(context); // "MozStumbler/X.Y.Z" return appName + '/' + appVersion; } }
package org.mozilla.mozstumbler; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; final class NetworkUtils { private static final String LOGTAG = NetworkUtils.class.getName(); private NetworkUtils() { } @SuppressWarnings("deprecation") static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { Log.e(LOGTAG, "ConnectivityManager is null!"); return false; } if (!cm.getBackgroundDataSetting()) { Log.w(LOGTAG, "Background data is restricted!"); return false; } NetworkInfo network = cm.getActiveNetworkInfo(); if (network == null) { Log.w(LOGTAG, "No active network!"); return false; } if (!network.isAvailable()) { Log.w(LOGTAG, "Active network is not available!"); return false; } if (!network.isConnected()) { Log.w(LOGTAG, "Active network is not connected!"); return false; } if (network.isRoaming()) { Log.w(LOGTAG, "Active network is roaming!"); return false; } return true; // Network is OK! } static String getUserAgentString(Context context) { String appName = context.getString(R.string.app_name); String appVersion = PackageUtils.getAppVersion(context); // "MozStumbler/X.Y.Z" return appName + '/' + appVersion; } }
Fix location of URL definition
"use strict"; const RequestResults = require("../constants/RequestResults"); const Utils = require("../utils/Utils"); let _token = null; let _requester = null; module.exports = { initialize: function(token, requester) { Utils.assertValidToken(token); Utils.assertValidRequester(requester); _token = token; _requester = requester; }, query: function(projectId, callback, opts = {}) { Utils.assertValidToken(_token); let endpoint = "/namespaces/"; const context = { projectId: projectId, options: opts }; const URL = _requester.getFullEndpoint(endpoint); const req = _requester.getRequest(URL, _token); if (opts.name) { req.query({name: opts.name}); } else if (opts.namespaceID) { endpoint = endpoint + opts.namespaceID; } const bodyHandler = function(resp, body, status) { if (status === RequestResults.SUCCESS) { resp.body = body; } else if (body && body.errors) { resp.error = body.errors[0].message; } }; const innerCb = Utils.createInnerCb(callback, context, bodyHandler); _requester.execute(req, innerCb); } };
"use strict"; const RequestResults = require("../constants/RequestResults"); const Utils = require("../utils/Utils"); let _token = null; let _requester = null; module.exports = { initialize: function(token, requester) { Utils.assertValidToken(token); Utils.assertValidRequester(requester); _token = token; _requester = requester; }, query: function(projectId, callback, opts = {}) { Utils.assertValidToken(_token); let endpoint = "/namespaces/"; const context = { projectId: projectId, options: opts }; const req = _requester.getRequest(URL, _token); if (opts.name) { req.query({name: opts.name}); } else if (opts.namespaceID) { endpoint = endpoint + opts.namespaceID; } const URL = _requester.getFullEndpoint(endpoint); const bodyHandler = function(resp, body, status) { if (status === RequestResults.SUCCESS) { resp.body = body; } else if (body && body.errors) { resp.error = body.errors[0].message; } }; const innerCb = Utils.createInnerCb(callback, context, bodyHandler); _requester.execute(req, innerCb); } };
Add lang, enviro in request
# -*- coding: utf-8 -*- import logging from icebergsdk.mixins.request_mixin import IcebergRequestBase logger = logging.getLogger('icebergsdk.frontmodules') class FrontModules(IcebergRequestBase): cache_key = "icebergsdk:frontmodule:data" cache_expire = 60*60 # one hour def __init__(self, *args, **kwargs): super(FrontModules, self).__init__(*args, **kwargs) self.cache = kwargs.get('cache', None) self.lang = kwargs.get('lang', "en") self.debug = kwargs.get('debug', False) def get_module_data(self, module_name): return self.modules_data['modules'][module_name] #### # Loader #### @property def modules_data(self): """ Helper to fetch Iceberg client side javascript templates """ if hasattr(self, "_modules_data"): return getattr(self, "_modules_data") if self.cache: data = self.cache.get("%s:%s" % (self.cache_key, self.lang), False) if data: setattr(self, '_modules_data', data) return data data = self.request(self.conf.ICEBERG_MODULES_URL, args = { "lang": self.lang, "enviro": self.conf.ICEBERG_ENV, "debug": self.debug }) # Do to, add lang setattr(self, '_modules_data', data) if self.cache: self.cache.set("%s:%s" % (self.cache_key, self.lang), data, self.cache_expire) return data
# -*- coding: utf-8 -*- import logging from icebergsdk.mixins.request_mixin import IcebergRequestBase logger = logging.getLogger('icebergsdk.frontmodules') class FrontModules(IcebergRequestBase): cache_key = "icebergsdk:frontmodule:data" cache_expire = 60*60 # one hour def __init__(self, *args, **kwargs): super(FrontModules, self).__init__(*args, **kwargs) self.cache = kwargs.get('cache', None) self.lang = kwargs.get('lang', "en") def get_module_data(self, module_name): return self.modules_data['modules'][module_name] #### # Loader #### @property def modules_data(self): """ Helper to fetch Iceberg client side javascript templates """ if hasattr(self, "_modules_data"): return getattr(self, "_modules_data") if self.cache: data = self.cache.get("%s:%s" % (self.cache_key, self.lang), False) if data: setattr(self, '_modules_data', data) return data data = self.request(self.conf.ICEBERG_MODULES_URL) # Do to, add lang setattr(self, '_modules_data', data) if self.cache: self.cache.set("%s:%s" % (self.cache_key, self.lang), data, self.cache_expire) return data
Fix indentation and es6 support
window.c.AdminNotificationHistory = ((m, h, _, models) => { return { controller: (args) => { const notifications = m.prop([]), getNotifications = (user) => { let notification = models.notification; notification.getPageWithToken(m.postgrest.filtersVM({ user_id: 'eq', sent_at: 'is.null' }) .user_id(user.id) .sent_at(!null) .order({ sent_at: 'desc' }) .parameters()) .then((data) => { notifications(data); }); return notifications(); }; getNotifications(args.user); return { notifications: notifications }; }, view: (ctrl) => { return m('.w-col.w-col-4', [ m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20', 'Histórico de notificações'), ctrl.notifications().map((cEvent) => { return m('.w-row.fontsize-smallest.lineheight-looser.date-event', [ m('.w-col.w-col-24', [ m('.fontcolor-secondary', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm'), ' - ', cEvent.template_name) ]), ]); }) ]); } }; }(window.m, window.c.h, window._, window.c.models));
window.c.AdminNotificationHistory = ((m, h, _, models) => { return { controller: (args) => { const notifications = m.prop([]), getNotifications = (user) => { let notification = models.notification; notification.getPageWithToken(m.postgrest.filtersVM({user_id: 'eq', sent_at: 'is.null'}).user_id(user.id).sent_at(!null).order({sent_at: 'desc'}).parameters()).then(function(data){ notifications(data); }); return notifications(); }; getNotifications(args.user); return { notifications: notifications }; }, view: (ctrl) => { return m('.w-col.w-col-4', [ m('.fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20', 'Histórico de notificações'), ctrl.notifications().map(function(cEvent) { return m('.w-row.fontsize-smallest.lineheight-looser.date-event', [ m('.w-col.w-col-24', [ m('.fontcolor-secondary', h.momentify(cEvent.sent_at, 'DD/MM/YYYY, HH:mm'), ' - ', cEvent.template_name) ]), ]); }) ]); } }; }(window.m, window.c.h, window._, window.c.models));
Increase to version 0.3.11 due to TG-dev requiring it for ming support
from setuptools import setup, find_packages import os version = '0.3.11' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='TG2, TG, sprox, Rest, internet, adminn', author='Christopher Perkins', author_email='[email protected]', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'sprox>=0.6.4', 'tgext.crud>=0.3.7', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import os version = '0.3.10' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='TG2, TG, sprox, Rest, internet, adminn', author='Christopher Perkins', author_email='[email protected]', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'sprox>=0.6.4', 'tgext.crud>=0.3.7', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Add docs and update constructor signature
<?php namespace OpenDominion; use Illuminate\Foundation\Application as LaravelApplication; class Application extends LaravelApplication { protected $appPath; /** * Create a new OpenDominion application instance. * * @param string|null $basePath */ public function __construct($basePath = null) { parent::__construct($basePath); $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app'); $this->bindPathsInContainer(); } /** * {@inheritdoc} */ public function path($path = '') { return ($this->basePath . DIRECTORY_SEPARATOR . 'src' . $this->getSuffixPath($path)); } /** * {@inheritdoc} */ public function bootstrapPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap' . $this->getSuffixPath($path)); } /** * {@inheritdoc} */ public function configPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'config' . $this->getSuffixPath($path)); } /** * {@inheritdoc} */ public function databasePath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'database' . $this->getSuffixPath($path)); } /** * {@inheritdoc} */ public function langPath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang'); } /** * {@inheritdoc} */ public function storagePath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'storage'); } /** * Get path prefixed by directory separator if not empty. * * @param string $path * @return string */ protected function getSuffixPath($path = '') { return ($path ? (DIRECTORY_SEPARATOR . $path) : ''); } }
<?php namespace OpenDominion; use Illuminate\Foundation\Application as LaravelApplication; class Application extends LaravelApplication { protected $appPath; public function __construct($basePath) { parent::__construct($basePath); $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app'); $this->bindPathsInContainer(); } public function path($path = '') { return ($this->basePath . DIRECTORY_SEPARATOR . 'src' . $this->getSuffixPath($path)); } public function bootstrapPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap' . $this->getSuffixPath($path)); } public function configPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'config' . $this->getSuffixPath($path)); } public function databasePath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'database' . $this->getSuffixPath($path)); } public function langPath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang'); } public function storagePath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'storage'); } protected function getSuffixPath($path = '') { return ($path ? (DIRECTORY_SEPARATOR . $path) : ''); } }
Make test command clean up asynchornously
package ru.vyarus.dropwizard.guice.test; import io.dropwizard.Application; import io.dropwizard.Configuration; import io.dropwizard.cli.EnvironmentCommand; import io.dropwizard.setup.Environment; import net.sourceforge.argparse4j.inf.Namespace; import org.eclipse.jetty.util.component.ContainerLifeCycle; /** * Lightweight variation of server command for testing purposes. * Handles managed objects lifecycle. * * @param <C> configuration type * @author Vyacheslav Rusakov * @since 23.10.2014 */ public class TestCommand<C extends Configuration> extends EnvironmentCommand<C> { private final Class<C> configurationClass; private ContainerLifeCycle container; public TestCommand(final Application<C> application) { super(application, "guicey-test", "Specific command to run guice context without jetty server"); cleanupAsynchronously(); configurationClass = application.getConfigurationClass(); } @Override protected void run(final Environment environment, final Namespace namespace, final C configuration) throws Exception { // simulating managed objects lifecycle support container = new ContainerLifeCycle(); environment.lifecycle().attach(container); container.start(); } public void stop() { try { container.stop(); } catch (Exception e) { throw new IllegalStateException("Failed to stop managed objects container", e); } container.destroy(); cleanup(); } @Override protected Class<C> getConfigurationClass() { return configurationClass; } }
package ru.vyarus.dropwizard.guice.test; import io.dropwizard.Application; import io.dropwizard.Configuration; import io.dropwizard.cli.EnvironmentCommand; import io.dropwizard.setup.Environment; import net.sourceforge.argparse4j.inf.Namespace; import org.eclipse.jetty.util.component.ContainerLifeCycle; /** * Lightweight variation of server command for testing purposes. * Handles managed objects lifecycle. * * @param <C> configuration type * @author Vyacheslav Rusakov * @since 23.10.2014 */ public class TestCommand<C extends Configuration> extends EnvironmentCommand<C> { private final Class<C> configurationClass; private ContainerLifeCycle container; public TestCommand(final Application<C> application) { super(application, "guicey-test", "Specific command to run guice context without jetty server"); configurationClass = application.getConfigurationClass(); } @Override protected void run(final Environment environment, final Namespace namespace, final C configuration) throws Exception { // simulating managed objects lifecycle support container = new ContainerLifeCycle(); environment.lifecycle().attach(container); container.start(); } public void stop() { try { container.stop(); } catch (Exception e) { throw new IllegalStateException("Failed to stop managed objects container", e); } container.destroy(); } @Override protected Class<C> getConfigurationClass() { return configurationClass; } }
Change event listener on input
$(document).ready(function(){ $('.popup__toggle').on('click', popup); $('.filter-drawer__toggle').on('click', openFilterDrawer); $('.create-drawer__toggle').on('click', openCreateDrawer); function popup() { $('#popup').toggleClass("popup--open"); } function openFilterDrawer() { $('#filter-drawer').toggleClass("filter-drawer--open"); } function openCreateDrawer() { $('#create-drawer').toggleClass("create-drawer--open"); } function fileHandler(event){ console.log("keis"); var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#popup').on("change", '#file', fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }
$(document).ready(function(){ $('.popup__toggle').on('click', popup); $('.filter-drawer__toggle').on('click', openFilterDrawer); $('.create-drawer__toggle').on('click', openCreateDrawer); function popup() { $('#popup').toggleClass("popup--open"); } function openFilterDrawer() { $('#filter-drawer').toggleClass("filter-drawer--open"); } function openCreateDrawer() { $('#create-drawer').toggleClass("create-drawer--open"); } function fileHandler(event){ var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element) var reader = new FileReader(); reader.onload = function(event){ var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader). $("#preview-img").attr('src', data); }; reader.readAsDataURL(file); } function addImgToInfo() { $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper'); } $('#file').on("change", fileHandler); $('#submit-img').on('click', addImgToInfo); }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }
Remove webfont from 503 page
<!DOCTYPE html> <html> <head> <title>Be right back.</title> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; color: #B0BEC5; display: table; font-weight: 100; font-family: font-family: system, -apple-system, ".SFNSText-Regular", "San Francisco", "Roboto", "Segoe UI", "Helvetica Neue", "Lucida Grande", sans-serif; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 72px; margin-bottom: 40px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">The site is temporarily unavailable (503).</div> </div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>Be right back.</title> <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; color: #B0BEC5; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 72px; margin-bottom: 40px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">Be right back.</div> </div> </div> </body> </html>
Exclude tests directory from install
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fabtools', version='0.1', description='Tools for writing awesome Fabric files', author='Ronan Amicel', author_email='[email protected]', url='http://github.com/ronnix/fabtools', install_requires=[ "fabric>=1.2.0", ], setup_requires=[], tests_require=[ "unittest2", "mock", ], packages=find_packages(exclude=['ez_setup', 'tests']), include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Software Distribution', 'Topic :: System :: Systems Administration', ], )
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fabtools', version='0.1', description='Tools for writing awesome Fabric files', author='Ronan Amicel', author_email='[email protected]', url='http://github.com/ronnix/fabtools', install_requires=[ "fabric>=1.2.0", ], setup_requires=[], tests_require=[ "unittest2", "mock", ], packages=find_packages(exclude=['ez_setup']), include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Software Distribution', 'Topic :: System :: Systems Administration', ], )
Add some options for prototype handler.
(function ($) { var methods = { init: function(options) { var settings = $.extend({ 'prototypePrefix': false, 'prototypeElementPrefix': '<hr />', 'containerSelector': false, }, options); return this.each(function() { show($(this), false); $(this).change(function() { show($(this), true); }); function show(element, replace) { var id = element.attr('id'); var selectedValue = element.val(); var prototypePrefix = id; if (false != settings.prototypePrefix) { prototypePrefix = settings.prototypePrefix; } var prototypeElement = $('#' + prototypePrefix + '_' + selectedValue); var container; if (settings.containerSelector) { container = $(settings.containerSelector); } else { container = $(prototypeElement.data('container')); } if (replace) { container.html(settings.prototypeElementPrefix + prototypeElement.data('prototype')); } else if (!container.html().trim()) { container.html(settings.prototypeElementPrefix + prototypeElement.data('prototype')); } }; }); } }; $.fn.handlePrototypes = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error( 'Method ' + method + ' does not exist on jQuery.handlePrototypes' ); } }; })(jQuery);
(function ($) { var methods = { init: function(options) { return this.each(function() { show($(this), false); $(this).change(function() { show($(this), true); }); function show(element, replace) { var id = element.attr('id'); var selectedValue = element.val(); var prototypeElement = $('#' + id + '_' + selectedValue); var container = $(prototypeElement.data('container')); if (replace) { container.html('<hr />' + prototypeElement.data('prototype')); } else if (!container.html().trim()) { container.html('<hr />' + prototypeElement.data('prototype')); } }; }); } }; $.fn.handlePrototypes = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error( 'Method ' + method + ' does not exist on jQuery.handlePrototypes' ); } }; })(jQuery);
Revert "fixed deleting repositories doenst always work" This reverts commit 81be538dfc24b1088959c9ae4e6d7aad31667897. The loop was ignored. See PR #54
'use strict'; /** * @ngdoc function * @name docker-registry-frontend.controller:DeleteRepositoryController * @description * # DeleteRepositoryController * Controller of the docker-registry-frontend */ angular.module('delete-repository-controller', ['registry-services']) .controller('DeleteRepositoryController', ['$scope', '$route', '$modalInstance', '$window', 'Repository', 'items', 'information', function($scope, $route, $modalInstance, $window, Repository, items, information){ $scope.items = items; $scope.information = information; // Callback that triggers deletion of tags and reloading of page $scope.ok = function () { angular.forEach($scope.items, function(value, key) { var repoStr = value; var repoUser = value.split("/")[0]; var repoName = value.split("/")[1]; var repo = { repoUser: repoUser, repoName: repoName }; Repository.delete(repo, // success function(value, responseHeaders) { toastr.success('Deleted repository: ' + repoStr); }, // error function(httpResponse) { toastr.error('Failed to delete repository: ' + repoStr + ' Response: ' + httpResponse.statusText); } ); }); $modalInstance.close(); // Go to the repositories page $window.location.href = '#/repositories'; $route.reload(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
'use strict'; /** * @ngdoc function * @name docker-registry-frontend.controller:DeleteRepositoryController * @description * # DeleteRepositoryController * Controller of the docker-registry-frontend */ angular.module('delete-repository-controller', ['registry-services']) .controller('DeleteRepositoryController', ['$scope', '$route', '$modalInstance', '$window', 'Repository', 'items', 'information', function($scope, $route, $modalInstance, $window, Repository, items, information){ $scope.items = items; $scope.information = information; // Callback that triggers deletion of tags and reloading of page $scope.ok = function () { angular.forEach($scope.items, function(value, key) { var repoStr = value; var repoUser = value.split("/")[0]; var repoName = value.split("/")[1]; var repo = { repoUser: repoUser, repoName: repoName }; var done = function() { // Go to the repositories page $window.location.href = '#/repositories'; $route.reload(); } Repository.delete(repo, // success function(value, responseHeaders) { toastr.success('Deleted repository: ' + repoStr); done(); }, // error function(httpResponse) { toastr.error('Failed to delete repository: ' + repoStr + ' Response: ' + httpResponse.statusText); done(); } ); }); $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
Hide the Contract details when the selected point changes
angular.module("yds").controller("TrafficCountsController", ["$scope", "$timeout", "DashboardService", function ($scope, $timeout, DashboardService) { var scope = $scope; scope.galwayProjectId = "http://linkedeconomy.org/resource/Contract/AwardNotice/2013208591/5795646"; scope.lang = "en"; scope.showGrid = true; scope.showProjectInfo = false; // Create the object for the clicked traffic point scope.selectedPoint = { "point": null }; /** * Get the selected contract from the DashboardService, and show or hide the Contract details */ var gridSelectionHandler = function () { var selectedContract = _.first(DashboardService.getGridSelection("galway_contract")); DashboardService.setSelectedProject(selectedContract, null); scope.showProjectInfo = false; $timeout(function () { scope.showProjectInfo = !_.isUndefined(selectedContract); }); }; // Watch changes in the selected point, and set it as selected in the DashboardService scope.$watch("selectedPoint.point", function (newPoint) { // Force a refresh of the related contracts grid scope.showGrid = false; scope.showProjectInfo = false; $timeout(function () { scope.showGrid = true; DashboardService.setGridSelection("galway_contract", undefined); DashboardService.setGridSelection("galway_traffic_point", newPoint); }); }); // Watch for changes in the selected contract, to show the Contract details page DashboardService.subscribeGridSelectionChanges(scope, gridSelectionHandler); } ]);
angular.module("yds").controller("TrafficCountsController", ["$scope", "$timeout", "DashboardService", function ($scope, $timeout, DashboardService) { var scope = $scope; scope.galwayProjectId = "http://linkedeconomy.org/resource/Contract/AwardNotice/2013208591/5795646"; scope.lang = "en"; scope.showGrid = true; scope.showProjectInfo = false; // Create the object for the clicked traffic point scope.selectedPoint = { "point": null }; /** * Get the selected contract from the DashboardService, and show or hide the Contract details */ var gridSelectionHandler = function () { var selectedContract = _.first(DashboardService.getGridSelection("galway_contract")); DashboardService.setSelectedProject(selectedContract, null); scope.showProjectInfo = false; $timeout(function () { scope.showProjectInfo = !_.isUndefined(selectedContract); }); }; // Watch changes in the selected point, and set it as selected in the DashboardService scope.$watch("selectedPoint.point", function (newPoint) { // Force a refresh of the related contracts grid scope.showGrid = false; scope.showProjectInfo = false; $timeout(function () { scope.showGrid = true; DashboardService.setGridSelection("galway_traffic_point", newPoint); }); }); // Watch for changes in the selected contract, to show the Contract details page DashboardService.subscribeGridSelectionChanges(scope, gridSelectionHandler); } ]);
Allow more dummy calls to ID Broker.
<?php namespace Sil\SilAuth\tests\fakes; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use Psr\Log\LoggerInterface; use Sil\SilAuth\auth\Authenticator; use Sil\Idp\IdBroker\Client\IdBrokerClient; use Sil\SilAuth\auth\IdBroker; abstract class FakeIdBroker extends IdBroker { public function __construct( string $baseUri, string $accessToken, LoggerInterface $logger, string $idpDomainName = 'fake.example.com' ) { parent::__construct($baseUri, $accessToken, $logger, $idpDomainName); // Now replace the client with one that will return the desired response. $this->client = new IdBrokerClient($baseUri, $accessToken, [ 'http_client_options' => [ 'handler' => HandlerStack::create(new MockHandler( /* Set up several, since this may be called multiple times * during a test: */ array_fill( 0, Authenticator::BLOCK_AFTER_NTH_FAILED_LOGIN * 2, $this->getDesiredResponse() ) )), ], ]); } abstract protected function getDesiredResponse(); }
<?php namespace Sil\SilAuth\tests\fakes; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; use Sil\SilAuth\auth\IdBroker; abstract class FakeIdBroker extends IdBroker { public function __construct( string $baseUri, string $accessToken, LoggerInterface $logger, string $idpDomainName = 'fake.example.com' ) { parent::__construct($baseUri, $accessToken, $logger, $idpDomainName); // Now replace the client with one that will return the desired response. $this->client = new IdBrokerClient($baseUri, $accessToken, [ 'http_client_options' => [ 'handler' => HandlerStack::create(new MockHandler([ /* Set up several, since this may be called multiple times * during a test: */ $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), $this->getDesiredResponse(), ])), ], ]); } abstract protected function getDesiredResponse(); }
Hide the Invite button in topics in secured categories
/** This view is used for rendering the buttons at the footer of the topic @class TopicFooterButtonsView @extends Discourse.ContainerView @namespace Discourse @module Discourse **/ Discourse.TopicFooterButtonsView = Discourse.ContainerView.extend({ elementId: 'topic-footer-buttons', topicBinding: 'controller.content', init: function() { this._super(); this.createButtons(); }, // Add the buttons below a topic createButtons: function() { var topic = this.get('topic'); if (Discourse.User.current()) { if (!topic.get('isPrivateMessage')) { // We hide some controls from private messages if (this.get('topic.details.can_invite_to') && !this.get('topic.category.read_restricted')) { this.attachViewClass(Discourse.InviteReplyButton); } this.attachViewClass(Discourse.StarButton); this.attachViewClass(Discourse.ShareButton); this.attachViewClass(Discourse.ClearPinButton); if (this.get('topic.details.can_flag_topic')) { this.attachViewClass(Discourse.FlagTopicButton); } } if (this.get('topic.details.can_create_post')) { this.attachViewClass(Discourse.ReplyButton); } this.attachViewClass(Discourse.NotificationsButton); this.trigger('additionalButtons', this); } else { // If not logged in give them a login control this.attachViewClass(Discourse.LoginReplyButton); } } });
/** This view is used for rendering the buttons at the footer of the topic @class TopicFooterButtonsView @extends Discourse.ContainerView @namespace Discourse @module Discourse **/ Discourse.TopicFooterButtonsView = Discourse.ContainerView.extend({ elementId: 'topic-footer-buttons', topicBinding: 'controller.content', init: function() { this._super(); this.createButtons(); }, // Add the buttons below a topic createButtons: function() { var topic = this.get('topic'); if (Discourse.User.current()) { if (!topic.get('isPrivateMessage')) { // We hide some controls from private messages if (this.get('topic.details.can_invite_to')) { this.attachViewClass(Discourse.InviteReplyButton); } this.attachViewClass(Discourse.StarButton); this.attachViewClass(Discourse.ShareButton); this.attachViewClass(Discourse.ClearPinButton); if (this.get('topic.details.can_flag_topic')) { this.attachViewClass(Discourse.FlagTopicButton); } } if (this.get('topic.details.can_create_post')) { this.attachViewClass(Discourse.ReplyButton); } this.attachViewClass(Discourse.NotificationsButton); this.trigger('additionalButtons', this); } else { // If not logged in give them a login control this.attachViewClass(Discourse.LoginReplyButton); } } });
Move variable assignment into function.
$(document).ready(function() { var locationPathName = location.pathname != '/' ? location.pathname : '/ruby/ruby/releases'; $(".top-nav a[href='" + locationPathName + "']").addClass('current'); $(".result-types-form input[type=radio]").change(function(value) { var $spinner = $(".spinner"); var xhr; // http://stackoverflow.com/questions/4551175/how-to-cancel-abort-jquery-ajax-request if(xhr && xhr.readyState != 4){ xhr.abort(); } var $resultTypesForm = $(".result-types-form"); var organizationName = $resultTypesForm.data('organization-name'); var repoName = $resultTypesForm.data('repo-name'); var name = $resultTypesForm.data('name') var resultType = $(this).val(); xhr = $.ajax({ url: "/" + organizationName + "/" + repoName + "/" + name, type: 'GET', data: { result_type: resultType }, dataType: 'script', beforeSend: function() { $spinner.toggleClass('hide'); $("#chart-container").empty(); $('html,body').animate({scrollTop:0},0); if (history && history.pushState) { history.pushState(null, '', "/" + organizationName + "/" + repoName + "/" + name + '?result_type=' + resultType); } }, complete: function() { $spinner.toggleClass('hide'); } }); }) drawReleaseChart(".release-chart"); drawChart(".chart"); })
$(document).ready(function() { var locationPathName = location.pathname != '/' ? location.pathname : '/ruby/ruby/releases'; $(".top-nav a[href='" + locationPathName + "']").addClass('current'); var $spinner = $(".spinner"); var xhr; $(".result-types-form input[type=radio]").change(function(value) { // http://stackoverflow.com/questions/4551175/how-to-cancel-abort-jquery-ajax-request if(xhr && xhr.readyState != 4){ xhr.abort(); } var $resultTypesForm = $(".result-types-form"); var organizationName = $resultTypesForm.data('organization-name'); var repoName = $resultTypesForm.data('repo-name'); var name = $resultTypesForm.data('name') var resultType = $(this).val(); xhr = $.ajax({ url: "/" + organizationName + "/" + repoName + "/" + name, type: 'GET', data: { result_type: resultType }, dataType: 'script', beforeSend: function() { $spinner.toggleClass('hide'); $("#chart-container").empty(); $('html,body').animate({scrollTop:0},0); if (history && history.pushState) { history.pushState(null, '', "/" + organizationName + "/" + repoName + "/" + name + '?result_type=' + resultType); } }, complete: function() { $spinner.toggleClass('hide'); } }); }) drawReleaseChart(".release-chart"); drawChart(".chart"); })
Update contribution comment for collate
package seedu.bulletjournal.logic.parser; /** * Provides variations of commands Note: hard-coded for v0.2, will implement nlp * for future versions * @@author A0127826Y */ public class FlexibleCommand { private String commandFromUser = ""; private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties", "delete d deletes del remove removes rm", "edit edits e change changes", "exit exits close closes logout logouts quit q", "find finds f search searches lookup", "show showall", "help helps h manual instruction instructions", "list lists l ls display displays", "select selects s choose chooses" }; /** * Constructor must take in a valid string input * * @param cfu */ public FlexibleCommand(String cfu) { commandFromUser = cfu; } /** * @return the correct command string that matches COMMAND_WORD of command * classes */ public String getCommandWord() { for (String commandGroup : commandGroups) { for (String command : commandGroup.split(" ")) { if (commandFromUser.equals(command)) { return commandGroup.split(" ")[0]; } } } return commandFromUser; } public boolean isValidCommand() { for (String commandGroup : commandGroups) { for (String command : commandGroup.split(" ")) { if (commandFromUser.equals(command)) { return true; } } } return false; } }
package seedu.bulletjournal.logic.parser; /** * Provides variations of commands Note: hard-coded for v0.2, will implement nlp * for future versions * @author A0127826Y */ public class FlexibleCommand { private String commandFromUser = ""; private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties", "delete d deletes del remove removes rm", "edit edits e change changes", "exit exits close closes logout logouts quit q", "find finds f search searches lookup", "show showall", "help helps h manual instruction instructions", "list lists l ls display displays", "select selects s choose chooses" }; /** * Constructor must take in a valid string input * @param cfu */ public FlexibleCommand(String cfu) { commandFromUser = cfu; } /** * @return the correct command string that matches COMMAND_WORD of command * classes */ public String getCommandWord() { for (String commandGroup : commandGroups) { for (String command : commandGroup.split(" ")) { if (commandFromUser.equals(command)) { return commandGroup.split(" ")[0]; } } } return commandFromUser; } public boolean isValidCommand() { for (String commandGroup : commandGroups) { for (String command : commandGroup.split(" ")) { if (commandFromUser.equals(command)) { return true; } } } return false; } }
Add errorhandling for testforblock parser.
<?php namespace gries\MControl\Server\Command\ResponseParser; class TestForBlockParser implements ResponseParserInterface { /** * Get the Server response * * @param $response * * @return mixed Response could be a string or an array */ public function getResponse($response) { // block was detected if (false !== strpos($response, 'Successfully found')) { return true; } // only meta index is wrong if (false !== strpos($response, 'value of')) { // find format: ... data value of 4 (expected: 0) $regex = "/value of ([a-zA-Z0-9_]*) \(expected/"; $matches = array(); preg_match_all($regex, $response, $matches); return $matches[1][0]; } if (false !== $tilePos = strpos($response, 'is tile.')) { // find format: ... is tile.air.name (expected: somethingelse) $regex = "/is tile.([a-zA-Z0-9_]*).name/"; $matches = array(); preg_match_all($regex, $response, $matches); return 'minecraft:' . $matches[1][0]; } // find format: ... is Wooden Planks (expected: somethingelse) $regex = "/is ([a-zA-Z0-9_\ ]*) \(expected/"; $matches = array(); preg_match_all($regex, $response, $matches); if (!isset($matches[1][0])) { throw new \LogicException(sprintf('Cant handle response: "%s" while parsing a TestForBlockOutput', $response)); } return $matches[1][0]; } }
<?php namespace gries\MControl\Server\Command\ResponseParser; class TestForBlockParser implements ResponseParserInterface { /** * Get the Server response * * @param $response * * @return mixed Response could be a string or an array */ public function getResponse($response) { // block was detected if (false !== strpos($response, 'Successfully found')) { return true; } // only meta index is wrong if (false !== strpos($response, 'value of')) { // find format: ... data value of 4 (expected: 0) $regex = "/value of ([a-zA-Z0-9_]*) \(expected/"; $matches = array(); preg_match_all($regex, $response, $matches); return $matches[1][0]; } if (false !== $tilePos = strpos($response, 'is tile.')) { // find format: ... is tile.air.name (expected: somethingelse) $regex = "/is tile.([a-zA-Z0-9_]*).name/"; $matches = array(); preg_match_all($regex, $response, $matches); return 'minecraft:' . $matches[1][0]; } // find format: ... is Wooden Planks (expected: somethingelse) $regex = "/is ([a-zA-Z0-9_\ ]*) \(expected/"; $matches = array(); preg_match_all($regex, $response, $matches); return $matches[1][0]; } }
Add notice about the license of the translation in the footer
<?php namespace Kenjis\TranslationTools\Modifier; use Kenjis\TranslationTools\Document; use Kenjis\TranslationTools\File; class AddCopyright { protected $targetLineRegExp; protected $copyright; public function __construct() { $this->targetLineRegExp = '!&copy; Copyright 2014 - 20\d\d, British Columbia Institute of Technology\.!u'; $this->copyright = '<br />Japanese Translation: <a href="http://codeigniter.jp/">CodeIgniter Users Group in Japan</a>(この日本語訳のライセンスは、<a href="https://github.com/codeigniter-jp/user_guide_src_ja/blob/develop_japanese/LICENSE.md">LICENSE.md</a> を参照してください)'; } public function add(File $html) { $content = ''; $check = false; $filename = preg_replace('/\.html\z/', '.rst', $html->getName()); foreach ($html as $line) { if ($check) { if (! preg_match('/' . preg_quote($this->copyright, '/') . '/u', $line, $matches)) { $line = rtrim($line) . $this->copyright . "\n"; echo 'Added Copyright link: ' . $html->getName() . PHP_EOL; } $check = false; } if (preg_match($this->targetLineRegExp, $line, $matches)) { $check = true; } $content .= $line; } return $content; } }
<?php namespace Kenjis\TranslationTools\Modifier; use Kenjis\TranslationTools\Document; use Kenjis\TranslationTools\File; class AddCopyright { protected $targetLineRegExp; protected $copyright; public function __construct() { $this->targetLineRegExp = '!&copy; Copyright 2014 - 20\d\d, British Columbia Institute of Technology\.!u'; $this->copyright = '<br />Japanese Translation: <a href="http://codeigniter.jp/">CodeIgniter Users Group in Japan</a>'; } public function add(File $html) { $content = ''; $check = false; $filename = preg_replace('/\.html\z/', '.rst', $html->getName()); foreach ($html as $line) { if ($check) { if (! preg_match('/' . preg_quote($this->copyright, '/') . '/u', $line, $matches)) { $line = rtrim($line) . $this->copyright . "\n"; echo 'Added Copyright link: ' . $html->getName() . PHP_EOL; } $check = false; } if (preg_match($this->targetLineRegExp, $line, $matches)) { $check = true; } $content .= $line; } return $content; } }
Fix bug with exit button for single asset view.
@extends('layouts.main') @section ('breadcrumb') <a href="{{ url()->previous() }}"> <button type="button" class="btn round-btn pull-right c-yellow"> <i class="fa fa-times fa-lg" aria-hidden="true"></i> </button> </a> {!! Breadcrumbs::render('dynamic', $asset) !!} @endsection @section ('content') <div class="row animated fadeIn"> <ul class=tabs> <li> <input type="radio" name="tabs" id="tab1" checked> <label for="tab1"> <div class="visible-xs mobile-tab"> <i class="fa fa-bomb fa-2x" aria-hidden="true"></i><br> <small>Asset</small> </div> <p class="hidden-xs">Asset</p> </label> <div id="tab-content1" class="tab-content"> <div class="dash-line"></div> <div class="col-md-12"> <div class="content-card solution"> <h4 class="h-4-1">{{ $asset->getHostname() ?? $asset->getName() }}</h4> <p>IP Address: {{ $asset->getIpAddressV4() }}</p> </div> </div> </div> </li> <li> @include('partials.vulnerabilities-tab', ['tabNo' => 2]) </li> </ul> <br style=clear:both;> </div> @endsection
@extends('layouts.main') @section ('breadcrumb') <a href="{{ redirect()->back() }}"> <button type="button" class="btn round-btn pull-right c-yellow"> <i class="fa fa-times fa-lg" aria-hidden="true"></i> </button> </a> {!! Breadcrumbs::render('dynamic', $asset) !!} @endsection @section ('content') <div class="row animated fadeIn"> <ul class=tabs> <li> <input type="radio" name="tabs" id="tab1" checked> <label for="tab1"> <div class="visible-xs mobile-tab"> <i class="fa fa-bomb fa-2x" aria-hidden="true"></i><br> <small>Asset</small> </div> <p class="hidden-xs">Asset</p> </label> <div id="tab-content1" class="tab-content"> <div class="dash-line"></div> <div class="col-md-12"> <div class="content-card solution"> <h4 class="h-4-1">{{ $asset->getHostname() ?? $asset->getName() }}</h4> <p>IP Address: {{ $asset->getIpAddressV4() }}</p> </div> </div> </div> </li> <li> @include('partials.vulnerabilities-tab', ['tabNo' => 2]) </li> </ul> <br style=clear:both;> </div> @endsection
Correct shebang to use /usr/bin/env node. /bin/env is not the usual location for the shebang line. Instead use /usr/bin/env.
#!/usr/bin/env node 'use strict'; var agent = require('superagent'); var program = require('commander'); var semver = require('semver'); var name, version; program .version(require('./package.json').version) .arguments('<name> <version>') .action(function (name_, version_) { name = name_; version = version_; }) .parse(process.argv); // TODO shouldn't be needed, probably a bug in commander if (!name) program.missingArgument('name'); if (!semver.valid(version)) { console.error('invalid version number: ' + version); process.exit(1); } var encodedName = encodeURIComponent(name); var npmURL = 'https://skimdb.npmjs.com/registry/_design/app/_view/dependentVersions?startkey=%5B%22' + encodedName + '%22%5D&endkey=%5B%22' + encodedName + '%22%2C%7B%7D%5D&reduce=false'; agent.get(npmURL) .set('Accept', 'application/json') .end(function (error, response) { if (error) { throw error; } var packages = response.body.rows.filter(function (pack) { return semver.satisfies(version, pack.key[1]); }).map(function (pack) { return pack.id; }); if (packages.length) { console.log(packages.join('\n')); } });
#!/bin/env node 'use strict'; var agent = require('superagent'); var program = require('commander'); var semver = require('semver'); var name, version; program .version(require('./package.json').version) .arguments('<name> <version>') .action(function (name_, version_) { name = name_; version = version_; }) .parse(process.argv); // TODO shouldn't be needed, probably a bug in commander if (!name) program.missingArgument('name'); if (!semver.valid(version)) { console.error('invalid version number: ' + version); process.exit(1); } var encodedName = encodeURIComponent(name); var npmURL = 'https://skimdb.npmjs.com/registry/_design/app/_view/dependentVersions?startkey=%5B%22' + encodedName + '%22%5D&endkey=%5B%22' + encodedName + '%22%2C%7B%7D%5D&reduce=false'; agent.get(npmURL) .set('Accept', 'application/json') .end(function (error, response) { if (error) { throw error; } var packages = response.body.rows.filter(function (pack) { return semver.satisfies(version, pack.key[1]); }).map(function (pack) { return pack.id; }); if (packages.length) { console.log(packages.join('\n')); } });
Access individual middleware through aggregating module
/* * Copyright (c) 2015-2017 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const middleware = require('../../../src/server/middleware') describe('correlationId', () => { describe('correlator', () => { let correlator let next let req let res beforeEach(() => { correlator = middleware.correlationId() next = jasmine.createSpy('next') req = { get: jasmine.createSpy('get') } res = { set: jasmine.createSpy('set') } }) it('should invoke the next middleware in the chain', () => { correlator(req, res, next) expect(next).toHaveBeenCalled() }) describe('when the request contains a request ID', () => { it('should echo the request ID as the correlation ID in the response', () => { const requestId = 'the-request-id' req.get.and.returnValue(requestId) correlator(req, res, next) expect(req.get).toHaveBeenCalledWith('X-Request-ID') expect(res.set).toHaveBeenCalledWith('X-Correlation-ID', requestId) }) }) describe('when the request does not contain a request ID', () => { it('should not modify the response', () => { correlator(req, res, next) expect(res.set).not.toHaveBeenCalled() }) }) }) })
/* * Copyright (c) 2015-2017 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const correlationId = require('../../../src/server/middleware/correlation-id') describe('correlationId', () => { describe('correlator', () => { let correlator let next let req let res beforeEach(() => { correlator = correlationId() next = jasmine.createSpy('next') req = { get: jasmine.createSpy('get') } res = { set: jasmine.createSpy('set') } }) it('should invoke the next middleware in the chain', () => { correlator(req, res, next) expect(next).toHaveBeenCalled() }) describe('when the request contains a request ID', () => { it('should echo the request ID as the correlation ID in the response', () => { const requestId = 'the-request-id' req.get.and.returnValue(requestId) correlator(req, res, next) expect(req.get).toHaveBeenCalledWith('X-Request-ID') expect(res.set).toHaveBeenCalledWith('X-Correlation-ID', requestId) }) }) describe('when the request does not contain a request ID', () => { it('should not modify the response', () => { correlator(req, res, next) expect(res.set).not.toHaveBeenCalled() }) }) }) })
Fix broken tiles (dev bug only).
package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj.toString()); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } }
package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } }
Fix missing testSchema in package
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid from pip.req import parse_requirements from setuptools import setup, find_packages requirements = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in requirements] readme = open('README.rst').read() setup(name='nuts', version='1.1.1', description='A Network Unit Test System', author='Andreas Stalder, David Meister, Matthias Gabriel, Urs Baumann', author_email='[email protected], [email protected], [email protected], [email protected]', url='https://github.com/HSRNetwork/Nuts', packages=find_packages(), data_files=[('lib/python2.7/site-packages/nuts/service', ['nuts/service/testSchema.yaml'])], zip_safe=False, include_package_data=True, license='MIT', keywords='network testing unit system', long_description=readme, install_requires=reqs, entry_points={ 'console_scripts': [ 'nuts = nuts.main:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid from pip.req import parse_requirements from setuptools import setup, find_packages requirements = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in requirements] readme = open('README.rst').read() setup(name='nuts', version='1.1', description='A Network Unit Test System', author='Andreas Stalder, David Meister, Matthias Gabriel, Urs Baumann', author_email='[email protected], [email protected], [email protected], [email protected]', url='https://github.com/HSRNetwork/Nuts', packages=find_packages(), zip_safe=False, include_package_data=True, license='MIT', keywords='network testing unit system', long_description=readme, install_requires=reqs, entry_points={ 'console_scripts': [ 'nuts = nuts.main:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
Fix type: NoneType --> bool
# coding: utf-8 import logging import psutil from subprocess import PIPE class FfmpegProcess(object): def __init__(self): self._cmdline = None self._process = None self._paused = False def run(self): if not self._cmdline: logging.debug('cmdline is not yet defined') return if not self.running: logging.debug('starting ffmpeg with command-line:\n`%s`', self.cmdline) # stdin pipe is required to shutdown ffmpeg gracefully (see below) self._process = psutil.Popen(self._cmdline, stdin=PIPE) def stop(self): if self.running: logging.debug('stopping ffmpeg process') self._process.resume() # emulate 'q' keyboard press to shutdown ffmpeg self._process.communicate(input='q') self._process.wait() @property def running(self): return self._process is not None and self._process.is_running() def pause(self): if self.running: if not self._paused: logging.debug('suspending ffmpeg process') self._process.suspend() self._paused = True def unpause(self): if self.running: if self._paused: logging.debug('resuming ffmpeg process') self._process.resume() self._paused = False @property def paused(self): return self._paused and self.running @property def cmdline(self): return self._cmdline @cmdline.setter def cmdline(self, value): self._cmdline = value
# coding: utf-8 import logging import psutil from subprocess import PIPE class FfmpegProcess(object): def __init__(self): self._cmdline = None self._process = None self._paused = False def run(self): if not self._cmdline: logging.debug('cmdline is not yet defined') return if not self.running: logging.debug('starting ffmpeg with command-line:\n`%s`', self.cmdline) # stdin pipe is required to shutdown ffmpeg gracefully (see below) self._process = psutil.Popen(self._cmdline, stdin=PIPE) def stop(self): if self.running: logging.debug('stopping ffmpeg process') self._process.resume() # emulate 'q' keyboard press to shutdown ffmpeg self._process.communicate(input='q') self._process.wait() @property def running(self): return self._process and self._process.is_running() def pause(self): if self.running: if not self._paused: logging.debug('suspending ffmpeg process') self._process.suspend() self._paused = True def unpause(self): if self.running: if self._paused: logging.debug('resuming ffmpeg process') self._process.resume() self._paused = False @property def paused(self): return self._paused and self.running @property def cmdline(self): return self._cmdline @cmdline.setter def cmdline(self, value): self._cmdline = value
Use urn from certificate to create username
''' Created on Aug 12, 2010 @author: jnaous ''' import logging import traceback from django.contrib.auth.backends import RemoteUserBackend from sfa.trust.gid import GID from expedient_geni.utils import get_user_urn, urn_to_username from geni.util.urn_util import URN logger = logging.getLogger("expedient_geni.backends") class GENIRemoteUserBackend(RemoteUserBackend): """ Extends the RemoteUserBackend to create GENI users. """ create_unknown_user = True def clean_username(self, username): try: # The username field should be the full certificate gid = GID(string=username) logger.debug("Getting username from %s" % gid.dump) # extract the URN in the subjectAltName urn_str = gid.get_urn() except: logger.warn("Failed to get certificate from username.") logger.warn(traceback.format_exc()) return username try: urn = URN(urn=str(urn_str)) except ValueError: return username # check if this user is one of ours home_urn = get_user_urn(urn.getName()) if home_urn == urn.urn_string(): username = urn.getName() else: username = urn_to_username(urn.urn_string()) return username class MagicWordBackend(object): """Authenticates users if the magic word "MagicWord" is given as credentials""" MAGIC_WORD = "MagicWord" def authenticate(self, magicword=None, user=None): if magicword == self.MAGIC_WORD: return user else: return None
''' Created on Aug 12, 2010 @author: jnaous ''' import logging import re from django.contrib.auth.backends import RemoteUserBackend from django.conf import settings from expedient.common.permissions.shortcuts import give_permission_to from django.contrib.auth.models import User logger = logging.getLogger("expedient_geni.backends") urn_matcher = re.compile(r"(?P<prefix>.*)\+(?P<role>.*)\+(?P<name>.*)") class GENIRemoteUserBackend(RemoteUserBackend): """ Extends the RemoteUserBackend to create GENI users. """ create_unknown_user = True def clean_username(self, username): logger.debug("Cleaning username %s" % username) match = urn_matcher.match(username) if match: if match.group("prefix") == settings.GCF_URN_PREFIX: username = match.group("name") else: username = match.group("name")+"@"+match.group("prefix") return username else: return username class MagicWordBackend(object): """Authenticates users if the magic word "MagicWord" is given as credentials""" MAGIC_WORD = "MagicWord" def authenticate(self, magicword=None, user=None): if magicword == self.MAGIC_WORD: return user else: return None
Fix up detecting if Bundler is installed
import path from 'path'; import {statNoException} from '../promise-array'; import BuildDiscoverBase from '../build-discover-base'; import {findActualExecutable} from 'spawn-rx'; const d = require('debug')('surf:build-discover-npm'); export default class DangerBuildDiscoverer extends BuildDiscoverBase { constructor(rootDir) { super(rootDir); // Danger runs concurrently with other builds this.shouldAlwaysRun = true; } async getAffinityForRootDir() { let dangerFile = path.join(this.rootDir, 'Dangerfile'); let exists = await statNoException(dangerFile); if (process.env.SURF_DISABLE_DANGER) return 0; if (!exists) return; // If we can't find Ruby or Bundler in PATH, bail if (!['ruby', 'bundle'].every((x) => findActualExecutable(x, []).cmd !== x)) { console.log(`A Dangerfile exists but can't find Ruby and Bundler in PATH, skipping`); return 0; } d(`Found Dangerfile at ${dangerFile}`); return exists ? 100 : 0; } async getBuildCommand() { let cmds = [ { cmd: 'bundle', args: ['exec', 'danger']} ]; if (!process.env.SURF_BUILD_NAME) { cmds[0].args.push('local'); } if (!process.env.DANGER_GITHUB_API_TOKEN) { process.env.DANGER_GITHUB_API_TOKEN = process.env.GITHUB_TOKEN; } return {cmds}; } }
import path from 'path'; import {statNoException} from '../promise-array'; import BuildDiscoverBase from '../build-discover-base'; import {findActualExecutable} from 'spawn-rx'; const d = require('debug')('surf:build-discover-npm'); export default class DangerBuildDiscoverer extends BuildDiscoverBase { constructor(rootDir) { super(rootDir); // Danger runs concurrently with other builds this.shouldAlwaysRun = true; } async getAffinityForRootDir() { let dangerFile = path.join(this.rootDir, 'Dangerfile'); let exists = await statNoException(dangerFile); if (process.env.SURF_DISABLE_DANGER) return 0; // If we can't find Ruby or Bundler in PATH, bail if (!['ruby', 'bundler'].find((x) => findActualExecutable(x, []).cmd !== x)) { d(`Can't find Ruby and Bundler in PATH, bailing`); return 0; } if (exists) { d(`Found Dangerfile at ${dangerFile}`); } return exists ? 100 : 0; } async getBuildCommand() { let cmds = [ { cmd: 'bundle', args: ['exec', 'danger']} ]; if (!process.env.SURF_BUILD_NAME) { cmds[0].args.push('local'); } if (!process.env.DANGER_GITHUB_API_TOKEN) { process.env.DANGER_GITHUB_API_TOKEN = process.env.GITHUB_TOKEN; } return {cmds}; } }
Fix epom to not use encoded adm
package com.xrtb.exchanges; import java.io.InputStream; import com.xrtb.pojo.BidRequest; /** * A class to handle Epom ad exchange * @author Ben M. Faul * */ public class Epom extends BidRequest { public Epom() { super(); parseSpecial(); } /** * Make a Epom bid request using a String. * @param in String. The JSON bid request for Epom * @throws Exception on JSON errors. */ public Epom(String in) throws Exception { super(in); parseSpecial(); } /** * Make a Epom bid request using an input stream. * @param in InputStream. The contents of a HTTP post. * @throws Exception on JSON errors. */ public Epom(InputStream in) throws Exception { super(in); parseSpecial(); } /** * Process special Epom stuff, sets the exchange name. */ @Override public boolean parseSpecial() { exchange = "epom"; usesEncodedAdm = false; return true; } }
package com.xrtb.exchanges; import java.io.InputStream; import com.xrtb.pojo.BidRequest; /** * A class to handle Epom ad exchange * @author Ben M. Faul * */ public class Epom extends BidRequest { public Epom() { super(); parseSpecial(); } /** * Make a Epom bid request using a String. * @param in String. The JSON bid request for Epom * @throws Exception on JSON errors. */ public Epom(String in) throws Exception { super(in); parseSpecial(); } /** * Make a Epom bid request using an input stream. * @param in InputStream. The contents of a HTTP post. * @throws Exception on JSON errors. */ public Epom(InputStream in) throws Exception { super(in); parseSpecial(); } /** * Process special Epom stuff, sets the exchange name. */ @Override public boolean parseSpecial() { exchange = "epom"; return true; } }
Add organizer_name and organizer to guarded since they're generated, not actually columns
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Event extends Model { use SoftDeletes; protected $dates = [ 'created_at', 'updated_at', 'start_time', 'end_time' ]; /** * The attributes that are not mass assignable. * * @var array */ protected $guarded = [ 'id', 'created_at', 'updated_at', 'organizer_name', 'organizer' ]; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = [ 'organizer_name' ]; public function organizer() { return $this->belongsTo('App\User', 'organizer_id'); } public function rsvps() { return $this->hasMany('App\Rsvp'); } /** * Get all of the event's attendance. */ public function attendance() { return $this->morphMany('App\Attendance', 'attendable'); } /** * Get the Payable amount */ public function getPayableAmount() { return ($this->price) ?: null; } /** * Get the organizer_name attribute for the model */ public function getOrganizerNameAttribute() { return $this->organizer->name; } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Event extends Model { use SoftDeletes; protected $dates = [ 'created_at', 'updated_at', 'start_time', 'end_time' ]; /** * The attributes that are not mass assignable. * * @var array */ protected $guarded = [ 'id', 'created_at', 'updated_at' ]; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = [ 'organizer_name' ]; public function organizer() { return $this->belongsTo('App\User', 'organizer_id'); } public function rsvps() { return $this->hasMany('App\Rsvp'); } /** * Get all of the event's attendance. */ public function attendance() { return $this->morphMany('App\Attendance', 'attendable'); } /** * Get the Payable amount */ public function getPayableAmount() { return ($this->price) ?: null; } /** * Get the organizer_name attribute for the model */ public function getOrganizerNameAttribute() { return $this->organizer->name; } }
Make ExternalProgramService use async process from tornado
from tornado.process import Subprocess from tornado import gen from subprocess import PIPE from delivery.models.execution import ExecutionResult, Execution class ExternalProgramService(object): """ A service for running external programs """ @staticmethod def run(cmd): """ Run a process and do not wait for it to finish :param cmd: the command to run as a list, i.e. ['ls','-l', '/'] :return: A instance of Execution """ p = Subprocess(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) return Execution(pid=p.pid, process_obj=p) @staticmethod @gen.coroutine def wait_for_execution(execution): """ Wait for an execution to finish :param execution: instance of Execution :return: an ExecutionResult for the execution """ status_code = yield execution.process_obj.wait_for_exit(raise_error=False) out = str(execution.process_obj.stdout.read()) err = str(execution.process_obj.stderr.read()) return ExecutionResult(out, err, status_code) @staticmethod def run_and_wait(cmd): """ Run an external command and wait for it to finish :param cmd: the command to run as a list, i.e. ['ls','-l', '/'] :return: an ExecutionResult for the execution """ execution = ExternalProgramService.run(cmd) return ExternalProgramService.wait_for_execution(execution)
import subprocess import logging from delivery.models.execution import ExecutionResult, Execution log = logging.getLogger(__name__) class ExternalProgramService(object): """ A service for running external programs """ @staticmethod def run(cmd): """ Run a process and do not wait for it to finish :param cmd: the command to run as a list, i.e. ['ls','-l', '/'] :return: A instance of Execution """ log.debug("Running command: {}".format(" ".join(cmd))) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) return Execution(pid=p.pid, process_obj=p) @staticmethod def wait_for_execution(execution): """ Wait for an execution to finish :param execution: instance of Execution :return: an ExecutionResult for the execution """ out, err = execution.process_obj.communicate() status_code = execution.process_obj.wait() return ExecutionResult(out, err, status_code) @staticmethod def run_and_wait(cmd): """ Run an external command and wait for it to finish :param cmd: the command to run as a list, i.e. ['ls','-l', '/'] :return: an ExecutionResult for the execution """ execution = ExternalProgramService.run(cmd) return ExternalProgramService.wait_for_execution(execution)
Create Database driver with configured Table name
<?php namespace IonutMilica\LaravelSettings; use IonutMilica\LaravelSettings\Drivers\Database; use IonutMilica\LaravelSettings\Drivers\Json; use IonutMilica\LaravelSettings\Drivers\Memory; use Illuminate\Support\Manager; class DriversManager extends Manager { /** * Get the default driver name. * * @return string */ public function getDefaultDriver() { return $this->config('settings.driver'); } /** * Creates a new memory driver for settings * * @return Memory */ public function createMemoryDriver() { return new Memory($this->app['config']); } /** * Creates a new database driver for settings * * @return Database */ public function createDatabaseDriver() { return new Database($this->app['db'], $this->config('settings.table')); } /** * Creates a new json driver for settings * * @return Json */ public function createJsonDriver() { return new Json($this->config('settings.json_file')); } /** * Get config data * * @param $key * @param null $default * @return mixed */ public function config($key, $default = null) { return $this->app['config']->get($key, $default); } }
<?php namespace IonutMilica\LaravelSettings; use IonutMilica\LaravelSettings\Drivers\Database; use IonutMilica\LaravelSettings\Drivers\Json; use IonutMilica\LaravelSettings\Drivers\Memory; use Illuminate\Support\Manager; class DriversManager extends Manager { /** * Get the default driver name. * * @return string */ public function getDefaultDriver() { return $this->config('settings.driver'); } /** * Creates a new memory driver for settings * * @return Memory */ public function createMemoryDriver() { return new Memory($this->app['config']); } /** * Creates a new database driver for settings * * @return Database */ public function createDatabaseDriver() { return new Database($this->app['db']); } /** * Creates a new json driver for settings * * @return Json */ public function createJsonDriver() { return new Json($this->config('settings.json_file')); } /** * Get config data * * @param $key * @param null $default * @return mixed */ public function config($key, $default = null) { return $this->app['config']->get($key, $default); } }
Make readonly attributes to boolean methods
function Entry(key, ttlInMilliSeconds, cache) { if (!key) throw new Error('invalid cache key'); if (!ttlInMilliSeconds) throw new Error('invalid TTL'); if (!cache) throw new Error('invalid storage'); this.key = key; this.ttlInMilliSeconds = ttlInMilliSeconds; this.cache = cache; this.data = { status: 0, headers: {}, body: [] }; }; Entry.prototype = { isCachable: function() { return this.data.status == 200; }, write: function(chunk, encoding) { this.data.body.push({ data: chunk, encoding: encoding }); }, finalize: function(response) { this.data.status = response.statusCode; this.data.headers = response.headers; }, hook: function(response) { var entry = this; var originalWrite = response.write; response.write = function(chunk, encoding) { entry.write(chunk, encoding); return originalWrite.call(response, chunk, encoding); }; var originalEnd = response.end; response.end = function(chunk, encoding) { entry.write(chunk, encoding); var returnValue = originalEnd.call(response, chunk, encoding); entry.finalize(response); entry.store(); return returnValue; }; }, store: function() { if (!this.isCachable()) return; this.cache.set(this.key, this.data, this.ttlInMilliSeconds); } }; exports = module.exports = Entry;
function Entry(key, ttlInMilliSeconds, cache) { if (!key) throw new Error('invalid cache key'); if (!ttlInMilliSeconds) throw new Error('invalid TTL'); if (!cache) throw new Error('invalid storage'); this.key = key; this.ttlInMilliSeconds = ttlInMilliSeconds; this.cache = cache; this.data = { status: 0, headers: {}, body: [] }; }; Entry.prototype = { get cachable() { return this.data.status == 200; }, write: function(chunk, encoding) { this.data.body.push({ data: chunk, encoding: encoding }); }, finalize: function(response) { this.data.status = response.statusCode; this.data.headers = response.headers; }, hook: function(response) { var entry = this; var originalWrite = response.write; response.write = function(chunk, encoding) { entry.write(chunk, encoding); return originalWrite.call(response, chunk, encoding); }; var originalEnd = response.end; response.end = function(chunk, encoding) { entry.write(chunk, encoding); var returnValue = originalEnd.call(response, chunk, encoding); entry.finalize(response); entry.store(); return returnValue; }; }, store: function() { if (!this.cachable) return; this.cache.set(this.key, this.data, this.ttlInMilliSeconds); } }; exports = module.exports = Entry;
Fix log_error so it now catches exceptions * This got accidentally disabled
from .. util import class_name, log class LogErrors: """ Wraps a function call to catch and report exceptions. """ def __init__(self, function, max_errors=-1): """ :param function: the function to wrap :param int max_errors: if ``max_errors`` is non-zero, then only the first ``max_errors`` error messages are printed """ self.function = function self.max_errors = max_errors self.errors = 0 def __call__(self, *args, **kwds): """ Calls ``self.function`` with the given arguments and keywords, and returns its value - or if the call throws an exception, returns None. If is ``self.max_errors`` is `0`, all the exceptions are reported, otherwise just the first ``self.max_errors`` are. """ try: return self.function(*args, **kwds) except Exception as e: args = (class_name.class_name(e),) + e.args self.errors += 1 if self.max_errors < 0 or self.errors <= self.max_errors: log.error(str(args)) elif self.errors == self.max_errors + 1: log.error('Exceeded max_errors of %d', self.max_errors)
from .. util import class_name, log class LogErrors: """ Wraps a function call to catch and report exceptions. """ def __init__(self, function, max_errors=-1): """ :param function: the function to wrap :param int max_errors: if ``max_errors`` is non-zero, then only the first ``max_errors`` error messages are printed """ self.function = function self.max_errors = max_errors self.errors = 0 def __call__(self, *args, **kwds): """ Calls ``self.function`` with the given arguments and keywords, and returns its value - or if the call throws an exception, returns None. If is ``self.max_errors`` is `0`, all the exceptions are reported, otherwise just the first ``self.max_errors`` are. """ try: return self.function(*args, **kwds) except Exception as e: args = (class_name.class_name(e),) + e.args raise self.errors += 1 if self.max_errors < 0 or self.errors <= self.max_errors: log.error(str(args)) elif self.errors == self.max_errors + 1: log.error('Exceeded max_errors of %d', self.max_errors)
[async-command] Fix service definition to apply the timeout addArgument add only one argument at a time to the construtor, right now the timeout configured by the user is never applied and it's always the default (60) value, this fixes it.
<?php namespace Enqueue\AsyncCommand\DependencyInjection; use Enqueue\AsyncCommand\Commands; use Enqueue\AsyncCommand\RunCommandProcessor; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; class AsyncCommandExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { foreach ($configs['clients'] as $client) { // BC compatibility if (!is_array($client)) { $client = [ 'name' => $client, 'command_name' => Commands::RUN_COMMAND, 'queue_name' => Commands::RUN_COMMAND, 'timeout' => 60, ]; } $id = sprintf('enqueue.async_command.%s.run_command_processor', $client['name']); $container->register($id, RunCommandProcessor::class) ->addArgument('%kernel.project_dir%') ->addArgument($client['timeout']) ->addTag('enqueue.processor', [ 'client' => $client['name'], 'command' => $client['command_name'] ?? Commands::RUN_COMMAND, 'queue' => $client['queue_name'] ?? Commands::RUN_COMMAND, 'prefix_queue' => false, 'exclusive' => true, ]) ->addTag('enqueue.transport.processor') ; } } }
<?php namespace Enqueue\AsyncCommand\DependencyInjection; use Enqueue\AsyncCommand\Commands; use Enqueue\AsyncCommand\RunCommandProcessor; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; class AsyncCommandExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { foreach ($configs['clients'] as $client) { // BC compatibility if (!is_array($client)) { $client = [ 'name' => $client, 'command_name' => Commands::RUN_COMMAND, 'queue_name' => Commands::RUN_COMMAND, 'timeout' => 60, ]; } $id = sprintf('enqueue.async_command.%s.run_command_processor', $client['name']); $container->register($id, RunCommandProcessor::class) ->addArgument('%kernel.project_dir%', $client['timeout']) ->addTag('enqueue.processor', [ 'client' => $client['name'], 'command' => $client['command_name'] ?? Commands::RUN_COMMAND, 'queue' => $client['queue_name'] ?? Commands::RUN_COMMAND, 'prefix_queue' => false, 'exclusive' => true, ]) ->addTag('enqueue.transport.processor') ; } } }
Improve output messages for backup:monitor command
<?php namespace Spatie\Backup\Commands; use Spatie\Backup\Events\HealthyBackupWasFound; use Spatie\Backup\Events\UnhealthyBackupWasFound; use Spatie\Backup\Tasks\Monitor\BackupDestinationStatusFactory; class MonitorCommand extends BaseCommand { /** @var string */ protected $signature = 'backup:monitor'; /** @var string */ protected $description = 'Monitor the health of all backups.'; public function handle() { if (config()->has('backup.monitorBackups')) { $this->warn("Warning! Your config file still uses the old monitorBackups key. Update it to monitor_backups."); } $hasError = false; $statuses = BackupDestinationStatusFactory::createForMonitorConfig(config('backup.monitor_backups')); foreach ($statuses as $backupDestinationStatus) { $backupName = $backupDestinationStatus->backupDestination()->backupName(); $diskName = $backupDestinationStatus->backupDestination()->diskName(); if ($backupDestinationStatus->isHealthy()) { $this->info("The {$backupName} backup on the {$diskName} disk is considered healthy."); event(new HealthyBackupWasFound($backupDestinationStatus)); } else { $hasError = true; $this->error("The {$backupName} backup on the {$diskName} disk is considered unhealthy!"); event(new UnhealthyBackupWasFound($backupDestinationStatus)); } } if ($hasError) { return 1; } } }
<?php namespace Spatie\Backup\Commands; use Spatie\Backup\Events\HealthyBackupWasFound; use Spatie\Backup\Events\UnhealthyBackupWasFound; use Spatie\Backup\Tasks\Monitor\BackupDestinationStatusFactory; class MonitorCommand extends BaseCommand { /** @var string */ protected $signature = 'backup:monitor'; /** @var string */ protected $description = 'Monitor the health of all backups.'; public function handle() { if (config()->has('backup.monitorBackups')) { $this->warn("Warning! Your config file still uses the old monitorBackups key. Update it to monitor_backups."); } $hasError = false; $statuses = BackupDestinationStatusFactory::createForMonitorConfig(config('backup.monitor_backups')); foreach ($statuses as $backupDestinationStatus) { $diskName = $backupDestinationStatus->backupDestination()->diskName(); if ($backupDestinationStatus->isHealthy()) { $this->info("The backups on {$diskName} are considered healthy."); event(new HealthyBackupWasFound($backupDestinationStatus)); } else { $hasError = true; $this->error("The backups on {$diskName} are considered unhealthy!"); event(new UnhealthyBackupWasFound($backupDestinationStatus)); } } if ($hasError) { return 1; } } }
Allow the free SMS fragment limit to be 0 This updates the schema so that the free allowance has a minimum value of 0 instead of 1.
from datetime import datetime create_or_update_free_sms_fragment_limit_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST annual billing schema", "type": "object", "title": "Create", "properties": { "free_sms_fragment_limit": {"type": "integer", "minimum": 0}, }, "required": ["free_sms_fragment_limit"] } def serialize_ft_billing_remove_emails(data): results = [] billed_notifications = [x for x in data if x.notification_type != 'email'] for notification in billed_notifications: json_result = { "month": (datetime.strftime(notification.month, "%B")), "notification_type": notification.notification_type, "billing_units": notification.billable_units, "rate": float(notification.rate), "postage": notification.postage, } results.append(json_result) return results def serialize_ft_billing_yearly_totals(data): yearly_totals = [] for total in data: json_result = { "notification_type": total.notification_type, "billing_units": total.billable_units, "rate": float(total.rate), "letter_total": float(total.billable_units * total.rate) if total.notification_type == 'letter' else 0 } yearly_totals.append(json_result) return yearly_totals
from datetime import datetime create_or_update_free_sms_fragment_limit_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST annual billing schema", "type": "object", "title": "Create", "properties": { "free_sms_fragment_limit": {"type": "integer", "minimum": 1}, }, "required": ["free_sms_fragment_limit"] } def serialize_ft_billing_remove_emails(data): results = [] billed_notifications = [x for x in data if x.notification_type != 'email'] for notification in billed_notifications: json_result = { "month": (datetime.strftime(notification.month, "%B")), "notification_type": notification.notification_type, "billing_units": notification.billable_units, "rate": float(notification.rate), "postage": notification.postage, } results.append(json_result) return results def serialize_ft_billing_yearly_totals(data): yearly_totals = [] for total in data: json_result = { "notification_type": total.notification_type, "billing_units": total.billable_units, "rate": float(total.rate), "letter_total": float(total.billable_units * total.rate) if total.notification_type == 'letter' else 0 } yearly_totals.append(json_result) return yearly_totals
Replace try..except with get_policy_option call
from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility @register_policy class ProhibitImplicitScopeVariable(AbstractPolicy): def __init__(self): super(ProhibitImplicitScopeVariable, self).__init__() self.reference = 'Anti-pattern of vimrc (Scope of identifier)' self.level = Level.STYLE_PROBLEM def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether the identifier has a scope prefix. """ scope_plugin = lint_context['plugins']['scope'] explicity = scope_plugin.get_explicity_of_scope_visibility(identifier) is_autoload = scope_plugin.is_autoload_identifier(identifier) config_dict = lint_context['config'] suppress_autoload = self.get_policy_option(config_dict, 'suppress_autoload', False) is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or is_autoload and suppress_autoload) if not is_valid: self._make_description(identifier, scope_plugin) return is_valid def _make_description(self, identifier, scope_plugin): self.description = 'Make the scope explicit like `{good_example}`'.format( good_example=scope_plugin.normalize_variable_name(identifier) )
from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.plugin.scope_plugin import ExplicityOfScopeVisibility @register_policy class ProhibitImplicitScopeVariable(AbstractPolicy): def __init__(self): super(ProhibitImplicitScopeVariable, self).__init__() self.reference = 'Anti-pattern of vimrc (Scope of identifier)' self.level = Level.STYLE_PROBLEM def listen_node_types(self): return [NodeType.IDENTIFIER] def is_valid(self, identifier, lint_context): """ Whether the identifier has a scope prefix. """ linter_config = lint_context['config'] scope_plugin = lint_context['plugins']['scope'] explicity = scope_plugin.get_explicity_of_scope_visibility(identifier) is_autoload = scope_plugin.is_autoload_identifier(identifier) try: suppress_autoload = linter_config['policies'][self.name]['suppress_autoload'] except KeyError: suppress_autoload = False is_valid = (explicity is not ExplicityOfScopeVisibility.IMPLICIT or is_autoload and suppress_autoload) if not is_valid: self._make_description(identifier, scope_plugin) return is_valid def _make_description(self, identifier, scope_plugin): self.description = 'Make the scope explicit like `{good_example}`'.format( good_example=scope_plugin.normalize_variable_name(identifier) )
Fix feate manage news category
<?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Input; use App\Http\Controllers\Controller; class NewsCategoryController extends Controller { public function index() { $newscategories = \App\NewsCategory::All(); return view('admin/newscategory/index')->with('newscategories', $newscategories); } public function create() { $newscategory_cr = \App\NewsCategory::pluck('name', 'id'); return view('admin/newscategory/create')->with('newscategory_cr', $newscategory_cr); } public function edit() { $newscategory = \App\NewsCategory::find($id); return view('admin/newscategory/create')->with('newscategory', $newscategory); } public function update() { $newscategory = \App\NewsCategory::find($id); $newscategory->update(Input::all()); return redirect('/admin/newscategory') ->withSuccess('Cat has been updated.'); } public function post() { \App\NewsCategory::create(Input::all()); return redirect('/admin/newscategory')->withSuccess('Cat has been created.'); } public function delete() { $newcategory = \App\NewsCategory::find($id); $newcategory->delete(); return redirect('/admin/newscategory') ->withSuccess('News Category has been deleted.'); } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Input; use App\Http\Controllers\Controller; class NewsCategoryController extends Controller { public function index() { $newscategories = \App\NewsCategory::All(); return view('admin/newscategory/index')->with('newscategories', $newscategories); } public function create() { $newscategory_cr = \App\NewsCategory::pluck('name', 'id'); return view('admin/newscategory/create')->with('newscategory_cr', $newscategory_cr); } public function edit($) { $newscategory = \App\NewsCategory::find($id); return view('admin/newscategory/create')->with('newscategory', $newscategory); } public function update() { $newscategory = \App\NewsCategory::find($id); $newscategory->update(Input::all()); return redirect('/admin/newscategory') ->withSuccess('Cat has been updated.'); } public function post() { \App\NewsCategory::create(Input::all()); return redirect('/admin/newscategory')->withSuccess('Cat has been created.'); } public function delete() { $newcategory = \App\NewsCategory::find($id); $newcategory->delete(); return redirect('/admin/newscategory') ->withSuccess('News Category has been deleted.'); } }
[fix] Add fix for "no ca" case.
'use strict'; var fs = require('fs'), path = require('path'); /* * function readSsl (options, callback) * Reads the SSL certificate information in the * specified options: * * options.root * options.cert * options.key * options.ca */ module.exports = function (options, callback) { var read = {}; function readCertFile(key, file, next) { fs.readFile(file, function (err, data) { if (err) { return next(err); } else if (read[key]) { if (!Array.isArray(read[key])) { read[key] = [read[key]]; } read[key].push(data); return next(); } read[key] = data; next(); }); } var sources = ['cert', 'key', 'ca'] .reduce(function (acc, key) { if (!options[key]) { return acc; } var list = !Array.isArray(options[key]) ? [options[key]] : options[key]; acc.push.apply(acc, list.map(function (file) { return { key: key, file: path.join(options.root, file) }; })); return acc; }, []); (function readUntilEmpty(err) { if (err) { return callback(err); } else if (!sources.length) { return callback(null, read); } var source = sources.shift(); readCertFile(source.key, source.file, readUntilEmpty); })(); };
'use strict'; var fs = require('fs'), path = require('path'); /* * function readSsl (options, callback) * Reads the SSL certificate information in the * specified options: * * options.root * options.cert * options.key * options.ca */ module.exports = function (options, callback) { var read = {}; function readCertFile(key, file, next) { fs.readFile(file, function (err, data) { if (err) { return next(err); } else if (read[key]) { if (!Array.isArray(read[key])) { read[key] = [read[key]]; } read[key].push(data); return next(); } read[key] = data; next(); }); } var sources = ['cert', 'key', 'ca'] .reduce(function (acc, key) { var list = !Array.isArray(options[key]) ? [options[key]] : options[key]; acc.push.apply(acc, list.map(function (file) { return { key: key, file: path.join(options.root, file) }; })); return acc; }, []); (function readUntilEmpty(err) { if (err) { return callback(err); } else if (!sources.length) { return callback(null, read); } var source = sources.shift(); readCertFile(source.key, source.file, readUntilEmpty); })(); };
Update feed tests to use a person object when creating LoggedAction Otherwise the notification signal attached to LoggedAction for the alerts throws an error as it expects a Person to exist
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from popolo.models import Person from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.person1 = Person.objects.create( name='Test Person1' ) self.person2 = Person.objects.create( name='Test Person2' ) self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person=self.person1, popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person=self.person2, popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete() self.person2.delete() self.person1.delete()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django_webtest import WebTest from .auth import TestUserMixin from ..models import LoggedAction class TestFeeds(TestUserMixin, WebTest): def setUp(self): self.action1 = LoggedAction.objects.create( user=self.user, action_type='person-create', ip_address='127.0.0.1', person_id='9876', popit_person_new_version='1234567890abcdef', source='Just for tests...', ) self.action2 = LoggedAction.objects.create( user=self.user, action_type='candidacy-delete', ip_address='127.0.0.1', person_id='1234', popit_person_new_version='987654321', source='Something with unicode in it…', ) def test_unicode(self): response = self.app.get('/feeds/changes.xml') self.assertTrue("Just for tests..." in response) self.assertTrue("Something with unicode in it…" in response) def tearDown(self): self.action2.delete() self.action1.delete()
Add version and version_info to exported public API
import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info') __version__ = '0.3.0' version = __version__ + ' , Python ' + sys.version VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'rc': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError("Invalid package version {}".format(ver)) version_info = _parse_version(__version__) # make pyflakes happy (connect, create_pool, Connection, Cursor, Pool)
import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool') __version__ = '0.3.0' version = __version__ + ' , Python ' + sys.version VersionInfo = namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'rc': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError("Invalid package version {}".format(ver)) version_info = _parse_version(__version__) # make pyflakes happy (connect, create_pool, Connection, Cursor, Pool)
Make urinorm tests runnable on their own
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') if isinstance(case, bytes) else case return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(pyUnitTests())
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests)
Check for and reject null event listeners.
/** * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.utils; import java.util.List; import java.util.concurrent.Executor; import static com.google.common.base.Preconditions.checkNotNull; /** * A simple wrapper around a listener and an executor, with some utility methods. */ public class ListenerRegistration<T> { public final T listener; public final Executor executor; public ListenerRegistration(T listener, Executor executor) { this.listener = checkNotNull(listener); this.executor = checkNotNull(executor); } public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) { checkNotNull(listener); ListenerRegistration<T> item = null; for (ListenerRegistration<T> registration : list) { if (registration.listener == listener) { item = registration; break; } } if (item != null) { list.remove(item); return true; } else { return false; } } }
/** * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.utils; import java.util.List; import java.util.concurrent.Executor; /** * A simple wrapper around a listener and an executor, with some utility methods. */ public class ListenerRegistration<T> { public T listener; public Executor executor; public ListenerRegistration(T listener, Executor executor) { this.listener = listener; this.executor = executor; } public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) { ListenerRegistration<T> item = null; for (ListenerRegistration<T> registration : list) { if (registration.listener == listener) { item = registration; break; } } if (item != null) { list.remove(item); return true; } else { return false; } } }
Add order by start date
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\EntityRepository; /** * LessonRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class LessonRepository extends EntityRepository { /** * Find the today lesson * * @return Lesson */ public function findTodayLesson() { $em = $this->getEntityManager(); return $em->createQuery( ' SELECT l FROM ProjectAppBundle:Lesson l WHERE CURRENT_TIMESTAMP() BETWEEN l.startDate AND l.endDate ' ) ->getOneOrNullResult(); } /** * Find lessons terminated * * @return array */ public function findEndedLessons() { $em = $this->getEntityManager(); return $em->createQuery(' SELECT l FROM ProjectAppBundle:Lesson l WHERE CURRENT_TIMESTAMP() > l.endDate ORDER BY l.startDate DESC ') ->getResult(); } }
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\EntityRepository; /** * LessonRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class LessonRepository extends EntityRepository { /** * Find the today lesson * * @return Lesson */ public function findTodayLesson() { $em = $this->getEntityManager(); return $em->createQuery( ' SELECT l FROM ProjectAppBundle:Lesson l WHERE CURRENT_TIMESTAMP() BETWEEN l.startDate AND l.endDate ' ) ->getOneOrNullResult(); } /** * Find lessons terminated * * @return array */ public function findEndedLessons() { $em = $this->getEntityManager(); return $em->createQuery(' SELECT l FROM ProjectAppBundle:Lesson l WHERE CURRENT_TIMESTAMP() > l.endDate ') ->getResult(); } }
Remove "text-fill" class requirement from text elements for automatic resizing. [IQSLDSH-382]
/*global angular*/ (function () { 'use strict'; // member attribute = member in slide to watch for changes // min-font-size attribute = minimum font size in pixels // max-font-size attribute = maximum font size in pixels // Directive must be used on the parent of an element with the .text-fill class angular.module('core').directive('textFill', ["$timeout", function ($timeout) { return { scope: { member: "@", minFontSize: "=", maxFontSize: "=", }, link: function postLink(scope, element, attrs) { var applyTextFill = function() { $(element).textfill({ minFontPixels: scope.minFontSize, maxFontPixels: scope.maxFontSize, innerTag: '*' }); } scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) { if (member === scope.member) { $timeout(applyTextFill, 100, false); } }); scope.$on("currentSlideChanged", function () { $timeout(applyTextFill, 100, false); }); scope.$on("slideTemplateLoaded", function () { $timeout(applyTextFill, 100, false); }); $timeout(applyTextFill, 100, false); } }; }]); }());
/*global angular*/ (function () { 'use strict'; // member attribute = member in slide to watch for changes // min-font-size attribute = minimum font size in pixels // max-font-size attribute = maximum font size in pixels // Directive must be used on the parent of an element with the .text-fill class angular.module('core').directive('textFill', ["$timeout", function ($timeout) { return { scope: { member: "@", minFontSize: "=", maxFontSize: "=", }, link: function postLink(scope, element, attrs) { if ($(element).find('.text-fill').length === 0) { return; } var applyTextFill = function() { $(element).textfill({ minFontPixels: scope.minFontSize, maxFontPixels: scope.maxFontSize, innerTag: '.text-fill' }); } scope.$on('updateSlideContentPart', function (event, content, member, slidePartId) { if (member === scope.member) { $timeout(applyTextFill, 100, false); } }); scope.$on("currentSlideChanged", function () { $timeout(applyTextFill, 100, false); }); scope.$on("slideTemplateLoaded", function () { $timeout(applyTextFill, 100, false); }); $timeout(applyTextFill, 100, false); } }; }]); }());
Use PhutilProxyException to disambiguate work queue failures Summary: Fixes T2569. This is the other common exception source which is ambiguous. List the task ID explicitly to make debugging easier. Test Plan: {F51268} Reviewers: btrahan Reviewed By: btrahan CC: aran Maniphest Tasks: T2569 Differential Revision: https://secure.phabricator.com/D6549
<?php final class PhabricatorTaskmasterDaemon extends PhabricatorDaemon { public function run() { $sleep = 0; do { $tasks = id(new PhabricatorWorkerLeaseQuery()) ->setLimit(1) ->execute(); if ($tasks) { foreach ($tasks as $task) { $id = $task->getID(); $class = $task->getTaskClass(); $this->log("Working on task {$id} ({$class})..."); $task = $task->executeTask(); $ex = $task->getExecutionException(); if ($ex) { if ($ex instanceof PhabricatorWorkerPermanentFailureException) { $this->log("Task {$id} failed permanently."); } else { $this->log("Task {$id} failed!"); throw new PhutilProxyException( "Error while executing task ID {$id} from queue.", $ex); } } else { $this->log("Task {$id} complete! Moved to archive."); } } $sleep = 0; } else { $sleep = min($sleep + 1, 30); } $this->sleep($sleep); } while (true); } }
<?php final class PhabricatorTaskmasterDaemon extends PhabricatorDaemon { public function run() { $sleep = 0; do { $tasks = id(new PhabricatorWorkerLeaseQuery()) ->setLimit(1) ->execute(); if ($tasks) { foreach ($tasks as $task) { $id = $task->getID(); $class = $task->getTaskClass(); $this->log("Working on task {$id} ({$class})..."); $task = $task->executeTask(); $ex = $task->getExecutionException(); if ($ex) { if ($ex instanceof PhabricatorWorkerPermanentFailureException) { $this->log("Task {$id} failed permanently."); } else { $this->log("Task {$id} failed!"); throw $ex; } } else { $this->log("Task {$id} complete! Moved to archive."); } } $sleep = 0; } else { $sleep = min($sleep + 1, 30); } $this->sleep($sleep); } while (true); } }
Modify attributes for dynamic columns Refs SH-64
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter from shuup.admin.utils.views import PicotableListView from shuup.core.models import Attribute, AttributeType, AttributeVisibility class AttributeListView(PicotableListView): model = Attribute default_columns = [ Column("identifier", _("Identifier"), filter_config=TextFilter( filter_field="identifier", placeholder=_("Filter by identifier...") )), Column("name", _("Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("type", _("Type"), filter_config=ChoicesFilter(AttributeType.choices)), Column("visibility_mode", _("Visibility Mode"), filter_config=ChoicesFilter(AttributeVisibility.choices)), Column("searchable", _("Searchable")), Column("n_product_types", _("Used in # Product Types")), ] def get_queryset(self): return Attribute.objects.all().annotate(n_product_types=Count("product_types"))
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter from shuup.admin.utils.views import PicotableListView from shuup.core.models import Attribute, AttributeType, AttributeVisibility class AttributeListView(PicotableListView): model = Attribute columns = [ Column("identifier", _("Identifier"), filter_config=TextFilter( filter_field="identifier", placeholder=_("Filter by identifier...") )), Column("name", _("Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("type", _("Type"), filter_config=ChoicesFilter(AttributeType.choices)), Column("visibility_mode", _("Visibility Mode"), filter_config=ChoicesFilter(AttributeVisibility.choices)), Column("searchable", _("Searchable")), Column("n_product_types", _("Used in # Product Types")), ] def get_queryset(self): return Attribute.objects.all().annotate(n_product_types=Count("product_types"))
Set Access-Control-Allow-Credentials for all responses In order to inform the browser to set the Cookie header on requests, this header must be set otherwise the session is reset on every request.
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin response['Access-Control-Allow-Credentials'] = 'true' if request.method == 'OPTIONS': response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
Raise hard error when API key is invalid
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: raise AuthenticationFailed('API key is not valid') if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
Add connect() description in RexsterClient tests
var should = require('should'); var grex = require('../index.js'); var _ = require("lodash"); var RexsterClient = require('../src/rexsterclient.js'); var defaultOptions = { 'host': 'localhost', 'port': 8182, 'graph': 'tinkergraph' }; describe.only('RexsterClient', function() { describe('connect()', function() { describe('when passing no parameters', function() { it('should use default options', function(done) { grex.connect(function(err, client) { should.not.exist(err); client.options.should.eql(defaultOptions); done(); }); }); }); describe('when passing custom options', function() { var options = { 'host': 'localhost', 'port': 8182, 'graph': 'gratefulgraph' }; before(function(done) { grex.connect(options, function(err, client) { done(); }); }); it('should use this new options', function(done) { grex.options.graph.should.equal(options.graph); done(); }); }); describe('when instantiating a client with custom options', function() { var options = { 'host': 'localhost', 'port': 8182, 'graph': 'gratefulgraph' }; it('should use the right options', function(done) { var client = new RexsterClient(options); client.options.graph.should.equal(options.graph); done(); }); }); }); });
var should = require('should'); var grex = require('../index.js'); var _ = require("lodash"); var RexsterClient = require('../src/rexsterclient.js'); var defaultOptions = { 'host': 'localhost', 'port': 8182, 'graph': 'tinkergraph' }; describe('RexsterClient', function() { describe('when passing no parameters', function() { it('should use default options', function(done) { grex.connect(function(err, client) { should.not.exist(err); client.options.should.eql(defaultOptions); done(); }); }); }); describe('when passing custom options', function() { var options = { 'host': 'localhost', 'port': 8182, 'graph': 'gratefulgraph' }; before(function(done) { grex.connect(options, function(err, client) { done(); }); }); it('should use this new options', function(done) { grex.options.graph.should.equal(options.graph); done(); }); }); describe('when instantiating a client with custom options', function() { var options = { 'host': 'localhost', 'port': 8182, 'graph': 'gratefulgraph' }; it('should use the right options', function(done) { var client = new RexsterClient(options); client.options.graph.should.equal(options.graph); done(); }); }); });
Hide load more button if no stories
import React from 'react'; import { ListView, RefreshControl, View } from 'react-native'; import Footer from './Footer'; import Story from './Story'; const renderSeparator = (sectionID, rowID, adjacentRowHighlighted) => <View key={`${sectionID}-${rowID}`} style={{ height: adjacentRowHighlighted ? 4 : 1, backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC', }} /> export default StoriesListView = ({ dataSource, onStoryPress, refreshing, onRefresh, loadMore }) => <ListView dataSource={dataSource} renderRow={(rowData, sectionID, rowID) => ( <Story onPress={() => { console.log(rowData); onStoryPress(rowData); }} title={rowData.title} points={rowData.points} user={rowData.user} timeAgo={rowData.time_ago} commentsCount={rowData.comments_count} key={rowID} /> )} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> } renderFooter={() => dataSource.getRowCount() > 0 ? <Footer loadMore={loadMore} key="footer" /> : null} renderSeparator={renderSeparator} enableEmptySections={true} pageSize={30} />
import React from 'react'; import { ListView, RefreshControl, View } from 'react-native'; import Footer from './Footer'; import Story from './Story'; const renderSeparator = (sectionID, rowID, adjacentRowHighlighted) => <View key={`${sectionID}-${rowID}`} style={{ height: adjacentRowHighlighted ? 4 : 1, backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC', }} /> export default StoriesListView = ({ dataSource, onStoryPress, refreshing, onRefresh, loadMore }) => <ListView dataSource={dataSource} renderRow={(rowData, sectionID, rowID) => ( <Story onPress={() => { console.log(rowData); onStoryPress(rowData); }} title={rowData.title} points={rowData.points} user={rowData.user} timeAgo={rowData.time_ago} commentsCount={rowData.comments_count} key={rowID} /> )} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> } renderFooter={() => <Footer loadMore={loadMore} key="footer" />} renderSeparator={renderSeparator} enableEmptySections={true} pageSize={30} />
Use shortname instead of alias Fixes #106
<?= '<?php' ?> /** * An helper file for Laravel 4, to provide autocomplete information to your IDE * Generated for Laravel <?= $version ?> on <?= date("Y-m-d") ?>. * * @author Barry vd. Heuvel <[email protected]> * @see https://github.com/barryvdh/laravel-ide-helper */ <?php foreach($namespaces as $namespace => $aliases): ?> namespace <?= $namespace == '__root' ? '' : $namespace ?>{ <?php if($namespace == '__root'): ?> exit("This file should not be included, only analyzed by your IDE"); <?= $helpers ?> <?php endif; ?> <?php foreach($aliases as $alias): ?> <?= $alias->getClassType() ?> <?= $alias->getShortName() ?> <?= $alias->getExtends() ? 'extends ' . $alias->getExtends() : '' ?>{ <?php foreach($alias->getMethods() as $method): ?> <?= trim($method->getDocComment(' ')) ?> public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>){<?php if($method->getDeclaringClass() !== $method->getRoot()): ?> //Method inherited from <?= $method->getDeclaringClass() ?> <?php endif; ?> <?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>); } <?php endforeach; ?> } <?php endforeach; ?> } <?php endforeach; ?>
<?= '<?php' ?> /** * An helper file for Laravel 4, to provide autocomplete information to your IDE * Generated for Laravel <?= $version ?> on <?= date("Y-m-d") ?>. * * @author Barry vd. Heuvel <[email protected]> * @see https://github.com/barryvdh/laravel-ide-helper */ <?php foreach($namespaces as $namespace => $aliases): ?> namespace <?= $namespace == '__root' ? '' : $namespace ?>{ <?php if($namespace == '__root'): ?> exit("This file should not be included, only analyzed by your IDE"); <?= $helpers ?> <?php endif; ?> <?php foreach($aliases as $alias): ?> <?= $alias->getClassType() ?> <?= $alias->getAlias() ?> <?= $alias->getExtends() ? 'extends ' . $alias->getExtends() : '' ?>{ <?php foreach($alias->getMethods() as $method): ?> <?= trim($method->getDocComment(' ')) ?> public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>){<?php if($method->getDeclaringClass() !== $method->getRoot()): ?> //Method inherited from <?= $method->getDeclaringClass() ?> <?php endif; ?> <?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>); } <?php endforeach; ?> } <?php endforeach; ?> } <?php endforeach; ?>
Check once every 15 minutes
from celery.schedules import crontab from celery.task import periodic_task from django.utils.timezone import now from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant import logging from bluebottle.events.models import Event logger = logging.getLogger('bluebottle') @periodic_task( run_every=(crontab(minute='*/15')), name="check_event_start", ignore_result=True ) def check_event_start(): for tenant in Client.objects.all(): with LocalTenant(tenant, clear_tenant=True): # Start events that are running now events = Event.objects.filter( start_time__lte=now(), end_time__gte=now(), status__in=['full', 'open'] ).all() for event in events: event.transitions.start() event.save() @periodic_task( run_every=(crontab(minute='*/15')), name="check_event_end", ignore_result=True ) def check_event_end(): for tenant in Client.objects.all(): with LocalTenant(tenant, clear_tenant=True): # Close events that are over events = Event.objects.filter( end_time__lte=now(), status__in=['running'] ).all() for event in events: event.transitions.succeed() event.save()
from celery.schedules import crontab from celery.task import periodic_task from django.utils.timezone import now from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant import logging from bluebottle.events.models import Event logger = logging.getLogger('bluebottle') @periodic_task( run_every=(crontab(minute='*/1')), name="check_event_start", ignore_result=True ) def check_event_start(): for tenant in Client.objects.all(): with LocalTenant(tenant, clear_tenant=True): # Start events that are running now events = Event.objects.filter( start_time__lte=now(), end_time__gte=now(), status__in=['full', 'open'] ).all() for event in events: event.transitions.start() event.save() @periodic_task( run_every=(crontab(minute='*/1')), name="check_event_end", ignore_result=True ) def check_event_end(): for tenant in Client.objects.all(): with LocalTenant(tenant, clear_tenant=True): # Close events that are over events = Event.objects.filter( end_time__lte=now(), status__in=['running'] ).all() for event in events: event.transitions.succeed() event.save()
Update sample Python report module for ReportModule interface API change
from java.lang import System from org.sleuthkit.autopsy.casemodule import Case from org.sleuthkit.datamodel import SleuthkitCase from org.sleuthkit.autopsy.report import GeneralReportModuleAdapter class SampleGeneralReportModule(GeneralReportModuleAdapter): def getName(self): return "Sample Report Module" def getDescription(self): return "A sample Jython report module" def getRelativeFilePath(self): return "sampleReport.txt" def generateReport(self, reportPath, progressBar): # There are two tasks to do. progressBar.setIndeterminate(False) progressBar.start() progressBar.setMaximumProgress(2) # Get files by created in last two weeks. fileCount = 0 autopsyCase = Case.getCurrentCase() sleuthkitCase = autopsyCase.getSleuthkitCase() currentTime = System.currentTimeMillis() / 1000 minTime = currentTime - (14 * 24 * 60 * 60) otherFiles = sleuthkitCase.findFilesWhere("crtime > %d" % minTime) for otherFile in otherFiles: fileCount += 1 progressBar.increment() # Write the result to the report file. report = open(reportPath + '\\' + self.getFilePath(), 'w') report.write("file count = %d" % fileCount) report.close() progressBar.increment() progressBar.complete()
from java.lang import System from org.sleuthkit.autopsy.casemodule import Case from org.sleuthkit.datamodel import SleuthkitCase from org.sleuthkit.autopsy.report import GeneralReportModuleAdapter class SampleGeneralReportModule(GeneralReportModuleAdapter): def getName(self): return "Sample Report Module" def getDescription(self): return "A sample Jython report module" def getFilePath(self): return "sampleReport.txt" def generateReport(self, reportPath, progressBar): # There are two tasks to do. progressBar.setIndeterminate(False) progressBar.start() progressBar.setMaximumProgress(2) # Get files by created in last two weeks. fileCount = 0 autopsyCase = Case.getCurrentCase() sleuthkitCase = autopsyCase.getSleuthkitCase() currentTime = System.currentTimeMillis() / 1000 minTime = currentTime - (14 * 24 * 60 * 60) otherFiles = sleuthkitCase.findFilesWhere("crtime > %d" % minTime) for otherFile in otherFiles: fileCount += 1 progressBar.increment() # Write the result to the report file. report = open(reportPath + '\\' + self.getFilePath(), 'w') report.write("file count = %d" % fileCount) report.close() progressBar.increment() progressBar.complete()
Add unit support for spacers git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@779 3777fadb-0f44-0410-9e7f-9d8fa6171d72
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * from styles import adjustUnits def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height """ elements = [] lines = data.splitlines() for line in lines: lexer = shlex.shlex(line) lexer.whitespace += ',' tokens = list(lexer) command = tokens[0] if command == 'PageBreak': if len(tokens) == 1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(adjustUnits(tokens[1]), adjustUnits(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now: # def depth(node): # if node.parent == None: # return 0 # else: # return 1 + depth(node.parent)
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height """ elements = [] lines = data.splitlines() for line in lines: lexer = shlex.shlex(line) lexer.whitespace += ',' tokens = list(lexer) command = tokens[0] if command == 'PageBreak': if len(tokens) == 1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]), int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now: # def depth(node): # if node.parent == None: # return 0 # else: # return 1 + depth(node.parent)
Update generate resource command signature
<?php namespace Nwidart\Modules\Commands; use Illuminate\Console\Command; class GenerateResource extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'module:make:resource {resource : The singular name of the resource} {module? : The name of the module to create the controller in}'; /** * The command description. * * @var string */ protected $description = 'Generate all assets for a new resource.'; /** * Execute the console command. */ public function fire() { // TODO: create resource, repo, … based on migration $this->call('module:make:controller', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->call('module:make:router', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->call('module:make:views:resource', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->info('Now register your resource router in the "mapRoutes" method of your module service provider.'); } }
<?php namespace Nwidart\Modules\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputArgument; class GenerateResource extends Command { /** * The command name. * * @var string */ protected $name = 'module:make:resource'; /** * The command description. * * @var string */ protected $description = 'Generate all assets for a new resource.'; /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ['resource', InputArgument::REQUIRED, 'The singular name of the resource.'], ['module', InputArgument::REQUIRED, 'The name of the module to create the controller in.'], ]; } /** * Execute the console command. */ public function fire() { // TODO: create resource, repo, … based on migration $this->call('module:make:resource-controller', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->call('module:make:resource-router', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->call('module:make:views:resource', [ 'resource' => $this->argument('resource'), 'module' => $this->argument('module'), ]); $this->info('Now register your resource router in the <mapRoutes> method of your module service provider.'); } }
Update name of vagrant module Changed to python-vagrant to get python setup.py to work
#!/usr/bin/env python from setuptools import setup setup( name = 'nepho', version = '0.2.0', url = 'http://github.com/huit/nepho', description = 'Simplified cloud orchestration tool for constructing virtual data centers', packages = ['nepho', 'nepho.aws'], author = 'Harvard University Information Technology', author_email = '[email protected]', license = 'MIT', scripts = ['bin/nepho'], package_data = { 'nepho': [ 'data/scenarios/*', ], 'nepho.aws': [ 'data/patterns/*/*.cf', 'data/drivers/*.sh' ] }, install_requires = [ 'argparse>=1.2', 'boto>=2.0', 'awscli>=1.2.3', 'Jinja2', 'PyYAML', 'cement>=2.0', 'termcolor', 'gitpython==0.3.2.RC1', 'requests>=1.2.3', 'ply==3.4', 'python-vagrant==0.4.0' ], )
#!/usr/bin/env python from setuptools import setup setup( name = 'nepho', version = '0.2.0', url = 'http://github.com/huit/nepho', description = 'Simplified cloud orchestration tool for constructing virtual data centers', packages = ['nepho', 'nepho.aws'], author = 'Harvard University Information Technology', author_email = '[email protected]', license = 'MIT', scripts = ['bin/nepho'], package_data = { 'nepho': [ 'data/scenarios/*', ], 'nepho.aws': [ 'data/patterns/*/*.cf', 'data/drivers/*.sh' ] }, install_requires = [ 'argparse>=1.2', 'boto>=2.0', 'awscli>=1.2.3', 'Jinja2', 'PyYAML', 'cement>=2.0', 'termcolor', 'gitpython==0.3.2.RC1', 'requests>=1.2.3', 'ply==3.4', 'vagrant==0.4.0' ], )
Use correct m2m join table name in LatestCommentsFeed --HG-- extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
Use more verbose progress output.
<?php namespace Aurora\Console\Commands; use Aurora\Services\Fastly; use Aurora\Resources\Redirect; use Illuminate\Console\Command; class FastlyImportCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'fastly:import {path}'; /** * The console command description. * * @var string */ protected $description = 'Import Fastly dictionaries to this app\'s service.'; /** * Execute the console command. * * @return mixed */ public function handle(Fastly $fastly) { $input = file_get_contents($this->argument('path')); $redirects = array_map(function ($redirect) { return new Redirect($redirect); }, json_decode($input, true)); $url = config('services.fastly.service_url'); $confirmation = 'Would you like to create ' . count($redirects) . ' redirects on ' . $url . '?'; if ($this->confirm($confirmation)) { foreach ($redirects as $redirect) { $this->line('Redirecting "' . $redirect->path . '" to "' . $redirect->target . '" (' . $redirect->status . ')'); $fastly->createRedirect($redirect->path, $redirect->target, $redirect->status); } } } }
<?php namespace Aurora\Console\Commands; use Aurora\Services\Fastly; use Aurora\Resources\Redirect; use Illuminate\Console\Command; class FastlyImportCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'fastly:import {path}'; /** * The console command description. * * @var string */ protected $description = 'Import Fastly dictionaries to this app\'s service.'; /** * Execute the console command. * * @return mixed */ public function handle(Fastly $fastly) { $input = file_get_contents($this->argument('path')); $redirects = array_map(function ($redirect) { return new Redirect($redirect); }, json_decode($input, true)); $url = config('services.fastly.service_url'); $confirmation = 'Would you like to create ' . count($redirects) . ' redirects on ' . $url . '?'; if ($this->confirm($confirmation)) { $progress = $this->output->createProgressBar(count($redirects)); foreach ($redirects as $redirect) { $fastly->createRedirect($redirect->path, $redirect->target, $redirect->status); $progress->advance(); } $progress->finish(); } } }
Add support for forum thread view
// ==UserScript== // @name Slickdeals Don't Track Me! // @version 1.1 // @description Replaces outgoing Slickdeals tracking links with direct links. // @match http://slickdeals.net/f/* // @namespace https://github.com/gg/slickdeals-dont-track-me // @author Gregg Gajic <https://github.com/gg> // @license MIT // ==/UserScript== (function() { var getQueryStringParameters = function (url) { // See: http://stackoverflow.com/a/3855394 return (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('=', 2); if (p.length == 1) b[p[0]] = ""; else b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })((url.split('?')[1] || '').split('&')); }; var contentBody = document.getElementById('maincontent') || document.getElementById('posts'); var aElements = contentBody.getElementsByTagName('a'); for (var i = 0, a; a = aElements[i]; i++) { var queryParamters = getQueryStringParameters(a.href); var directUrl = queryParamters['u2']; if (directUrl) { a.href = directUrl; a.onclick = ''; }; } })();
// ==UserScript== // @name Slickdeals Don't Track Me! // @version 1.0 // @description Replaces outgoing Slickdeals tracking links with direct links. // @match http://slickdeals.net/f/* // @namespace https://github.com/gg/slickdeals-dont-track-me // @author Gregg Gajic <https://github.com/gg> // @license MIT // ==/UserScript== (function() { var getQueryStringParameters = function (url) { // See: http://stackoverflow.com/a/3855394 return (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('=', 2); if (p.length == 1) b[p[0]] = ""; else b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })((url.split('?')[1] || '').split('&')); }; var aElements = document.getElementById('maincontent').getElementsByTagName('a'); for (var i = 0, a; a = aElements[i]; i++) { var queryParamters = getQueryStringParameters(a.href); var directUrl = queryParamters['u2']; if (directUrl) { a.href = directUrl; a.onclick = ''; }; } })();
Use create instead of instance and save
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key passed as a GET parameter """ def is_authenticated(self, request): try: keyobj = AuthAPIKey.objects.get(key=request.GET.get('apikey', None)) except AuthAPIKey.DoesNotExist: pass else: if keyobj and keyobj.active: params = request.GET.copy() if params.get('apikey', None): del params['apikey'] if len(params): url = "%s?%s" % (request.path, urlencode(params)) else: url = request.path AuthAPILog.objects.create(key=keyobj, access_datetime=now(), url=url) request.user = AnonymousUser() request.api_key = keyobj return True return False def challenge(self): return HttpResponseForbidden('Access Denied, use a API Key')
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key passed as a GET parameter """ def is_authenticated(self, request): try: keyobj = AuthAPIKey.objects.get(key=request.GET.get('apikey', None)) except AuthAPIKey.DoesNotExist: pass else: if keyobj and keyobj.active: params = request.GET.copy() if params.get('apikey', None): del params['apikey'] if len(params): url = "%s?%s" % (request.path, urlencode(params)) else: url = request.path AuthAPILog(key=keyobj, access_datetime=now(), url=url).save() request.user = AnonymousUser() request.api_key = keyobj return True return False def challenge(self): return HttpResponseForbidden('Access Denied, use a API Key')
Set `replaced` also for children array Signed-off-by: Stefan Marr <[email protected]>
'use strict'; function Node(source) { var _this = this; this._parent = null; this.getSource = function () { return source; }; this.adopt = function (nodeOrNodes) { if (nodeOrNodes instanceof Array) { for (var i in nodeOrNodes) { nodeOrNodes[i]._parent = _this; } } else { nodeOrNodes._parent = _this; } return nodeOrNodes; }; this.replace = function (newNode) { var parent = _this._parent; var replaced = false; for (var prop in parent) { if (prop.indexOf("_child") == 0) { if (prop.indexOf("_children") == 0) { // an array with child nodes var children = parent[prop]; for (var i in children) { if (children[i] === _this) { children[i] = newNode; replaced = true; } } } else { // just a simple child node if (parent[prop] === _this) { parent[prop] = newNode; replaced = true; } } } } if (!replaced) { debugger; // node was not replaced??? } return newNode; } }
'use strict'; function Node(source) { var _this = this; this._parent = null; this.getSource = function () { return source; }; this.adopt = function (nodeOrNodes) { if (nodeOrNodes instanceof Array) { for (var i in nodeOrNodes) { nodeOrNodes[i]._parent = _this; } } else { nodeOrNodes._parent = _this; } return nodeOrNodes; }; this.replace = function (newNode) { var parent = _this._parent; var replaced = false; for (var prop in parent) { if (prop.indexOf("_child") == 0) { if (prop.indexOf("_children") == 0) { // an array with child nodes var children = parent[prop]; for (var i in children) { if (children[i] === _this) { children[i] = newNode } } } else { // just a simple child node if (parent[prop] === _this) { parent[prop] = newNode; replaced = true; } } } } if (!replaced) { debugger; // node was not replaced??? } return newNode; } }
Fix a few Sphinx typos * `.. note:` -> `.. note::` to prevent the `note` from being interpreted as a comment, which wouldn't show up when the docs are rendered. * Double backticks for the code bits. * Correct typo ("atribute" -> "attribute"). * Sphinx doesn't like characters immediately after the backticks, so add a hyphen in to prevent it from being rendered incorrectly.
"""PRAW exception classes. Includes two main exceptions: :class:`.APIException` for when something goes wrong on the server side, and :class:`.ClientException` when something goes wrong on the client side. Both of these classes extend :class:`.PRAWException`. """ class PRAWException(Exception): """The base PRAW Exception that all other exception classes extend.""" class APIException(PRAWException): """Indicate exception that involve responses from Reddit's API.""" def __init__(self, error_type, message, field): """Initialize an instance of APIException. :param error_type: The error type set on Reddit's end. :param message: The associated message for the error. :param field: The input field associated with the error if available. .. note:: Calling ``str()`` on the instance returns ``unicode_escape``-d ASCII string because the message may be localized and may contain UNICODE characters. If you want a non-escaped message, access the ``message`` attribute on the instance. """ error_str = u'{}: \'{}\''.format(error_type, message) if field: error_str += u' on field \'{}\''.format(field) error_str = error_str.encode('unicode_escape').decode('ascii') super(APIException, self).__init__(error_str) self.error_type = error_type self.message = message self.field = field class ClientException(PRAWException): """Indicate exceptions that don't involve interaction with Reddit's API."""
"""PRAW exception classes. Includes two main exceptions: :class:`.APIException` for when something goes wrong on the server side, and :class:`.ClientException` when something goes wrong on the client side. Both of these classes extend :class:`.PRAWException`. """ class PRAWException(Exception): """The base PRAW Exception that all other exception classes extend.""" class APIException(PRAWException): """Indicate exception that involve responses from Reddit's API.""" def __init__(self, error_type, message, field): """Initialize an instance of APIException. :param error_type: The error type set on Reddit's end. :param message: The associated message for the error. :param field: The input field associated with the error if available. .. note: Calling `str()` on the instance returns `unicode_escape`d ASCII string because the message may be localized and may contain UNICODE characters. If you want a non-escaped message, access the `message` atribute on the instance. """ error_str = u'{}: \'{}\''.format(error_type, message) if field: error_str += u' on field \'{}\''.format(field) error_str = error_str.encode('unicode_escape').decode('ascii') super(APIException, self).__init__(error_str) self.error_type = error_type self.message = message self.field = field class ClientException(PRAWException): """Indicate exceptions that don't involve interaction with Reddit's API."""
JsMinify: Hide output textarea by default
DDH.js_minify = DDH.js_minify || {}; "use strict"; DDH.js_minify.build = function(ops) { var shown = false; return { onShow: function() { // make sure this function is run only once, the first time // the IA is shown otherwise things will get initialized more than once if (shown) return; // set the flag to true so it doesn't get run again shown = true; var $dom = $('#zci-js_minify'), $main = $dom.find('.zci__main'), $minifyButton = $dom.find('.js_minify__action'), $input = $dom.find('#js_minify__input'), $output = $dom.find('#js_minify__output'); $main.toggleClass('c-base'); // hide output textarea by default $output.css('display', 'none'); $.getScript('http://sahildua.com/js/prettydiff.min.js', function() { // Add click handler for the minify button $minifyButton.click(function() { // Set config options for minify operation var args = { mode: "minify", lang: "javascript", source: $input.val() }; // Operate using the prettydiff function provided by the library var output = prettydiff(args); // hide output textarea by default $output.css('display', 'inline'); // Add the output to output textarea field $output.val(output); }); }) } }; };
DDH.js_minify = DDH.js_minify || {}; "use strict"; DDH.js_minify.build = function(ops) { var shown = false; return { onShow: function() { // make sure this function is run only once, the first time // the IA is shown otherwise things will get initialized more than once if (shown) return; // set the flag to true so it doesn't get run again shown = true; var $dom = $('#zci-js_minify'), $main = $dom.find('.zci__main'), $minifyButton = $dom.find('.js_minify__action'), $input = $dom.find('#js_minify__input'), $output = $dom.find('#js_minify__output'); $main.toggleClass('c-base'); $.getScript('http://sahildua.com/js/prettydiff.min.js', function() { // Add click handler for the minify button $minifyButton.click(function() { // Set config options for minify operation var args = { mode: "minify", lang: "javascript", source: $input.val() }; // Operate using the prettydiff function provided by the library var output = prettydiff(args); // Add the output to output textarea field $output.val(output); }); }) } }; };
Add attributes for drag and drop
function generate_board_page(that, board_id){ /* Generate the board page */ // Gets the node of board page var bp_node = that.nodeById('board_page'); // Make a serverCall to gets lists and cards related // to the board. var result = genro.serverCall( 'get_lists_cards', {board_id: board_id} ); // sets the return result to the board datapath that.setRelativeData('board', result); var res_asDict = result.asDict(true); for (var k in res_asDict){ var list_wrapper = bp_node._('div', {_class:'list-wrapper'}); // name of the list var list_div = list_wrapper._('div', {_class: 'gen-list'}) list_div._('h3', {innerHTML: '^.' + k + '?list_name'}); // create a ul for the cards var list_cards = list_div._('div', { _class: 'list-cards', dropTarget: true, dropTypes:'*', }); var cards = res_asDict[k]; for (var c in cards){ var card =list_cards._('div', { _class: 'list-card', draggable: true, }); card._('div', { innerHTML: '^.' + k + '.' + c + '.name', _class: 'list-card-label' }); } } // Once done with the rendering change the page that.setRelativeData('page_selected', 1); }
function generate_board_page(that, board_id){ /* Generate the board page */ // Gets the node of board page var bp_node = that.nodeById('board_page'); // Make a serverCall to gets lists and cards related // to the board. var result = genro.serverCall( 'get_lists_cards', {board_id: board_id} ); // sets the return result to the board datapath that.setRelativeData('board', result); var res_asDict = result.asDict(true); for (var k in res_asDict){ var list_wrapper = bp_node._('div', {_class:'list-wrapper'}); // name of the list var list_div = list_wrapper._('div', {_class: 'gen-list'}) list_div._('h3', {innerHTML: '^.' + k + '?list_name'}); // create a ul for the cards var list_cards = list_div._('div', {_class: 'list-cards'}); var cards = res_asDict[k]; for (var c in cards){ var card =list_cards._('div', { _class: 'list-card' }); card._('div', { innerHTML: '^.' + k + '.' + c + '.name', _class: 'list-card-label' }); } } // Once done with the rendering change the page that.setRelativeData('page_selected', 1); }
Move logout to the last position
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'logout': { url: '/logout', controller: StateController, controllerAs: 'vm', title: 'Logout' } }; } function navItems() { return {}; } function sidebarItems() { return { 'logout': { type: 'state', state: 'logout', label: 'Logout', style: 'logout', isVisible: isVisible, order: 9999 } }; } /** @ngInject */ function isVisible() { // Visibility can be conditional return true; } /** @ngInject */ function StateController($state, AuthenticationService, logger, lodash) { var vm = this; vm.AuthService = AuthenticationService; vm.title = ''; vm.AuthService.logout().success(lodash.bind(function() { logger.info('You have been logged out.'); $state.transitionTo('login'); }, vm)).error(lodash.bind(function() { logger.info('An error has occured at logout.'); }, vm)); } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'logout': { url: '/logout', controller: StateController, controllerAs: 'vm', title: 'Logout' } }; } function navItems() { return {}; } function sidebarItems() { return { 'logout': { type: 'state', state: 'logout', label: 'Logout', style: 'logout', isVisible: isVisible, order: 99 } }; } /** @ngInject */ function isVisible() { // Visibility can be conditional return true; } /** @ngInject */ function StateController($state, AuthenticationService, logger, lodash) { var vm = this; vm.AuthService = AuthenticationService; vm.title = ''; vm.AuthService.logout().success(lodash.bind(function() { logger.info('You have been logged out.'); $state.transitionTo('login'); }, vm)).error(lodash.bind(function() { logger.info('An error has occured at logout.'); }, vm)); } })();
Move Pillow to the last version
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.2.6.1', url='http://github.com/jorgebastida/glue', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites using any kind of source images like ' 'PNG, JPEG or GIF. Glue will generate a unique PNG ' 'file containing every source image and a CSS file ' 'including the necessary CSS classes to use the ' 'sprite.'), py_modules=['glue'], platforms='any', install_requires=[ 'Pillow==1.7.7' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw )
try: from setuptools import setup kw = {'entry_points': """[console_scripts]\nglue = glue:main\n""", 'zip_safe': False} except ImportError: from distutils.core import setup kw = {'scripts': ['glue.py']} setup( name='glue', version='0.2.6.1', url='http://github.com/jorgebastida/glue', license='BSD', author='Jorge Bastida', author_email='[email protected]', description='Glue is a simple command line tool to generate CSS sprites.', long_description=('Glue is a simple command line tool to generate CSS ' 'sprites using any kind of source images like ' 'PNG, JPEG or GIF. Glue will generate a unique PNG ' 'file containing every source image and a CSS file ' 'including the necessary CSS classes to use the ' 'sprite.'), py_modules=['glue'], platforms='any', install_requires=[ 'Pillow==1.7.6' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], **kw )
Allow listing players if dead
package me.rkfg.xmpp.bot.plugins.game.command; import static me.rkfg.xmpp.bot.plugins.game.misc.Utils.*; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; import java.util.stream.Stream; import me.rkfg.xmpp.bot.plugins.game.IPlayer; import me.rkfg.xmpp.bot.plugins.game.World; public class ListPlayersCommand implements ICommandHandler { @Override public Optional<String> exec(IPlayer player, Stream<String> args) { List<IPlayer> playersList = World.THIS.listPlayers(); if (playersList.isEmpty()) { return Optional.of("Игроков нет."); } return IntStream.range(0, playersList.size()).mapToObj(i -> { final IPlayer p = playersList.get(i); return "" + (i + 1) + ": " + p.getName() + (p.isAlive() ? "" : " [мёртв]") + (p == player ? " [вы]" : ""); }).reduce(commaReducer).map(list -> "Игроки: " + list); } @Override public Optional<String> getHelp() { return Optional.of("Вывести список всех участников."); } @Override public Collection<String> getCommand() { return Arrays.asList("игроки"); } @Override public boolean deadAllowed() { return true; } }
package me.rkfg.xmpp.bot.plugins.game.command; import static me.rkfg.xmpp.bot.plugins.game.misc.Utils.*; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; import java.util.stream.Stream; import me.rkfg.xmpp.bot.plugins.game.IPlayer; import me.rkfg.xmpp.bot.plugins.game.World; public class ListPlayersCommand implements ICommandHandler { @Override public Optional<String> exec(IPlayer player, Stream<String> args) { List<IPlayer> playersList = World.THIS.listPlayers(); if (playersList.isEmpty()) { return Optional.of("Игроков нет."); } return IntStream.range(0, playersList.size()).mapToObj(i -> { final IPlayer p = playersList.get(i); return "" + (i + 1) + ": " + p.getName() + (p.isAlive() ? "" : " [мёртв]") + (p == player ? " [вы]" : ""); }).reduce(commaReducer).map(list -> "Игроки: " + list); } @Override public Optional<String> getHelp() { return Optional.of("Вывести список всех участников."); } @Override public Collection<String> getCommand() { return Arrays.asList("игроки"); } }
Add register and IO addresses
import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ include('whitespace'), (r'\(' + identifier + '\)', Name.Label), (r'[+-=;&|!]+', Operator), (r'\/\/.+$', Comment), (r'[\r\n]+', Text), (r'@[A-Za-z][A-Za-z0-9]+', Name.Variable), (r'\b(JGT|JEQ|JGE|JLT|JNE|JLE|JMP)\b', Keyword), (r'\b@(SCREEN|KBD)\b', Name.Builtin.Pseudo), # I/O addresses (r'\b@(R0|R1|R2|R3|R4|R5|R6|R7|R8|R9|R10|R11|R12|R13|R14|R15)\b', Name.Builtin.Pseudo), # RAM Addresses (r'\b@(SP|LCL|ARG|THIS|THAT)\b', Name.Builtin.Pseudo), # Parameter addresses (r'null', Keyword.Pseudo), (r'\b(D|M|MD|A|AM|AD|AMD)\b', Name.Builtin), (r'@[0-9]+', Name.Constant) ], 'whitespace': [ (r'\n', Text), (r'\s+', Text), (r'#.*?\n', Comment) ] }
import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ include('whitespace'), (r'\(' + identifier + '\)', Name.Label), (r'[+-=;&|!]+', Operator), (r'\/\/.+$', Comment), (r'[\r\n]+', Text), (r'@[A-Za-z][A-Za-z0-9]+', Name.Variable), (r'\b(JGT|JEQ|JGE|JLT|JNE|JLE|JMP)\b', Keyword), (r'null', Keyword.Pseudo), (r'\b(D|M|MD|A|AM|AD|AMD)\b', Name.Builtin), (r'@[0-9]+', Name.Constant) ], 'whitespace': [ (r'\n', Text), (r'\s+', Text), (r'#.*?\n', Comment) ] }
Adjust coverage values to match existing setup
'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: 97, statements: 95 }, 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: 97, statements: 98 }, 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']) }
Drop Python 2 support in split_level utility function
from collections.abc import Iterable def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded. """ expand = request.query_params.get("expand", "") expand_fields = [] for e in expand.split(","): expand_fields.extend([e for e in e.split(".")]) return "~all" in expand_fields or key in expand_fields def split_levels(fields): """ Convert dot-notation such as ['a', 'a.b', 'a.d', 'c'] into current-level fields ['a', 'c'] and next-level fields {'a': ['b', 'd']}. """ first_level_fields = [] next_level_fields = {} if not fields: return first_level_fields, next_level_fields assert ( isinstance(fields, Iterable) ), "`fields` must be iterable (e.g. list, tuple, or generator)" if isinstance(fields, str): fields = [a.strip() for a in fields.split(",") if a.strip()] for e in fields: if "." in e: first_level, next_level = e.split(".", 1) first_level_fields.append(first_level) next_level_fields.setdefault(first_level, []).append(next_level) else: first_level_fields.append(e) first_level_fields = list(set(first_level_fields)) return first_level_fields, next_level_fields
try: # Python 3 from collections.abc import Iterable string_types = (str,) except ImportError: # Python 2 from collections import Iterable string_types = (str, unicode) def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded. """ expand = request.query_params.get("expand", "") expand_fields = [] for e in expand.split(","): expand_fields.extend([e for e in e.split(".")]) return "~all" in expand_fields or key in expand_fields def split_levels(fields): """ Convert dot-notation such as ['a', 'a.b', 'a.d', 'c'] into current-level fields ['a', 'c'] and next-level fields {'a': ['b', 'd']}. """ first_level_fields = [] next_level_fields = {} if not fields: return first_level_fields, next_level_fields assert ( isinstance(fields, Iterable) ), "`fields` must be iterable (e.g. list, tuple, or generator)" if isinstance(fields, string_types): fields = [a.strip() for a in fields.split(",") if a.strip()] for e in fields: if "." in e: first_level, next_level = e.split(".", 1) first_level_fields.append(first_level) next_level_fields.setdefault(first_level, []).append(next_level) else: first_level_fields.append(e) first_level_fields = list(set(first_level_fields)) return first_level_fields, next_level_fields
Make sure executing lettuce still results in something sane
from lettuce import before, world, after from splinter.browser import Browser from salad.logger import logger @before.all def setup_master_browser(): try: browser = world.drivers[0] remote_url = world.remote_url except AttributeError, IndexError: browser = 'firefox' remote_url = None world.master_browser = setup_browser(browser, remote_url) world.browser = world.master_browser def setup_browser(browser, url=None): logger.info("Setting up browser %s..." % browser) try: if url: browser = Browser('remote', url=url, browser=browser) else: browser = Browser(browser) except Exception as e: logger.warn("Error starting up %s: %s" % (browser, e)) raise return browser @before.each_scenario def clear_alternative_browsers(step): world.browsers = [] @after.each_scenario def reset_to_parent_frame(step): if hasattr(world, "parent_browser"): world.browser = world.parent_browser @after.each_scenario def restore_browser(step): world.browser = world.master_browser for browser in world.browsers: teardown_browser(browser) @after.all def teardown_master_browser(total): teardown_browser(world.master_browser) def teardown_browser(browser): name = browser.driver_name logger.info("Tearing down browser %s..." % name) try: browser.quit() except: logger.warn("Error tearing down %s" % name)
from lettuce import before, world, after from splinter.browser import Browser from salad.logger import logger @before.all def setup_master_browser(): world.master_browser = setup_browser(world.drivers[0], world.remote_url) world.browser = world.master_browser def setup_browser(browser, url=None): logger.info("Setting up browser %s..." % browser) try: if url: browser = Browser('remote', url=url, browser=browser) else: browser = Browser(browser) except Exception as e: logger.warn("Error starting up %s: %s" % (browser, e)) raise return browser @before.each_scenario def clear_alternative_browsers(step): world.browsers = [] @after.each_scenario def reset_to_parent_frame(step): if hasattr(world, "parent_browser"): world.browser = world.parent_browser @after.each_scenario def restore_browser(step): world.browser = world.master_browser for browser in world.browsers: teardown_browser(browser) @after.all def teardown_master_browser(total): teardown_browser(world.master_browser) def teardown_browser(browser): name = browser.driver_name logger.info("Tearing down browser %s..." % name) try: browser.quit() except: logger.warn("Error tearing down %s" % name)
Allow inactive sessions to last 14 days instead of 1 day
import datetime from db import session import model class UserInfo: def __init__(self, user=None, token=None): self.id = user.id if user else None self.role = user.role if user else None self.token = token self.user = user def is_logged_in(self): return self.id is not None def get_id(self): return self.id def is_admin(self): return self.role == 'admin' def is_org(self): return self.role == 'org' or self.role == 'admin' def is_tester(self): return self.role == 'tester' def update_tokens(): try: # refresh token nechavame v databazi jeste den, aby se uzivatel mohl # znovu prihlasit automaticky (napriklad po uspani pocitace) tokens = session.query(model.Token).all() tokens = [ token for token in tokens if (datetime.datetime.utcnow() > token.expire+datetime.timedelta(days=14)) ] for token in tokens: session.delete(token) session.commit() except: session.rollback() raise
import datetime from db import session import model class UserInfo: def __init__(self, user=None, token=None): self.id = user.id if user else None self.role = user.role if user else None self.token = token self.user = user def is_logged_in(self): return self.id is not None def get_id(self): return self.id def is_admin(self): return self.role == 'admin' def is_org(self): return self.role == 'org' or self.role == 'admin' def is_tester(self): return self.role == 'tester' def update_tokens(): try: # refresh token nechavame v databazi jeste den, aby se uzivatel mohl # znovu prihlasit automaticky (napriklad po uspani pocitace) tokens = session.query(model.Token).all() tokens = [ token for token in tokens if (datetime.datetime.utcnow() > token.expire+datetime.timedelta(days=1)) ] for token in tokens: session.delete(token) session.commit() except: session.rollback() raise
Store current working directory before import
# # This program provides a simple command line to query population statistics. # Author: Tay Joc Cing # Date: 20 Mar 2015 # import sys import os sys.path.append(os.getcwd() + "/classes") from country import Country from datamanager import DataManager from dispatcher import CommandDispatcher from constants import * def main(): from optparse import OptionParser usage = "usage: %prog [[option] <Country regex> [attribute regex]] " version = APP_VERSION parser = OptionParser(usage=usage, version="%prog " + version) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Make lots of noise") parser.add_option("-f", "--file", action="store", dest="filename", help="Initialize store for country stats") (options, args) = parser.parse_args() if len(args) < 1 and options.filename is None: # interactive mode CommandDispatcher() else: dm = DataManager(options.filename, options.verbose, excludeList=['Country']) # command line query mode if len(args) >= 1 and dm.getSize() > 0: # Find countries using regular expression match result = dm.getCountryApprox(args[0]) # if no arguments, then assume all country stats are requested propertyRE = args[1] if len(args) == 2 else "" for c in result: print(c.getPropertyString(propertyRE)) if __name__ == "__main__": main()
# # This program provides a simple command line to query population statistics. # Author: Tay Joc Cing # Date: 20 Mar 2015 # import sys import os from country import Country from datamanager import DataManager from dispatcher import CommandDispatcher from constants import * sys.path.append(os.getcwd() + "/classes") def main(): from optparse import OptionParser usage = "usage: %prog [[option] <Country regex> [attribute regex]] " version = APP_VERSION parser = OptionParser(usage=usage, version="%prog " + version) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Make lots of noise") parser.add_option("-f", "--file", action="store", dest="filename", help="Initialize store for country stats") (options, args) = parser.parse_args() if len(args) < 1 and options.filename is None: # interactive mode CommandDispatcher() else: dm = DataManager(options.filename, options.verbose, excludeList=['Country']) # command line query mode if len(args) >= 1 and dm.getSize() > 0: # Find countries using regular expression match result = dm.getCountryApprox(args[0]) # if no arguments, then assume all country stats are requested propertyRE = args[1] if len(args) == 2 else "" for c in result: print(c.getPropertyString(propertyRE)) if __name__ == "__main__": main()
Fix in admin meta tags
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{__('admin_pages.login_form')}}</title> <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" /> <link href="{{ asset('css/mdb.min.css') }}" rel="stylesheet" /> <link href="{{ asset('css/adminCustom.css') }}" rel="stylesheet" /> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet" /> <link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300|Material+Icons' rel='stylesheet' type='text/css' /> <script src="{{ asset('js/jquery-3.2.1.min.js') }}"></script> </head> <body> @yield('content') <script src="{{ asset('js/bootstrap.min.js') }}"></script> <script src="{{ asset('js/bootbox.min.js') }}"></script> <script src="{{ asset('js/mdb.min.js') }}"></script> <script src="{{ asset('js/placeholders.min.js') }}"></script> </body> </html>
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{__('admin_pages.login_form')}}</title> <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" /> <link href="{{ asset('css/mdb.min.css') }}" rel="stylesheet" /> <link href="{{ asset('css/adminCustom.css') }}" rel="stylesheet" /> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet"> <link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300|Material+Icons' rel='stylesheet' type='text/css'> <script src="{{ asset('js/jquery-3.2.1.min.js') }}"></script> </head> <body> @yield('content') <script src="{{ asset('js/bootstrap.min.js') }}"></script> <script src="{{ asset('js/bootbox.min.js') }}"></script> <script src="{{ asset('js/mdb.min.js') }}"></script> <script src="{{ asset('js/placeholders.min.js') }}"></script> </body> </html>