text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Improve test script, report namespaces for stuff missing docstrings
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
Split up url() logic to separate fxns
<?php namespace allejo\stakx\Twig; use Twig_Environment; class BaseUrlFunction { public function __invoke (Twig_Environment $env, $assetPath) { $globals = $env->getGlobals(); $assetPath = $this->guessAssetPath($assetPath); // @TODO 1.0.0 Remove support for 'base' as it's been deprecated $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl']; $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/'; $url = $this->trimSlashes($assetPath); return ($baseURL . $url); } public static function get () { return new \Twig_SimpleFunction('url', new self(), array( 'needs_environment' => true )); } private function guessAssetPath ($assetPath) { if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess)) { return (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/'; } else if (is_null($assetPath)) { return '/'; } return $assetPath; } private function trimSlashes ($url) { $url = ltrim($url, '/'); if (!empty($url) && $url[strlen($url) - 1] == '/') { return rtrim($url, '/') . '/'; } return $url; } }
<?php namespace allejo\stakx\Twig; use Twig_Environment; class BaseUrlFunction { public function __invoke (Twig_Environment $env, $assetPath) { $globals = $env->getGlobals(); if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess)) { $assetPath = (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/'; } else if (is_null($assetPath)) { $assetPath = '/'; } // @TODO 1.0.0 Remove support for 'base' as it's been deprecated $base = (array_key_exists('base', $globals['site'])) ? $globals['site']['base'] : $globals['site']['baseurl']; $baseURL = (empty($base)) ? '/' : '/' . trim($base, '/') . '/'; $url = ltrim($assetPath, '/'); // Sanity check, remove any excess trailing '/' if (!empty($url) && $url[strlen($url) - 1] == '/') { $url = rtrim($url, '/') . '/'; } return ($baseURL . $url); } public static function get () { return new \Twig_SimpleFunction('url', new self(), array( 'needs_environment' => true )); } }
Use HashSet for reserved user names lookup
package com.cardshifter.core.username; import java.util.*; /** * Instances of this class are guaranteed to be valid user names */ public class UserName { private static final int MIN_LENGTH = 1; private static final int MAX_LENGTH = 20; private static final Collection<String> reservedNames = new HashSet<>(Arrays.asList("Server", "undefined")); private String name; private UserName(String name) { this.name = name; } /** * Try to create a new UserName object * * @param name Any string * @return A UserName guaranteed to be valid * @throws InvalidUserNameException If the proposed name is not valid */ public static UserName create(String name) throws InvalidUserNameException { if (name.length() < MIN_LENGTH) { throw new InvalidUserNameException("Too short"); } if (name.length() > MAX_LENGTH) { throw new InvalidUserNameException("Too long"); } if (name.startsWith(" ") || name.endsWith(" ")) { throw new InvalidUserNameException("Starts or ends with space"); } if (!name.matches("^[a-zA-Z0-9_ ]*$")) { throw new InvalidUserNameException("Invalid characters"); } if (reservedNames.contains(name)) { throw new InvalidUserNameException("Reserved"); } return new UserName(name); } public String asString() { return name; } }
package com.cardshifter.core.username; import java.util.*; /** * Instances of this class are guaranteed to be valid user names */ public class UserName { private static final int MIN_LENGTH = 1; private static final int MAX_LENGTH = 20; private static final Collection<String> reservedNames = Arrays.asList("Server", "undefined"); private String name; private UserName(String name) { this.name = name; } /** * Try to create a new UserName object * * @param name Any string * @return A UserName guaranteed to be valid * @throws InvalidUserNameException If the proposed name is not valid */ public static UserName create(String name) throws InvalidUserNameException { if (name.length() < MIN_LENGTH) { throw new InvalidUserNameException("Too short"); } if (name.length() > MAX_LENGTH) { throw new InvalidUserNameException("Too long"); } if (name.startsWith(" ") || name.endsWith(" ")) { throw new InvalidUserNameException("Starts or ends with space"); } if (!name.matches("^[a-zA-Z0-9_ ]*$")) { throw new InvalidUserNameException("Invalid characters"); } if (reservedNames.contains(name)) { throw new InvalidUserNameException("Reserved"); } return new UserName(name); } public String asString() { return name; } }
Upgrade project to production ready
"""setup.py ..codeauthor:: John Lane <[email protected]> """ from setuptools import setup, find_packages from sda import __author__, __email__, __license__, __version__ setup( name='sda', version=__version__, packages=find_packages(), scripts=[], description='A wrapper for Selenium. This library uses custom data attributes to accelerate ' 'testing through the Selenium framework', author=__author__, author_email=__email__, url='https://github.com/jlane9/selenium-data-attributes', download_url='https://github.com/jlane9/selenium-data-attributes/tarball/{}'.format(__version__), keywords='testing selenium qa web automation', install_requires=['lxml', 'cssselect'], license=__license__, classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing'])
"""setup.py ..codeauthor:: John Lane <[email protected]> """ from setuptools import setup, find_packages from sda import __author__, __email__, __license__, __version__ setup( name='sda', version=__version__, packages=find_packages(), scripts=[], description='A wrapper for Selenium. This library uses custom data attributes to accelerate ' 'testing through the Selenium framework', author=__author__, author_email=__email__, url='https://github.com/jlane9/selenium-data-attributes', download_url='https://github.com/jlane9/selenium-data-attributes/tarball/{}'.format(__version__), keywords='testing selenium qa web automation', install_requires=['lxml', 'cssselect'], license=__license__, classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing'])
Make this one-char variable name a two-char.
from setuptools import find_packages import os.path as op try: from setuptools import setup except ImportError: from distutils.core import setup here = op.abspath(op.dirname(__file__)) # Get metadata from the AFQ/version.py file: ver_file = op.join(here, 'AFQ', 'version.py') with open(ver_file) as f: exec(f.read()) REQUIRES = [] with open(op.join(here, 'requirements.txt')) as f: ll = f.readline()[:-1] while ll: REQUIRES.append(l) ll = f.readline()[:-1] with open(op.join(here, 'README.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, packages=find_packages(), install_requires=REQUIRES, scripts=SCRIPTS, version=VERSION, python_requires=PYTHON_REQUIRES) if __name__ == '__main__': setup(**opts)
from setuptools import find_packages import os.path as op try: from setuptools import setup except ImportError: from distutils.core import setup here = op.abspath(op.dirname(__file__)) # Get metadata from the AFQ/version.py file: ver_file = op.join(here, 'AFQ', 'version.py') with open(ver_file) as f: exec(f.read()) REQUIRES = [] with open(op.join(here, 'requirements.txt')) as f: l = f.readline()[:-1] while l: REQUIRES.append(l) l = f.readline()[:-1] with open(op.join(here, 'README.md'), encoding='utf-8') as f: LONG_DESCRIPTION = f.read() opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, packages=find_packages(), install_requires=REQUIRES, scripts=SCRIPTS, version=VERSION, python_requires=PYTHON_REQUIRES) if __name__ == '__main__': setup(**opts)
Update regex for new error format Closes #34
import Prism from "prismjs"; export function configureRustErrors(gotoPosition) { Prism.languages.rust_errors = { // eslint-disable-line camelcase 'warning':/warning:.*\n/, 'error': { pattern: /error(\[E\d+\])?:.*\n/, inside: { 'error-explanation': /\[E\d+\]/, }, }, 'error-location': /-->.*\n/, }; Prism.hooks.add('wrap', env => { if (env.type === 'error-explanation') { const errorMatch = /E\d+/.exec(env.content); const [errorCode] = errorMatch; env.tag = 'a'; env.attributes.href = `https://doc.rust-lang.org/error-index.html#${errorCode}`; } if (env.type === 'error-location') { const errorMatch = /(\d+):(\d+)/.exec(env.content); const [_, line, col] = errorMatch; env.tag = 'a'; env.attributes.href = '#'; env.attributes['data-line'] = line; env.attributes['data-col'] = col; } }); Prism.hooks.add('after-highlight', env => { env.element.querySelectorAll('.error-location').forEach(link => { const { line, col } = link.dataset; link.onclick = e => { e.preventDefault(); gotoPosition(line, col); }; }); }); }
import Prism from "prismjs"; export function configureRustErrors(gotoPosition) { Prism.languages.rust_errors = { // eslint-disable-line camelcase 'warning':/warning:.*\n/, 'error': { pattern: /error:.*\n/, inside: { 'error-explanation': /\[--explain E\d+\]/, }, }, 'error-location': /-->.*\n/, }; Prism.hooks.add('wrap', env => { if (env.type === 'error-explanation') { const errorMatch = /E\d+/.exec(env.content); const [errorCode] = errorMatch; env.tag = 'a'; env.attributes.href = `https://doc.rust-lang.org/error-index.html#${errorCode}`; } if (env.type === 'error-location') { const errorMatch = /(\d+):(\d+)/.exec(env.content); const [_, line, col] = errorMatch; env.tag = 'a'; env.attributes.href = '#'; env.attributes['data-line'] = line; env.attributes['data-col'] = col; } }); Prism.hooks.add('after-highlight', env => { env.element.querySelectorAll('.error-location').forEach(link => { const { line, col } = link.dataset; link.onclick = e => { e.preventDefault(); gotoPosition(line, col); }; }); }); }
Refactor realm:load to load by realmId vs filename
<?php namespace Realm\Command; use Symfony\Component\Console\Helper\DescriptorHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Command\Command; use Realm\Loader\XmlRealmLoader; use Realm\Model\Project; use RuntimeException; class RealmLoadCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this->ignoreValidationErrors(); $this ->setName('realm:load') ->setDescription('Load realm, and output contents') ->addOption( 'realm', 'r', InputOption::VALUE_REQUIRED, null ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $realmId = $input->getOption('realm'); if (!$realmId) { throw new RuntimeException("Please pass a realm to load"); } $output->writeLn("Loading realm: " . $realmId); $realmLoader = new XmlRealmLoader(); $realm = $realmLoader->load($realmId); var_dump($realm); } }
<?php namespace Realm\Command; use Symfony\Component\Console\Helper\DescriptorHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Command\Command; use Realm\Loader\XmlRealmLoader; use Realm\Model\Project; use RuntimeException; class RealmLoadCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this->ignoreValidationErrors(); $this ->setName('realm:load') ->setDescription('Load realm, and output contents') ->addOption( 'filename', 'f', InputOption::VALUE_REQUIRED, null ) ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $filename = $input->getOption('filename'); if (!$filename) { $filename = getcwd() . '/realm.xml'; } $output->writeLn("Loading realm file: " . $filename); $realm = new Project(); $realmLoader = new XmlRealmLoader(); $realm = $realmLoader->loadFile($filename, $realm); var_dump($realm); } }
Use window dimensions rather than document dimensions so the sizing is more stable
angular.module('WatchTimer') .directive('resizeTextToFill', function($window, $timeout) { return { link: function(scope, element, attrs, controller, transcludeFn) { var initial_font_size = 10; var font_size_increment = 20; var safety_counter_max = 100; function set_size(font_size) { element.css({ fontSize: font_size + "px", lineHeight: font_size + "px" // digits don't need more than this }); } function resize_to_fit() { var font_size = initial_font_size; var max_height = $($window).height() - font_size_increment; var max_width = $($window).width() - font_size_increment; var safety_counter = 0; set_size(font_size); while ( element.height() <= max_height && element.width() <= max_width && safety_counter < safety_counter_max ) { safety_counter++; font_size += font_size_increment; set_size(font_size); } // go back down one size so we know it fits font_size -= font_size_increment; set_size(font_size); } $timeout(function() { resize_to_fit(); }); // 'resize' as the chrome dev toolkit does not trigger an // 'orientationchange' event when switching between oriantations. $($window).on("resize orientationchange", resize_to_fit); } }; })
angular.module('WatchTimer') .directive('resizeTextToFill', function($document, $timeout) { return { link: function(scope, element, attrs, controller, transcludeFn) { var initial_font_size = 10; var font_size_increment = 20; var safety_counter_max = 100; function set_size(font_size) { element.css({ fontSize: font_size + "px", lineHeight: font_size + "px" // digits don't need more than this }); } function resize_to_fit() { var font_size = initial_font_size; var max_height = $document.height() - font_size_increment; var max_width = $document.width() - font_size_increment; var safety_counter = 0; set_size(font_size); while ( element.height() <= max_height && element.width() <= max_width && safety_counter < safety_counter_max ) { safety_counter++; font_size += font_size_increment; set_size(font_size); } // go back down one size so we know it fits font_size -= font_size_increment; set_size(font_size); } $timeout(function() { resize_to_fit(); }); // 'resize' as the chrome dev toolkit does not trigger an // 'orientationchange' event when switching between oriantations. $(window).on("resize orientationchange", resize_to_fit); } }; })
Set columns to reactivate component
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'deactivated_at', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: null, model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), (item.deactivated_at) ? m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : '' ]), ]); } }; }(window.m, window._, window.c));
window.c.AdminUserDetail = (function(m, _, c){ return { controller: function(){ return { actions: { reset: { property: 'user_password', updateKey: 'password', callToAction: 'Redefinir', innerLabel: 'Nova senha de Usuário:', outerLabel: 'Redefinir senha', placeholder: 'ex: 123mud@r', model: c.models.userDetail }, reactivate: { property: 'state', updateKey: 'id', callToAction: 'Reativar', innerLabel: 'Tem certeza que deseja reativar esse usuário?', outerLabel: 'Reativar usuário', forceValue: 'deleted', model: c.models.userDetail } } }; }, view: function(ctrl, args){ var actions = ctrl.actions, item = args.item, details = args.details; return m('#admin-contribution-detail-box', [ m('.divider.u-margintop-20.u-marginbottom-20'), m('.w-row.u-marginbottom-30', [ m.component(c.AdminInputAction, {data: actions.reset, item: item}), (item.deactivated_at) ? m.component(c.AdminInputAction, {data: actions.reactivate, item: item}) : '' ]), ]); } }; }(window.m, window._, window.c));
Fix typo in requests helper
from __future__ import absolute_import from __future__ import unicode_literals import json import requests from django.conf import settings from mesoshttp.acs import DCOSServiceAuth DCOS_AUTH = None DCOS_VERIFY = True if settings.SERVICE_SECRET: # We are in Enterprise mode and using service account DCOS_AUTH = DCOSServiceAuth((json.loads(settings.SERVICE_SECRET))) cert_file = 'dcos-ca.crt' response = requests.get('https://leader.mesos/ca/' + cert_file, verify=False) if response.status_code == 200: with open(cert_file, 'w') as cert: cert.write(response.text) DCOS_VERIFY = cert_file def make_dcos_request(host_address, relative_url, params=None): """Makes a requests that is capable of traversing DCOS EE Strict boundary :param master: The address for the Mesos master :type master: `util.host.HostAddress` :param relative_url: URL path relative to the base address :type relative_url: basestring :param params: The query parameters for request :type params: dict :returns: The request response object :rtype: :class:`requests.Response` """ return requests.get('%s://%s:%s%s' % (host_address.protocol, host_address.hostname, host_address.port, relative_url), params=params, auth=DCOS_AUTH, verify=DCOS_VERIFY)
from __future__ import absolute_import from __future__ import unicode_literals import json import requests from django.conf import settings from mesoshttp.acs import DCOSServiceAuth DCOS_AUTH = None DCOS_VERIFY = True if settings.SERVICE_SECRET: # We are in Enterprise mode and using service account DCOS_AUTH = DCOSServiceAuth((json.loads(settings.SERVICE_SECRET))) cert_file = 'dcos-ca.crt' response = requests.get('https://leader.mesos/ca/' + cert_file, verify=False) if response.status_code == 200: with open(cert_file, 'w') as cert: cert.write(response.text) DCOS_VERIFY = cert_file def make_dcos_request(host_address, relative_url, params=None): """Makes a requests that is capable of traversing DCOS EE Strict boundary :param master: The address for the Mesos master :type master: `util.host.HostAddress` :param relative_url: URL path relative to the base address :type relative_url: basestring :param params: The query parameters for request :type params: dict :returns: The request response object :rtype: :class:`requests.Response` """ return requests.get('%s://%s:%s%s' % (host_address.protocol, host_address.hostname, host_address.port, relative_url), param=params, auth=DCOS_AUTH, verify=DCOS_VERIFY)
Move GlossaryManager to tabpanels package (leftover)
/* * 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/. */ package net.localizethat.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import net.localizethat.Main; import net.localizethat.gui.tabpanels.GlossaryGuiManager; /** * Opens a tab with the Glossary manager in the main window * @author rpalomares */ public class GlossaryManagerAction extends AbstractAction { private static final String TITLE = "Glossary Manager"; private static final String DESCRIPTION = "Opens " + TITLE; private static final int MNEMONIC = java.awt.event.KeyEvent.VK_G; private GlossaryGuiManager glossaryGuiMgr; /** * Action representing the launching of the Main panel as a tab in main window */ public GlossaryManagerAction() { super(TITLE); putValue(SHORT_DESCRIPTION, DESCRIPTION); putValue(MNEMONIC_KEY, MNEMONIC); putValue(ACCELERATOR_KEY, javax.swing.KeyStroke.getKeyStroke(MNEMONIC, java.awt.event.InputEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { if (glossaryGuiMgr == null) { glossaryGuiMgr = new GlossaryGuiManager(); } Main.mainWindow.addTab(glossaryGuiMgr, TITLE); } }
/* * 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/. */ package net.localizethat.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import net.localizethat.Main; import net.localizethat.gui.GlossaryGuiManager; /** * Opens a tab with the Glossary manager in the main window * @author rpalomares */ public class GlossaryManagerAction extends AbstractAction { private static final String TITLE = "Glossary Manager"; private static final String DESCRIPTION = "Opens " + TITLE; private static final int MNEMONIC = java.awt.event.KeyEvent.VK_G; private GlossaryGuiManager glossaryGuiMgr; /** * Action representing the launching of the Main panel as a tab in main window */ public GlossaryManagerAction() { super(TITLE); putValue(SHORT_DESCRIPTION, DESCRIPTION); putValue(MNEMONIC_KEY, MNEMONIC); putValue(ACCELERATOR_KEY, javax.swing.KeyStroke.getKeyStroke(MNEMONIC, java.awt.event.InputEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { if (glossaryGuiMgr == null) { glossaryGuiMgr = new GlossaryGuiManager(); } Main.mainWindow.addTab(glossaryGuiMgr, TITLE); } }
Remove status enable filter on multiselect source
<?php /** * Studioforty9 Gallery * * @category Studioforty9 * @package Studioforty9_Gallery * @author StudioForty9 <[email protected]> * @copyright 2015 StudioForty9 (http://www.studioforty9.com) * @license https://github.com/studioforty9/gallery/blob/master/LICENCE BSD * @version 1.0.0 * @link https://github.com/studioforty9/gallery */ /** * Studioforty9_Gallery_Model_Source_Album_Multiselect * * @category Studioforty9 * @package Studioforty9_Gallery * @subpackage Model */ class Studioforty9_Gallery_Model_Source_Album_Multiselect { /** * Create a list of multiselect options for selecting albums. * * @return array */ public function toOptionsArray() { $albums = Mage::getModel('studioforty9_gallery/album')->getCollection() ->addFieldToSelect(array('name', 'entity_id')) ->addOrder('name', 'ASC'); $options = array(); if ($albums->count() > 0) { foreach ($albums as $album) { $options[] = array( 'label' => $album->getName(), 'value' => (int) $album->getId() ); } } return $options; } }
<?php /** * Studioforty9 Gallery * * @category Studioforty9 * @package Studioforty9_Gallery * @author StudioForty9 <[email protected]> * @copyright 2015 StudioForty9 (http://www.studioforty9.com) * @license https://github.com/studioforty9/gallery/blob/master/LICENCE BSD * @version 1.0.0 * @link https://github.com/studioforty9/gallery */ /** * Studioforty9_Gallery_Model_Source_Album_Multiselect * * @category Studioforty9 * @package Studioforty9_Gallery * @subpackage Model */ class Studioforty9_Gallery_Model_Source_Album_Multiselect { /** * Create a list of multiselect options for selecting albums. * * @return array */ public function toOptionsArray() { $albums = Mage::getModel('studioforty9_gallery/album')->getCollection() ->addFieldToSelect(array('name', 'entity_id')) ->addOrder('name', 'ASC') ->addFieldToFilter( 'status', array( 'eq' => Studioforty9_Gallery_Model_Album::ENABLED ) ); $options = array(); if ($albums->count() > 0) { foreach ($albums as $album) { $options[] = array( 'label' => $album->getName(), 'value' => (int) $album->getId() ); } } return $options; } }
Fix auth, using Europe/Prague timezone to get right hour for auth
<?php namespace Lubos\Wedos\Shell; use Cake\Console\Shell; use Cake\Core\Configure; use Cake\Network\Http\Client; use DateTime; use DateTimeZone; class WedosShell extends Shell { /** * Initial settings on startup * * @return void */ public function startup() { $data = Configure::read('Wedos'); if (!isset($data['user']) || !isset($data['password'])) { $this->error('Please set up Wedos user and password'); } $this->client = new Client(); $date = new DateTime(); $date->setTimeZone(new DateTimeZone("Europe/Prague")); $this->request = [ 'request' => [ 'user' => $data['user'], 'auth' => sha1(implode([ $data['user'], sha1($data['password']), $date->format('H') ])), ] ]; $this->url = 'https://api.wedos.com/wapi/xml'; } /** * Main function Prints out the list of shells. * * @return void */ public function main() { $this->out($this->OptionParser->help()); } }
<?php namespace Lubos\Wedos\Shell; use Cake\Console\Shell; use Cake\Core\Configure; use Cake\Network\Http\Client; class WedosShell extends Shell { /** * Initial settings on startup * * @return void */ public function startup() { $data = Configure::read('Wedos'); if (!isset($data['user']) || !isset($data['password'])) { $this->error('Please set up Wedos user and password'); } $this->client = new Client(); $this->request = [ 'request' => [ 'user' => $data['user'], 'auth' => sha1(implode([ $data['user'], sha1($data['password']), date('H', time()) ])), ] ]; $this->url = 'https://api.wedos.com/wapi/xml'; } /** * Main function Prints out the list of shells. * * @return void */ public function main() { $this->out($this->OptionParser->help()); } }
Increase timeout for test_long_running_job test
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils.platform # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing functions ''' def test_long_running_job(self): ''' Test that we will wait longer than the job timeout for a minion to return. ''' # Launch the command sleep_length = 30 if salt.utils.platform.is_windows(): popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))} else: popen_kwargs = None ret = self.run_salt( 'minion test.sleep {0}'.format(sleep_length), timeout=90, catch_stderr=True, popen_kwargs=popen_kwargs, ) self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion' ' may have returned error: {0}'.format(ret)) self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret)) self.assertTrue('True' in ret[0][1], 'Minion did not return True after ' '{0} seconds. ret={1}'.format(sleep_length, ret))
# -*- coding: utf-8 -*- ''' Tests for various minion timeouts ''' # Import Python libs from __future__ import absolute_import import os import sys import salt.utils.platform # Import Salt Testing libs from tests.support.case import ShellCase class MinionTimeoutTestCase(ShellCase): ''' Test minion timing functions ''' def test_long_running_job(self): ''' Test that we will wait longer than the job timeout for a minion to return. ''' # Launch the command sleep_length = 30 if salt.utils.platform.is_windows(): popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))} else: popen_kwargs = None ret = self.run_salt( 'minion test.sleep {0}'.format(sleep_length), timeout=45, catch_stderr=True, popen_kwargs=popen_kwargs, ) self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion' ' may have returned error: {0}'.format(ret)) self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret)) self.assertTrue('True' in ret[0][1], 'Minion did not return True after ' '{0} seconds. ret={1}'.format(sleep_length, ret))
Make 'read' the default 'file' action
const actionTypes = require('../actions/actionTypes'); const actions = require('../actions'); const { identity, omit } = require('lodash/fp'); const fs = require('fs'); const request = require('request'); const runTypes = { file: (data, store, action) => { const fileAction = data.fileAction; const filename = data.filename; switch (fileAction) { case 'write': { const outstream = fs.createWriteStream(filename); const outData = omit(['runType', 'filename', 'fileAction'], data); const outStr = JSON.stringify(outData, null, 2); outstream.write(outStr); return; } case 'read': default: { fs.readFile(filename, 'utf8', (err, contents) => { store.dispatch(action(JSON.parse(contents))); }); return; } } }, http: (data, store, action) => request(omit(['runType'], data), (err, res) => { store.dispatch(action(res)); }), }; module.exports = store => next => action => { switch (action.type) { case actionTypes.RUN: const data = store.getState().data; const runType = data.runType; const handler = runTypes[runType] || identity; handler(data, store, actions.setData); return next(action); default: return next(action); } };
const actionTypes = require('../actions/actionTypes'); const actions = require('../actions'); const { identity, omit } = require('lodash/fp'); const fs = require('fs'); const request = require('request'); const runTypes = { file: (data, store, action) => { const fileAction = data.fileAction; const filename = data.filename; switch (fileAction) { case 'read': { fs.readFile(filename, 'utf8', (err, contents) => { store.dispatch(action(JSON.parse(contents))); }); return; } case 'write': { const outstream = fs.createWriteStream(filename); const outData = omit(['runType', 'filename', 'fileAction'], data); const outStr = JSON.stringify(outData, null, 2); outstream.write(outStr); return; } default: return; } }, http: (data, store, action) => request(omit(['runType'], data), (err, res) => { store.dispatch(action(res)); }), }; module.exports = store => next => action => { switch (action.type) { case actionTypes.RUN: const data = store.getState().data; const runType = data.runType; const handler = runTypes[runType] || identity; handler(data, store, actions.setData); return next(action); default: return next(action); } };
Add skip support to shim
// Temporary Shim File for use while migrating from QUnit to Mocha /*global chai */ function qunitShim() { var _currentTest, _describe = describe; function emitQUnit() { if (_currentTest) { _describe(_currentTest.name, function() { var config = _currentTest.config; if (config && config.setup) { beforeEach(config.setup); } if (config && config.teardown) { afterEach(config.teardown); } _.each(_currentTest.tests, function(config) { it(config.msg, config.exec); }); }); } _currentTest = undefined; } window.describe = function(name, exec) { emitQUnit(); _describe.call(this, name, exec); }; window.describe.skip = function(name, exec) { emitQUnit(); _describe.skip.call(this, name, exec); }; window.test = function(msg, exec) { if (typeof exec === 'number') { exec = arguments[2]; } if (_currentTest) { _currentTest.tests.push({msg: msg, exec: exec}); } else { it(msg, exec); } }; window.QUnit = { test: window.test, module: function(name, config) { emitQUnit(); _currentTest = { name: name, config: config, tests: [] }; } }; window.equal = chai.assert.equal; window.deepEqual = chai.assert.deepEqual; window.notEqual = chai.assert.notEqual; window.ok = chai.assert.ok; }
// Temporary Shim File for use while migrating from QUnit to Mocha /*global chai */ function qunitShim() { var _currentTest, _describe = describe; function emitQUnit() { if (_currentTest) { _describe(_currentTest.name, function() { var config = _currentTest.config; if (config && config.setup) { beforeEach(config.setup); } if (config && config.teardown) { afterEach(config.teardown); } _.each(_currentTest.tests, function(config) { it(config.msg, config.exec); }); }); } _currentTest = undefined; } window.describe = function(name, exec) { emitQUnit(); _describe.call(this, name, exec); }; window.test = function(msg, exec) { if (typeof exec === 'number') { exec = arguments[2]; } if (_currentTest) { _currentTest.tests.push({msg: msg, exec: exec}); } else { it(msg, exec); } }; window.QUnit = { test: window.test, module: function(name, config) { emitQUnit(); _currentTest = { name: name, config: config, tests: [] }; } }; window.equal = chai.assert.equal; window.deepEqual = chai.assert.deepEqual; window.notEqual = chai.assert.notEqual; window.ok = chai.assert.ok; }
Add base trove classifier for Django. Implying "currently supported versions".
from setuptools import find_packages, setup from channels import __version__ setup( name='channels', version=__version__, url='http://github.com/django/channels', author='Django Software Foundation', author_email='[email protected]', description="Brings async, event-driven capabilities to Django. Django 2.2 and up only.", license='BSD', packages=find_packages(exclude=['tests']), include_package_data=True, python_requires='>=3.6', install_requires=[ 'Django>=2.2', 'asgiref~=3.2', 'daphne~=2.3', ], extras_require={ 'tests': [ "pytest", "pytest-django", "pytest-asyncio", "async_generator", "async-timeout", "coverage~=4.5", ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Framework :: Django', 'Topic :: Internet :: WWW/HTTP', ], )
from setuptools import find_packages, setup from channels import __version__ setup( name='channels', version=__version__, url='http://github.com/django/channels', author='Django Software Foundation', author_email='[email protected]', description="Brings async, event-driven capabilities to Django. Django 2.2 and up only.", license='BSD', packages=find_packages(exclude=['tests']), include_package_data=True, python_requires='>=3.6', install_requires=[ 'Django>=2.2', 'asgiref~=3.2', 'daphne~=2.3', ], extras_require={ 'tests': [ "pytest", "pytest-django", "pytest-asyncio", "async_generator", "async-timeout", "coverage~=4.5", ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Internet :: WWW/HTTP', ], )
Resolve todo (set correct class)
<?php class Kwc_Favourites_Box_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js'; $ret['favouritesPageComponentClass'] = 'Kwc_Favourites_Page_Component'; $ret['viewCache'] = false; $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})'); return $ret; } public function getTemplateVars() { $ret = parent::getTemplateVars(); $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser(); if ($user) { $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model'); $select = new Kwf_Model_Select(); $select->whereEquals('user_id', $user->id); $count = $model->countRows($select); $ret['linkText'] = str_replace('{0}', "<span class=\"cnt\">$count</span>", $this->_getPlaceholder('linkText')); } $class = Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponentClass'); if (!$class) { throw new Kwf_Exception('Set favouritesComponent (favourites-page) in getSettings'); } $ret['favourite'] = Kwf_Component_Data_Root::getInstance() ->getComponentByClass($class); return $ret; } }
<?php class Kwc_Favourites_Box_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js'; $ret['favouritesPageComponentClass'] = null; //TODO set to kwc-favourites-page $ret['viewCache'] = false; $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})'); return $ret; } public function getTemplateVars() { $ret = parent::getTemplateVars(); $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser(); if ($user) { $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model'); $select = new Kwf_Model_Select(); $select->whereEquals('user_id', $user->id); $count = $model->countRows($select); $ret['linkText'] = str_replace('{0}', "<span class=\"cnt\">$count</span>", $this->_getPlaceholder('linkText')); } $class = Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponentClass'); if (!$class) { throw new Kwf_Exception('Set favouritesComponent (favourites-page) in getSettings'); } $ret['favourite'] = Kwf_Component_Data_Root::getInstance() ->getComponentByClass($class); return $ret; } }
Reorder logic to make the intention clearer
define([ 'extensions/views/view' ], function (View) { var SingleStatView = View.extend({ changeOnSelected: false, valueTag: 'strong', initialize: function () { View.prototype.initialize.apply(this, arguments); var events = 'reset'; if (this.changeOnSelected) { events += ' change:selected'; } this.collection.on(events, this.render, this); }, render: function () { View.prototype.render.apply(this, arguments); var value, label; var selection = this.collection.getCurrentSelection(); if (this.changeOnSelected && selection.selectedModel) { value = this.getValueSelected(selection); label = this.getLabelSelected(selection); } else { value = this.getValue(); label = this.getLabel(); } var content = null; if (value === null) { content = "<span class='no-data'>(no data)</span>"; } else if (this.valueTag) { content = '<' + this.valueTag + '>' + value + '</' + this.valueTag + '>'; } else { content = value; } if (label) { content += ' ' + label; } this.$el.html(content); }, getLabel: function () { return ''; }, getLabelSelected: function () { return ''; } }); return SingleStatView; });
define([ 'extensions/views/view' ], function (View) { var SingleStatView = View.extend({ changeOnSelected: false, valueTag: 'strong', initialize: function () { View.prototype.initialize.apply(this, arguments); var events = 'reset'; if (this.changeOnSelected) { events += ' change:selected'; } this.collection.on(events, this.render, this); }, render: function () { View.prototype.render.apply(this, arguments); var value, label; var selection = this.collection.getCurrentSelection(); if (this.changeOnSelected && selection.selectedModel) { value = this.getValueSelected(selection); label = this.getLabelSelected(selection); } else { value = this.getValue(); label = this.getLabel(); } var content = value; if (this.valueTag && value !== null) { content = '<' + this.valueTag + '>' + value + '</' + this.valueTag + '>'; } if (value === null) { content = "<span class='no-data'>(no data)</span>"; } if (label) { content += ' ' + label; } this.$el.html(content); }, getLabel: function () { return ''; }, getLabelSelected: function () { return ''; } }); return SingleStatView; });
Add comment why we are manually saving the session
<?php namespace Auth0\Login; use Session; use Auth0\SDK\Store\StoreInterface; class LaravelSessionStore implements StoreInterface { const BASE_NAME = 'auth0_'; /** * Persists $value on $_SESSION, identified by $key. * * @see Auth0SDK\BaseAuth0 * * @param string $key * @param mixed $value */ public function set($key, $value) { $key_name = $this->getSessionKeyName($key); Session::put($key_name, $value); // The Auth0 SDK might decide to redirect and exit the PHP execution // before the Laravel middleware can write the changes. // thus we have to persist our changes early Session::save(); } /** * @param $key * @param null $default * * @return mixed */ public function get($key, $default = null) { $key_name = $this->getSessionKeyName($key); return Session::get($key_name, $default); } /** * Removes a persisted value identified by $key. * * @see Auth0SDK\BaseAuth0 * * @param string $key */ public function delete($key) { $key_name = $this->getSessionKeyName($key); Session::forget($key_name); } /** * Constructs a session var name. * * @param string $key * * @return string */ public function getSessionKeyName($key) { return self::BASE_NAME.'_'.$key; } }
<?php namespace Auth0\Login; use Session; use Auth0\SDK\Store\StoreInterface; class LaravelSessionStore implements StoreInterface { const BASE_NAME = 'auth0_'; /** * Persists $value on $_SESSION, identified by $key. * * @see Auth0SDK\BaseAuth0 * * @param string $key * @param mixed $value */ public function set($key, $value) { $key_name = $this->getSessionKeyName($key); Session::put($key_name, $value); Session::save(); } /** * @param $key * @param null $default * * @return mixed */ public function get($key, $default = null) { $key_name = $this->getSessionKeyName($key); return Session::get($key_name, $default); } /** * Removes a persisted value identified by $key. * * @see Auth0SDK\BaseAuth0 * * @param string $key */ public function delete($key) { $key_name = $this->getSessionKeyName($key); Session::forget($key_name); } /** * Constructs a session var name. * * @param string $key * * @return string */ public function getSessionKeyName($key) { return self::BASE_NAME.'_'.$key; } }
Revert "change to field for testing"
from django.shortcuts import redirect from django.http import JsonResponse from django.core.mail import EmailMessage from django.middleware import csrf from rest_framework.decorators import api_view @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': to_address = request.POST.get("to_address", "").split(',') from_name = request.POST.get("from_name", "") from_address = request.POST.get("from_address", "") from_string = '{} <{}>'.format(from_name, from_address) subject = request.POST.get("subject", "") message_body = request.POST.get("message_body", "") csrf_token = request.POST.get("csrfmiddlewaretoken", "") email = EmailMessage(subject, message_body, '[email protected]', to_address, reply_to=[from_string]) email.send(fail_silently=False) #return redirect('/contact-thank-you') data = {'subject': subject, 'message_body': message_body, 'to_address': to_address, 'reply_to': [from_string], 'from_address': '[email protected]', 'csrf_token': csrf_token, } return JsonResponse(data) # if this is not posting a message, let's send the csfr token back else: csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return JsonResponse(data)
from django.shortcuts import redirect from django.http import JsonResponse from django.core.mail import EmailMessage from django.middleware import csrf from rest_framework.decorators import api_view @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': to_address = request.POST.get("to_address", "").split(',') from_name = request.POST.get("from_name", "") from_address = request.POST.get("from_address", "") from_string = '{} <{}>'.format(from_name, from_address) subject = request.POST.get("subject", "") message_body = request.POST.get("message_body", "") csrf_token = request.POST.get("csrfmiddlewaretoken", "") email = EmailMessage(subject, message_body, '[email protected]', ["[email protected]"], reply_to=[from_string]) email.send(fail_silently=False) #return redirect('/contact-thank-you') data = {'subject': subject, 'message_body': message_body, 'to_address': to_address, 'reply_to': [from_string], 'from_address': '[email protected]', 'csrf_token': csrf_token, } return JsonResponse(data) # if this is not posting a message, let's send the csfr token back else: csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return JsonResponse(data)
REFACTOR : Removed unnecessary code.
from hitchstory import utils, exceptions from ruamel.yaml.comments import CommentedMap, CommentedSeq class Arguments(object): """A null-argument, single argument or group of arguments of a hitchstory step.""" def __init__(self, yaml_args): """Create arguments from dict (from yaml).""" if yaml_args is None: self.is_none = True self.single_argument = False elif type(yaml_args) is CommentedMap: self.is_none = False self.single_argument = False self.kwargs = yaml_args else: self.is_none = False self.single_argument = True self.argument = yaml_args def validate(self, validators): """ Validate step using validators specified in decorators. """ if not self.is_none and not self.single_argument: _kwargs = {} for key, value in self.kwargs.items(): if key in validators.keys(): _kwargs[key] = validators[key](value) else: if type(value) in (CommentedMap, CommentedSeq): raise exceptions.StepArgumentWithoutValidatorContainsComplexData else: _kwargs[key] = str(value) self.kwargs = _kwargs def pythonized_kwargs(self): pythonized_dict = {} for key, value in self.kwargs.items(): pythonized_dict[utils.to_underscore_style(key)] = value return pythonized_dict
from hitchstory import utils, exceptions from ruamel.yaml.comments import CommentedMap, CommentedSeq class Arguments(object): """A null-argument, single argument or group of arguments of a hitchstory step.""" def __init__(self, yaml_args): """Create arguments from dict (from yaml).""" if yaml_args is None: self.is_none = True self.single_argument = False elif type(yaml_args) is CommentedMap: self.is_none = False self.single_argument = False self.kwargs = yaml_args else: self.is_none = False self.single_argument = True self.argument = yaml_args def validate(self, validators): if self.is_none: return elif self.single_argument: return else: _kwargs = {} for key, value in self.kwargs.items(): if key in validators.keys(): _kwargs[key] = validators[key](value) else: if type(value) in (CommentedMap, CommentedSeq): raise exceptions.StepArgumentWithoutValidatorContainsComplexData else: _kwargs[key] = str(value) self.kwargs = _kwargs return def pythonized_kwargs(self): pythonized_dict = {} for key, value in self.kwargs.items(): pythonized_dict[utils.to_underscore_style(key)] = value return pythonized_dict def to_dict(self): if self.is_none: return None elif self.single_argument: return self.argument else: return self.kwargs
Add reconstruct corpus as a test
#!/usr/bin/env python3 from __future__ import print_function import argparse import collections import random import sys def reconstruct(f_in, f_out): sentence_starts = [] contexts = {} for line in f_in: parts = line.split() words = parts[:-1] count = int(parts[-1]) if words[0] == "<s>" and words[-1] == "</s>": for _ in range(count): print(" ".join(words), file=f_out) continue context = tuple(words[:-1]) if context not in contexts: contexts[context] = collections.Counter() contexts[context][words[-1]] += count random.shuffle(sentence_starts) c = len(sentence_starts[0]) - 1 for start in sentence_starts: line = list(start) while line[-1] != "</s>": context = line[:-c] next_word = contexts[context].most_common(1)[0][0] contexts[context][next_word] -= 1 line.append(next_word) print(" ".join(line), file=f_out) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Construct corpus') parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin) parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout) args = parser.parse_args() reconstruct(args.infile, args.outfile)
#!/usr/bin/env python3 import argparse import collections import random import sys def reconstruct(f_in, f_out): sentence_starts = [] contexts = {} for line in f_in: parts = line.split() words = parts[:-1] count = int(parts[-1]) if words[0] == "<s>" and words[-1] == "</s>": for _ in range(count): print(" ".join(words), file=f_out) continue context = tuple(words[:-1]) if context not in contexts: contexts[context] = collections.Counter() contexts[context][words[-1]] += count random.shuffle(sentence_starts) c = len(sentence_starts[0]) - 1 for start in sentence_starts: line = list(start) while line[-1] != "</s>": context = line[:-c] next_word = contexts[context].most_common(1)[0][0] contexts[context][next_word] -= 1 line.append(next_word) print(" ".join(line), file=f_out) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Construct corpus') parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin) parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout) args = parser.parse_args() reconstruct(args.infile, args.outfile)
Use Ramsey/Uuid instead of Rhumsaa
<?php namespace Madewithlove\LaravelCqrsEs\Identifier; use Ramsey\Uuid\Uuid; class UuidIdentifier implements Identifier { /** * @var Uuid */ protected $value; /** * @param Uuid $value */ public function __construct(Uuid $value) { $this->value = $value; } /** * @return static */ public static function generate() { return new static(Uuid::uuid4()); } /** * @param $string * * @return static */ public static function fromString($string) { return new static(Uuid::fromString($string)); } /** * @param Identifier $identifier * * @return bool */ public function equals(Identifier $identifier) { return $this == $identifier; } /** * @return string */ public function toString() { return $this->value->toString(); } /** * @return string */ public function __toString() { return $this->value->toString(); } /** * @param array $data * * @return UuidIdentifier */ public static function deserialize(array $data) { return static::fromString($data['value']); } /** * @return string */ public function serialize() { return [ 'value' => $this->toString(), ]; } }
<?php namespace Madewithlove\LaravelCqrsEs\Identifier; use Rhumsaa\Uuid\Uuid; class UuidIdentifier implements Identifier { /** * @var Uuid */ protected $value; /** * @param Uuid $value */ public function __construct(Uuid $value) { $this->value = $value; } /** * @return static */ public static function generate() { return new static(Uuid::uuid4()); } /** * @param $string * * @return static */ public static function fromString($string) { return new static(Uuid::fromString($string)); } /** * @param Identifier $identifier * * @return bool */ public function equals(Identifier $identifier) { return $this == $identifier; } /** * @return string */ public function toString() { return $this->value->toString(); } /** * @return string */ public function __toString() { return $this->value->toString(); } /** * @param array $data * * @return UuidIdentifier */ public static function deserialize(array $data) { return static::fromString($data['value']); } /** * @return string */ public function serialize() { return [ 'value' => $this->toString(), ]; } }
Fix for chrome developer tools console
if (typeof define === 'undefined' && typeof importScripts !== 'undefined') importScripts('lib/require.js'); var string_split = /(\w+)(\s\w+){0,1}$/ window = self; require( ['worker_console', 'x_protocol', 'endianbuffer'] , function (console, x_protocol, EndianBuffer) { self.console = console; var buffer = null , clients = {} , server = null; var socket = null; self.addEventListener('message', function (event) { switch (event.data.cmd) { case 'connect': if (server) return postMessage({ cmd: 'error', message: 'Server exists!' }); var socket = new WebSocket('ws://' + event.data.address, 'x11-proxy'); socket.binaryType = 'arraybuffer'; server = new x_protocol.XProtocolServer(socket, function () { postMessage({ cmd: 'close' }) server = null; }); break; case 'disconnect': if (! server) return postMessage({ cmd: 'error', message: 'not connected' }) socket.close(); break; case 'message': if (! server) return postMessage({ cmd: 'error', message: 'not connected' }) if (! server.clients[event.data.id]) throw new Error('Invalid client! Disconnected?'); server.serverMessage(event.data); break; } }); } )
if (typeof define === 'undefined' && typeof importScripts !== 'undefined') importScripts('lib/require.js'); var string_split = /(\w+)(\s\w+){0,1}$/ require( ['worker_console', 'x_protocol', 'endianbuffer'] , function (console, x_protocol, EndianBuffer) { var buffer = null , clients = {} , server = null; var socket = null; addEventListener('message', function (event) { switch (event.data.cmd) { case 'connect': if (server) return postMessage({ cmd: 'error', message: 'Server exists!' }); var socket = new WebSocket('ws://' + event.data.address, 'x11-proxy'); socket.binaryType = 'arraybuffer'; server = new x_protocol.XProtocolServer(socket, function () { server = null; }); break; case 'disconnect': if (! server) return postMessage({ cmd: 'error', message: 'not connected' }) socket.close(); break; case 'message': if (! server) return postMessage({ cmd: 'error', message: 'not connected' }) if (! server.clients[event.data.id]) throw new Error('Invalid client! Disconnected?'); server.serverMessage(event.data); break; } }); } )
Fix enum (how did this work?)
"use strict"; module.exports = function(sequelize, DataTypes) { var Task = sequelize.define("Task", { taskID: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING, allowNull: false }, taskType: { type: DataTypes.ENUM('todo', 'exercise', 'meal', 'meeting', 'other'), allowNull: false, defaultValue: 'other' }, date: { type: DataTypes.DATE, defaultValue: DataTypes.NOW }, time: { type: DataTypes.STRING, allowNull: true, defaultValue: null }, moveable: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, autoMoveable: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: null }, description: { type: DataTypes.TEXT, allowNull: false, defaultValue: '' }, stravaID: { type: DataTypes.INTEGER, allowNull: true, defaultValue: null }, isRecurring: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, recPeriod: { type: DataTypes.ENUM('week', 'month'), allowNull: true, defaultValue: null }, recRange: { type: DataTypes.INTEGER, allowNull: true, defaultValue: null } }, { classMethods: { associate: function(models) { Task.belongsTo(models.User, { onDelete: "CASCADE", foreignKey: { allowNull: false } }); Task.hasMany(models.TaskRecurrence); } } }); return Task; }
"use strict"; module.exports = function(sequelize, DataTypes) { var Task = sequelize.define("Task", { taskID: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING, allowNull: false }, taskType: { type: DataTypes.ENUM('todo', 'exercise', 'meal', 'meeting', 'other'), allowNull: false, defaultValue: 'other' }, date: { type: DataTypes.DATE, defaultValue: DataTypes.NOW }, time: { type: DataTypes.STRING, allowNull: true, defaultValue: null }, moveable: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, autoMoveable: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: null }, description: { type: DataTypes.TEXT, allowNull: false, defaultValue: '' }, stravaID: { type: DataTypes.INTEGER, allowNull: true, defaultValue: null }, isRecurring: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, recPeriod: { type: DataTypes.ENUM('weekly', 'monthly'), allowNull: true, defaultValue: null }, recRange: { type: DataTypes.INTEGER, allowNull: true, defaultValue: null } }, { classMethods: { associate: function(models) { Task.belongsTo(models.User, { onDelete: "CASCADE", foreignKey: { allowNull: false } }); Task.hasMany(models.TaskRecurrence); } } }); return Task; }
Move serial device path to settings
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' ITEM_MAP = { "5236713": "kitchen", "7697747": "hall", "1328959": "front-door", "247615": "unused-magnetic-switch", "8981913": "table", } def handle(self, *args, **options): s = serial.Serial(settings.ARDUINO_433, 9600) sent_event_map = {} while True: line = s.readline() print "- %s" % line if line.startswith("Received "): id = line.split(" ")[1] if id in self.ITEM_MAP: item_name = self.ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: print "Too recent event: %s" % item_name continue process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: print "Unknown id: %s" % id
from django.core.management.base import BaseCommand, CommandError from control_milight.utils import process_automatic_trigger import serial import time class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' ITEM_MAP = { "5236713": "kitchen", "7697747": "hall", "1328959": "front-door", "247615": "unused-magnetic-switch", "8981913": "table", } def handle(self, *args, **options): s = serial.Serial("/dev/tty.usbserial-A9007LzM", 9600) sent_event_map = {} while True: line = s.readline() print "- %s" % line if line.startswith("Received "): id = line.split(" ")[1] if id in self.ITEM_MAP: item_name = self.ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: print "Too recent event: %s" % item_name continue process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: print "Unknown id: %s" % id
Add comment to clarify constructor access
package model.transform.tasks; import model.transform.base.ImageTransformTask; public class StoreOptions extends ImageTransformTask { // Constructor left public because this task can be used with default options public StoreOptions() { super("store"); } public static class Builder { private StoreOptions storeOptions; public Builder() { this.storeOptions = new StoreOptions(); } public Builder filename(String filename) { storeOptions.addOption("filename", filename); return this; } public Builder location(String location) { storeOptions.addOption("location", location); return this; } public Builder path(String path) { storeOptions.addOption("path", path); return this; } public Builder container(String container) { storeOptions.addOption("container", container); return this; } public Builder region(String region) { storeOptions.addOption("region", region); return this; } public Builder access(String access) { storeOptions.addOption("access", access); return this; } public Builder base64Decode(boolean base64Decode) { storeOptions.addOption("base64decode", base64Decode); return this; } public StoreOptions build() { return storeOptions; } } }
package model.transform.tasks; import model.transform.base.ImageTransformTask; public class StoreOptions extends ImageTransformTask { public StoreOptions() { super("store"); } public static class Builder { private StoreOptions storeOptions; public Builder() { this.storeOptions = new StoreOptions(); } public Builder filename(String filename) { storeOptions.addOption("filename", filename); return this; } public Builder location(String location) { storeOptions.addOption("location", location); return this; } public Builder path(String path) { storeOptions.addOption("path", path); return this; } public Builder container(String container) { storeOptions.addOption("container", container); return this; } public Builder region(String region) { storeOptions.addOption("region", region); return this; } public Builder access(String access) { storeOptions.addOption("access", access); return this; } public Builder base64Decode(boolean base64Decode) { storeOptions.addOption("base64decode", base64Decode); return this; } public StoreOptions build() { return storeOptions; } } }
Add dutch translation for aggregation
(function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('nl', { aggregate: { label: 'items' }, groupPanel: { description: 'Sleep hier een kolomnaam heen om op te groeperen.' }, search: { placeholder: 'Zoeken...', showingItems: 'Getoonde items:', selectedItems: 'Geselecteerde items:', totalItems: 'Totaal aantal items:', size: 'Items per pagina:', first: 'Eerste pagina', next: 'Volgende pagina', previous: 'Vorige pagina', last: 'Laatste pagina' }, menu: { text: 'Kies kolommen:' }, sort: { ascending: 'Sorteer oplopend', descending: 'Sorteer aflopend', remove: 'Verwijder sortering' }, column: { hide: 'Verberg kolom' }, aggregation: { count: 'aantal rijen: ', sum: 'som: ', avg: 'gemiddelde: ', min: 'min: ', max: 'max: ' } }); return $delegate; }]); }]); })();
(function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('nl', { aggregate: { label: 'items' }, groupPanel: { description: 'Sleep hier een kolomnaam heen om op te groeperen.' }, search: { placeholder: 'Zoeken...', showingItems: 'Getoonde items:', selectedItems: 'Geselecteerde items:', totalItems: 'Totaal aantal items:', size: 'Items per pagina:', first: 'Eerste pagina', next: 'Volgende pagina', previous: 'Vorige pagina', last: 'Laatste pagina' }, menu: { text: 'Kies kolommen:' }, sort: { ascending: 'Sorteer oplopend', descending: 'Sorteer aflopend', remove: 'Verwijder sortering' }, column: { hide: 'Verberg kolom' }, aggregation: { count: 'total rows: ', sum: 'total: ', avg: 'avg: ', min: 'min: ', max: 'max: ' } }); return $delegate; }]); }]); })();
Add values reordering to survey component.
export default [ { key: 'multiple', ignore: true }, { type: 'datagrid', input: true, label: 'Questions', key: 'questions', tooltip: 'The questions you would like to ask in this survey question.', weight: 0, reorder: true, defaultValue: [{ label: '', value: '' }], components: [ { label: 'Label', key: 'label', input: true, type: 'textfield' }, { label: 'Value', key: 'value', input: true, type: 'textfield', allowCalculateOverride: true, calculateValue: { _camelCase: [{ var: 'row.label' }] } } ] }, { type: 'datagrid', input: true, label: 'Values', key: 'values', tooltip: 'The values that can be selected per question. Example: \'Satisfied\', \'Very Satisfied\', etc.', weight: 1, reorder: true, defaultValue: [{ label: '', value: '' }], components: [ { label: 'Label', key: 'label', input: true, type: 'textfield' }, { label: 'Value', key: 'value', input: true, type: 'textfield', allowCalculateOverride: true, calculateValue: { _camelCase: [{ var: 'row.label' }] } } ] } ];
export default [ { key: 'multiple', ignore: true }, { type: 'datagrid', input: true, label: 'Questions', key: 'questions', tooltip: 'The questions you would like to ask in this survey question.', weight: 0, defaultValue: [{ label: '', value: '' }], components: [ { label: 'Label', key: 'label', input: true, type: 'textfield' }, { label: 'Value', key: 'value', input: true, type: 'textfield', allowCalculateOverride: true, calculateValue: { _camelCase: [{ var: 'row.label' }] } } ] }, { type: 'datagrid', input: true, label: 'Values', key: 'values', tooltip: 'The values that can be selected per question. Example: \'Satisfied\', \'Very Satisfied\', etc.', weight: 1, defaultValue: [{ label: '', value: '' }], components: [ { label: 'Label', key: 'label', input: true, type: 'textfield' }, { label: 'Value', key: 'value', input: true, type: 'textfield', allowCalculateOverride: true, calculateValue: { _camelCase: [{ var: 'row.label' }] } } ] } ];
Comment out the failing Plan test
# -*- coding: utf-8 -*- # vim: ft=python:sw=4:ts=4:sts=4:et: import json from silver.models import Plan from django.test.client import Client from django.test import TestCase class PlansSpecificationTestCase(TestCase): def setUp(self): self.client = Client() def test_create_plan(self): assert True # response = self.client.put('/api/plans', json.dumps({ # 'name': 'Hydrogen', # 'interval': 'month', # 'interval_count': 1, # 'amount': 150, # 'currency': 'USD', # 'trial_period_days': 15, # 'metered_features': [ # { # 'name': '100k PageViews', # 'price_per_unit': 10, # 'included_units': 5 # } # ], # 'due_days': 10, # 'generate_after': 86400 # }), content_type='application/json') # plan = Plan.objects.filter(name='Hydrogen') # self.assertEqual(plan.count(), 1) # self.assertEqual(response.status_code, 201)
# -*- coding: utf-8 -*- # vim: ft=python:sw=4:ts=4:sts=4:et: import json from silver.models import Plan from django.test.client import Client from django.test import TestCase class PlansSpecificationTestCase(TestCase): def setUp(self): self.client = Client() def test_create_plan(self): response = self.client.put('/api/plans', json.dumps({ 'name': 'Hydrogen', 'interval': 'month', 'interval_count': 1, 'amount': 150, 'currency': 'USD', 'trial_period_days': 15, 'metered_features': [ { 'name': '100k PageViews', 'price_per_unit': 10, 'included_units': 5 } ], 'due_days': 10, 'generate_after': 86400 }), content_type='application/json') plan = Plan.objects.filter(name='Hydrogen') self.assertEqual(plan.count(), 1) self.assertEqual(response.status_code, 201)
Create method to send curl commands.
<?php /** * MIT License * Copyright (c) 2017 Electronic Student Services @ Appalachian State University * * See LICENSE file in root directory for copyright and distribution permissions. * * @author Matthew McNaney <[email protected]> * @license https://opensource.org/licenses/MIT */ namespace stories\Factory; use stories\Exception\ResourceNotFound; /** * * @author Matthew McNaney <[email protected]> */ abstract class BaseFactory extends \phpws2\ResourceFactory { abstract public function build(); public function load($id) { if (empty($id)) { throw new ResourceNotFound; } $resource = $this->build(); $resource->setId($id); if (!parent::loadByID($resource)) { throw new ResourceNotFound($id); } return $resource; } protected function walkingCase($name) { if (stripos($name, '_')) { return preg_replace_callback('/^(\w)(\w*)_(\w)(\w*)/', function($letter) { $str = strtoupper($letter[1]) . $letter[2] . strtoupper($letter[3]) . $letter[4]; return $str; }, $name); } else { return ucfirst($name); } } protected function sendCurl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch); return $result; } }
<?php /** * MIT License * Copyright (c) 2017 Electronic Student Services @ Appalachian State University * * See LICENSE file in root directory for copyright and distribution permissions. * * @author Matthew McNaney <[email protected]> * @license https://opensource.org/licenses/MIT */ namespace stories\Factory; use stories\Exception\ResourceNotFound; /** * * @author Matthew McNaney <[email protected]> */ abstract class BaseFactory extends \phpws2\ResourceFactory { abstract public function build(); public function load($id) { if (empty($id)) { throw new ResourceNotFound; } $resource = $this->build(); $resource->setId($id); if (!parent::loadByID($resource)) { throw new ResourceNotFound($id); } return $resource; } protected function walkingCase($name) { if (stripos($name, '_')) { return preg_replace_callback('/^(\w)(\w*)_(\w)(\w*)/', function($letter) { $str = strtoupper($letter[1]) . $letter[2] . strtoupper($letter[3]) . $letter[4]; return $str; }, $name); } else { return ucfirst($name); } } }
Fix missing group in configuration publishing
<?php namespace BotMan\BotMan; use BotMan\BotMan\Cache\LaravelCache; use BotMan\BotMan\Container\LaravelContainer; use BotMan\BotMan\Storages\Drivers\FileStorage; use Illuminate\Support\ServiceProvider; class BotManServiceProvider extends ServiceProvider { /** * Bootstrap any package services. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/../assets/config.php' => config_path('botman/config.php'), ], 'config'); } /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/../assets/config.php', 'botman.config'); $this->app->singleton('botman', function ($app) { $storage = new FileStorage(storage_path('botman')); $botman = BotManFactory::create( config('botman', []), new LaravelCache(), $app->make('request'), $storage ); $botman->setContainer(new LaravelContainer($this->app)); return $botman; }); } }
<?php namespace BotMan\BotMan; use BotMan\BotMan\Cache\LaravelCache; use BotMan\BotMan\Container\LaravelContainer; use BotMan\BotMan\Storages\Drivers\FileStorage; use Illuminate\Support\ServiceProvider; class BotManServiceProvider extends ServiceProvider { /** * Bootstrap any package services. * * @return void */ public function boot() { $this->publishes([ __DIR__ . '/../assets/config.php' => config_path('botman/config.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/../assets/config.php', 'botman.config'); $this->app->singleton('botman', function ($app) { $storage = new FileStorage(storage_path('botman')); $botman = BotManFactory::create( config('botman', []), new LaravelCache(), $app->make('request'), $storage ); $botman->setContainer(new LaravelContainer($this->app)); return $botman; }); } }
ENH: Improve the version information string
import os import subprocess from distutils.core import setup try: if os.path.exists(".git"): s = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISION = "unknown" except WindowsError: GIT_REVISION = "unknown" FULL_VERSION = '0.0.1-dev' if "dev" in FULL_VERSION: RELEASED = False VERSION = FULL_VERSION + '-' + GIT_REVISION[:7] else: RELEASED = True VERSION = FULL_VERSION def generate_version_py(filename): cnt = """\ # This file was autogenerated version = '%s' git_revision = '%s' """ cnt = cnt % (VERSION, GIT_REVISION) f = open(filename, "w") try: f.write(cnt) finally: f.close() setup( name='SAHGutils', version=VERSION, author='Scott Sinclair', author_email='[email protected]', packages=['sahgutils'], license='LICENSE.txt', description='Useful tools for data analysis and plots.', long_description=open('README.txt').read(), ) if __name__ == '__main__': generate_version_py("sahgutils/__dev_version.py")
import os import subprocess from distutils.core import setup try: if os.path.exists(".git"): s = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISION = "" except WindowsError: GIT_REVISION = "" FULL_VERSION = '0.0.1dev' if "dev" in FULL_VERSION: RELEASED = False VERSION = FULL_VERSION+GIT_REVISION[:7] else: RELEASED = True VERSION = FULL_VERSION def generate_version_py(filename): cnt = """\ # This file was autogenerated version = '%s' git_revision = '%s' """ cnt = cnt % (VERSION, GIT_REVISION) f = open(filename, "w") try: f.write(cnt) finally: f.close() setup( name='SAHGutils', version=VERSION, author='Scott Sinclair', author_email='[email protected]', packages=['sahgutils'], license='LICENSE.txt', description='Useful tools for data analysis and plots.', long_description=open('README.txt').read(), ) if __name__ == '__main__': generate_version_py("sahgutils/__dev_version.py")
Upgrade medialibrary db to v9
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMediaTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create(config('cortex.foundation.tables.media'), function (Blueprint $table) { $table->increments('id'); $table->morphs('model'); $table->uuid('uuid')->nullable(); $table->string('collection_name'); $table->string('name'); $table->string('file_name'); $table->string('mime_type')->nullable(); $table->string('disk'); $table->string('conversions_disk')->nullable(); $table->integer('size')->unsigned(); $table->json('manipulations'); $table->json('custom_properties'); $table->json('generated_conversions'); $table->json('responsive_images'); $table->integer('order_column')->unsigned()->nullable(); $table->nullableTimestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists(config('cortex.foundation.tables.media')); } }
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMediaTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create(config('cortex.foundation.tables.media'), function (Blueprint $table) { $table->increments('id'); $table->morphs('model'); $table->uuid('uuid')->nullable(); $table->string('collection_name'); $table->string('name'); $table->string('file_name'); $table->string('mime_type')->nullable(); $table->string('disk'); $table->string('conversions_disk')->nullable(); $table->integer('size')->unsigned(); $table->json('manipulations'); $table->json('custom_properties'); $table->json('responsive_images'); $table->integer('order_column')->unsigned()->nullable(); $table->nullableTimestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists(config('cortex.foundation.tables.media')); } }
Fix ld a,[hram] -> ldh a,[offset] optimizations
// Dependencies --------------------------------------------------------------- // ---------------------------------------------------------------------------- var Token = require('./parser/Lexer').Token; // Assembly Instruction Optimizer --------------------------------------------- // ---------------------------------------------------------------------------- function Optimizer(instr) { var opCode = instr.raw[0]; switch(opCode) { // ld a,[someLabel] -> ldh a,$XX case 0xFA: // Transform memory loads into high loads if argument is // in the range of 0xff00-0xffff if (instr.resolvedArg >= 0xff00 && instr.resolvedArg <= 0xffff) { instr.rewrite('ldh', 12, [0xF0], new Token('NUMBER', instr.resolvedArg & 0xff), true); } break; // ld [someLabel],a -> ldh $XX,a case 0xEA: // Transform memory loads into high loads if argument is // in the range of 0xff00-0xffff if (instr.resolvedArg >= 0xff00 && instr.resolvedArg <= 0xffff) { instr.rewrite('ldh', 12, [0xE0], new Token('NUMBER', instr.resolvedArg & 0xff), true); } break; // Extended instructions case 0xCB: break; } } // Exports -------------------------------------------------------------------- module.exports = Optimizer;
// Dependencies --------------------------------------------------------------- // ---------------------------------------------------------------------------- var Token = require('./parser/Lexer').Token; // Assembly Instruction Optimizer --------------------------------------------- // ---------------------------------------------------------------------------- function Optimizer(instr) { var opCode = instr.raw[0]; switch(opCode) { // ld a,[someLabel] -> ldh a,$XX case 0xFA: // Transform memory loads into high loads if argument is // in the range of 0xff00-0xffff if (instr.resolvedArg >= 0xff00 && instr.resolvedArg <= 0xff80) { //instr.rewrite('ldh', 12, [0xF0], new Token('NUMBER', instr.resolvedArg & 0xff), true); } break; // ld [someLabel],a -> ldh $XX,a case 0xEA: // Transform memory loads into high loads if argument is // in the range of 0xff00-0xffff if (instr.resolvedArg >= 0xff00 && instr.resolvedArg <= 0xff80) { //instr.rewrite('ldh', 12, [0xE0], new Token('NUMBER', instr.resolvedArg & 0xff), true); } break; // Extended instructions case 0xCB: break; } } // Exports -------------------------------------------------------------------- module.exports = Optimizer;
Add try/catch to improve error handling
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 F Dou<[email protected]> # See LICENSE for details. import bluetooth import os import logging import time from daemon import runner class RxCmdDaemon(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/RxCmdDaemon.pid' self.pidfile_timeout = 5 def run(self): while True: server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) port = 1 server_sock.bind(("",port)) server_sock.listen(1) client_sock,address = server_sock.accept() print "Accepted connection from ",address try: while True: data = client_sock.recv(1024) print "received [%s]" % data os.system(data) except Exception as e: logging.exception(e) while True: try: rxCmdDaemon = RxCmdDaemon() daemon_runner = runner.DaemonRunner(rxCmdDaemon) daemon_runner.do_action() except Exception as e: logging.exception(e)
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 F Dou<[email protected]> # See LICENSE for details. import bluetooth import os import logging import time from daemon import runner class RxCmdDaemon(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/RxCmdDaemon.pid' self.pidfile_timeout = 5 def run(self): while True: server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) port = 1 server_sock.bind(("",port)) server_sock.listen(1) client_sock,address = server_sock.accept() print "Accepted connection from ",address try: while True: data = client_sock.recv(1024) print "received [%s]" % data os.system(data) except Exception as e: logging.exception(e) rxCmdDaemon = RxCmdDaemon() daemon_runner = runner.DaemonRunner(rxCmdDaemon) daemon_runner.do_action()
Add example to function docstring
# -*- coding: utf-8 -*- ''' Salt proxy state .. versionadded:: 2015.8.2 State to deploy and run salt-proxy processes on a minion. Set up pillar data for your proxies per the documentation. Run the state as below ..code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True This state will configure the salt proxy settings within /etc/salt/proxy (if /etc/salt/proxy doesn't exists) and start the salt-proxy process (default true), if it isn't already running. ''' from __future__ import absolute_import import logging log = logging.getLogger(__name__) def configure_proxy(name, proxyname='p8000', start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started Example: ..code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True ''' ret = __salt__['salt_proxy.configure_proxy'](proxyname, start=start) ret.update({ 'name': name, 'comment': '{0} config messages'.format(name) }) return ret
# -*- coding: utf-8 -*- ''' Salt proxy state .. versionadded:: 2015.8.2 State to deploy and run salt-proxy processes on a minion. Set up pillar data for your proxies per the documentation. Run the state as below ..code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True This state will configure the salt proxy settings within /etc/salt/proxy (if /etc/salt/proxy doesn't exists) and start the salt-proxy process (default true), if it isn't already running. ''' from __future__ import absolute_import import logging log = logging.getLogger(__name__) def configure_proxy(name, proxyname='p8000', start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started ''' ret = __salt__['salt_proxy.configure_proxy'](proxyname, start=start) ret.update({ 'name': name, 'comment': '{0} config messages'.format(name) }) return ret
Remove default value for properties.
<?php namespace Retrinko\CottonTail\Message\Messages; use Retrinko\CottonTail\Exceptions\MessageException; use Retrinko\CottonTail\Message\MessageInterface; use Retrinko\CottonTail\Message\Payloads\RpcResponsePayload; class RpcResponseMessage extends BasicMessage { /** * @var array */ protected $requiredProperties = [MessageInterface::PROPERTY_TYPE, MessageInterface::PROPERTY_CORRELATION_ID, MessageInterface::PROPERTY_CONTENT_TYPE]; /** * @param string $body * @param array $properties */ public function __construct($body = '', array $properties) { // Override MessageInterface::PROPERTY_TYPE $properties[MessageInterface::PROPERTY_TYPE] = MessageInterface::TYPE_RPC_RESPONSE; parent::__construct($body, $properties); } /** * @return RpcResponsePayload */ public function getPayload() { $data = parent::getPayload(); return new RpcResponsePayload($data); } /** * @param array $properties * * @throws MessageException */ protected function checkRequiredPropertiesPresence(array $properties) { parent::checkRequiredPropertiesPresence($properties); if (MessageInterface::TYPE_RPC_RESPONSE != $properties[MessageInterface::PROPERTY_TYPE]) { throw MessageException::wrongMessageType($this->getType(), MessageInterface::TYPE_RPC_REQUEST); } } }
<?php namespace Retrinko\CottonTail\Message\Messages; use Retrinko\CottonTail\Exceptions\MessageException; use Retrinko\CottonTail\Message\MessageInterface; use Retrinko\CottonTail\Message\Payloads\RpcResponsePayload; class RpcResponseMessage extends BasicMessage { /** * @var array */ protected $requiredProperties = [MessageInterface::PROPERTY_TYPE, MessageInterface::PROPERTY_CORRELATION_ID, MessageInterface::PROPERTY_CONTENT_TYPE]; /** * @param string $body * @param array $properties */ public function __construct($body = '', array $properties = []) { // Override MessageInterface::PROPERTY_TYPE $properties[MessageInterface::PROPERTY_TYPE] = MessageInterface::TYPE_RPC_RESPONSE; parent::__construct($body, $properties); } /** * @return RpcResponsePayload */ public function getPayload() { $data = parent::getPayload(); return new RpcResponsePayload($data); } /** * @param array $properties * * @throws MessageException */ protected function checkRequiredPropertiesPresence(array $properties) { parent::checkRequiredPropertiesPresence($properties); if (MessageInterface::TYPE_RPC_RESPONSE != $properties[MessageInterface::PROPERTY_TYPE]) { throw MessageException::wrongMessageType($this->getType(), MessageInterface::TYPE_RPC_REQUEST); } } }
Fix TimeStampType to use convert method
from __future__ import absolute_import import datetime from time import mktime try: from dateutil.tz import tzutc, tzlocal except ImportError: raise ImportError( 'Using the datetime fields requires the dateutil library. ' 'You can obtain dateutil from http://labix.org/python-dateutil' ) from .base import DateTimeType class TimeStampType(DateTimeType): """Variant of a datetime field that saves itself as a unix timestamp (int) instead of a ISO-8601 string. """ def convert(self, value): """Will try to parse the value as a timestamp. If that fails it will fallback to DateTimeType's value parsing. A datetime may be used (and is encouraged). """ if not value: return try: value = float(value) return TimeStampType.timestamp_to_date(value) except (TypeError, ValueError): pass return super(TimeStampType, self).convert(value) @classmethod def timestamp_to_date(cls, value): return datetime.datetime.fromtimestamp(value, tz=tzutc()) @classmethod def date_to_timestamp(cls, value): if value.tzinfo is None: value = value.replace(tzinfo=tzlocal()) return int(round(mktime(value.astimezone(tzutc()).timetuple()))) def to_primitive(self, value): v = TimeStampType.date_to_timestamp(value) return v
from __future__ import absolute_import import datetime from time import mktime try: from dateutil.tz import tzutc, tzlocal except ImportError: raise ImportError( 'Using the datetime fields requires the dateutil library. ' 'You can obtain dateutil from http://labix.org/python-dateutil' ) from .base import DateTimeType class TimeStampType(DateTimeType): """Variant of a datetime field that saves itself as a unix timestamp (int) instead of a ISO-8601 string. """ def __set__(self, instance, value): """Will try to parse the value as a timestamp. If that fails it will fallback to DateTimeType's value parsing. A datetime may be used (and is encouraged). """ if not value: return try: value = TimeStampType.timestamp_to_date(value) except TypeError: pass super(TimeStampType, self).__set__(instance, value) @classmethod def timestamp_to_date(cls, value): return datetime.datetime.fromtimestamp(value, tz=tzutc()) @classmethod def date_to_timestamp(cls, value): if value.tzinfo is None: value = value.replace(tzinfo=tzlocal()) return int(round(mktime(value.astimezone(tzutc()).timetuple()))) def to_primitive(self, value): v = TimeStampType.date_to_timestamp(value) return v
Declare that our SQL functions just read data
<?php use Phinx\Migration\AbstractMigration; use Phinx\Db\Adapter\MysqlAdapter; class InitialFunctions extends AbstractMigration { public function up() { $query= <<<EOF CREATE FUNCTION ROUND_TO_EVEN(val DECIMAL(32,16), places INT) RETURNS DECIMAL(32,16) DETERMINISTIC READS SQL DATA BEGIN RETURN IF(ABS(val - TRUNCATE(val, places)) * POWER(10, places + 1) = 5 AND NOT CONVERT(TRUNCATE(ABS(val) * POWER(10, places), 0), UNSIGNED) % 2 = 1, TRUNCATE(val, places), ROUND(val, places)); END EOF; $this->execute($query); $query= <<<EOF CREATE FUNCTION SALE_PRICE(retail_price DECIMAL(9,2), type CHAR(32), discount DECIMAL(9,2)) RETURNS DECIMAL(9,2) DETERMINISTIC READS SQL DATA BEGIN RETURN IF(type IS NOT NULL AND type != '', CASE type WHEN 'percentage' THEN CAST(ROUND_TO_EVEN(retail_price * ((100 - discount) / 100), 2) AS DECIMAL(9,2)) WHEN 'relative' THEN (retail_price - discount) WHEN 'fixed' THEN (discount) END, retail_price); END EOF; $this->execute($query); } }
<?php use Phinx\Migration\AbstractMigration; use Phinx\Db\Adapter\MysqlAdapter; class InitialFunctions extends AbstractMigration { public function up() { $query= <<<EOF CREATE FUNCTION ROUND_TO_EVEN(val DECIMAL(32,16), places INT) RETURNS DECIMAL(32,16) DETERMINISTIC BEGIN RETURN IF(ABS(val - TRUNCATE(val, places)) * POWER(10, places + 1) = 5 AND NOT CONVERT(TRUNCATE(ABS(val) * POWER(10, places), 0), UNSIGNED) % 2 = 1, TRUNCATE(val, places), ROUND(val, places)); END EOF; $this->execute($query); $query= <<<EOF CREATE FUNCTION SALE_PRICE(retail_price DECIMAL(9,2), type CHAR(32), discount DECIMAL(9,2)) RETURNS DECIMAL(9,2) DETERMINISTIC BEGIN RETURN IF(type IS NOT NULL AND type != '', CASE type WHEN 'percentage' THEN CAST(ROUND_TO_EVEN(retail_price * ((100 - discount) / 100), 2) AS DECIMAL(9,2)) WHEN 'relative' THEN (retail_price - discount) WHEN 'fixed' THEN (discount) END, retail_price); END EOF; $this->execute($query); } }
Return exception details when failing to load link
#!/usr/bin/env python from __future__ import division import requests import json import sys from requests.exceptions import SSLError, InvalidSchema, ConnectionError def get_link_status_code(link): headers = {'User-agent':'Mozilla/5.0'} try: r = requests.head(link, headers=headers, allow_redirects=True) return r.status_code except (Exception) as e: return '%s: %s' % (type(e).__name__, str(e)) def is_valid_link(status_code): if status_code == 200: return True else: return False def process_links(links): bad_links = 0 try: for link in links: status_code = get_link_status_code(link['href']) if not is_valid_link(status_code): print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href']) bad_links += 1 except KeyboardInterrupt: pass linkrot = int(bad_links/len(links)*100) print '\n%s%% linkrot\n' % linkrot def process_bookmarks_file(filename): with open(filename) as f: bookmarks = json.load(f) process_links(bookmarks) if __name__ == '__main__': if len(sys.argv) != 2: print 'Usage: pinboard_linkrot.py <bookmarks.json>' exit(1) process_bookmarks_file(sys.argv[1])
#!/usr/bin/env python from __future__ import division import requests import json import sys from requests.exceptions import SSLError, InvalidSchema, ConnectionError def get_link_status_code(link): headers = {'User-agent':'Mozilla/5.0'} try: r = requests.head(link, headers=headers, allow_redirects=True) return r.status_code except (SSLError, InvalidSchema, ConnectionError): return 409 def is_valid_link(status_code): if status_code == 200: return True else: return False def process_links(links): bad_links = 0 try: for link in links: status_code = get_link_status_code(link['href']) if not is_valid_link(status_code): print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href']) bad_links += 1 except KeyboardInterrupt: pass linkrot = int(bad_links/len(links)*100) print '\n%s%% linkrot\n' % linkrot def process_bookmarks_file(filename): with open(filename) as f: bookmarks = json.load(f) process_links(bookmarks) if __name__ == '__main__': if len(sys.argv) != 2: print 'Usage: pinboard_linkrot.py <bookmarks.json>' exit(1) process_bookmarks_file(sys.argv[1])
Fix not being able to disable TokenManager integration
package com.elmakers.mine.bukkit.integration; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import me.realized.tokenmanager.api.TokenManager; public class TokenManagerController { private final TokenManager tokenManager; private final MageController controller; private boolean enabled; public TokenManagerController(MageController controller, Plugin tokenManagerPlugin) { this.controller = controller; tokenManager = tokenManagerPlugin instanceof TokenManager ? (TokenManager)tokenManagerPlugin : null; } public void load(ConfigurationSection configuration) { enabled = configuration.getBoolean("enabled", true); String statusString; if (!enabled) { statusString = " but is disabled in Magic's configs"; } else if (tokenManager == null) { statusString = " but integration failed"; } else { statusString = ", registering tokens currency"; } controller.getLogger().info("TokenManager found" + statusString); } public void register(ConfigurationSection currencyConfiguration) { if (enabled && tokenManager != null) { ConfigurationSection configuration = currencyConfiguration.getConfigurationSection("tokens"); if (configuration == null) { configuration = ConfigurationUtils.newConfigurationSection(); } controller.register(new TokenManagerCurrency(controller, tokenManager, configuration)); } } }
package com.elmakers.mine.bukkit.integration; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import me.realized.tokenmanager.api.TokenManager; public class TokenManagerController { private final TokenManager tokenManager; private final MageController controller; private boolean enabled; public TokenManagerController(MageController controller, Plugin tokenManagerPlugin) { this.controller = controller; tokenManager = tokenManagerPlugin instanceof TokenManager ? (TokenManager)tokenManagerPlugin : null; } public void load(ConfigurationSection configuration) { enabled = configuration.getBoolean("token_manager.enabled", true); String statusString; if (!enabled) { statusString = " but is disabled in Magic's configs"; } else if (tokenManager == null) { statusString = " but integration failed"; } else { statusString = ", registering tokens currency"; } controller.getLogger().info("TokenManager found" + statusString); } public void register(ConfigurationSection currencyConfiguration) { if (enabled && tokenManager != null) { ConfigurationSection configuration = currencyConfiguration.getConfigurationSection("tokens"); if (configuration == null) { configuration = ConfigurationUtils.newConfigurationSection(); } controller.register(new TokenManagerCurrency(controller, tokenManager, configuration)); } } }
Add documentation Clean duplicate code remove unused code
import os import unittest from gateway.utils.resourcelocator import ResourceLocator from unittest import TestLoader TEST_PATH = "tests" verbosity = 1 test_loader = unittest.defaultTestLoader def find_test_modules(test_modules=None): test_locator = ResourceLocator.get_locator(TEST_PATH) test_suite = test_loader.discover(test_locator.ROOT_PATH) return test_suite def run_tests(test_classes=None): """ run_tests - runs a test suite with specified paramters :param test_classes: list of tests classnames to only test :return int: -1 for failure or 0 for success """ test_runner = unittest.TextTestRunner(verbosity=verbosity) if test_classes: suite = load_test_from_classes(test_classes) if not suite.countTestCases(): return -1 else: test_runner.run(suite) return 0 tests = find_test_modules(test_modules) test_runner.run(tests) return 0 def load_test_from_classes(class_names): """ load_test_from_classes - returns a suite with specified class_names :param class_names: list of tests classnames to add to the suite """ test_suite = find_test_modules() temp_ts = unittest.TestSuite() for test in test_suite: suite = test.__dict__["_tests"] if len(suite): for case in suite: if case.__dict__["_tests"][0].__class__.__name__ in class_names: temp_ts.addTest(case) return temp_ts
import os import unittest from gateway.utils.resourcelocator import ResourceLocator from unittest import TestLoader TEST_PATH = "tests" verbosity = 1 test_loader = unittest.defaultTestLoader def find_test_modules(test_modules=None): test_locator = ResourceLocator.get_locator(TEST_PATH) test_suite = test_loader.discover(test_locator.ROOT_PATH) return test_suite def run_tests(test_classes=None): test_runner = unittest.TextTestRunner(verbosity=verbosity) if test_classes: suite = load_test_from_classes(test_classes) if not suite.countTestCases(): return -1 else: test_runner.run(suite) return 0 tests = find_test_modules(test_modules) test_runner.run(tests) return 0 def load_test_from_classes(class_names): test_locator = ResourceLocator.get_locator(TEST_PATH) test_suite = test_loader.discover(test_locator.ROOT_PATH) temp_ts = unittest.TestSuite() for test in test_suite: suite = test.__dict__["_tests"] if len(suite): for case in suite: if case.__dict__["_tests"][0].__class__.__name__ in class_names: temp_ts.addTest(case) return temp_ts def load_module_test_case(module_name): return test_loader.loadTestsFromName(module_name)
Revert "Do not display the start time of an event on the RSVP confirmation view" This reverts commit 79f86048c086e8a3928decfc27e7ac5af95e4f28. Fixes #1386.
<!DOCTYPE html> <html lang="en"> <head> <title>Event RSVP | MyRoboJackets</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{{ mix('/css/app.css') }}" rel="stylesheet"> <style type="text/css"> b { font-weight: bold; !important } </style> @include('favicon') </head> <body id="confirmation"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <img class="mt-2 px-5 img-fluid" src="{{ asset('img/recruiting_form_header.svg') }}"> <hr class="my-4"> </div> </div> <div class="row justify-content-center"> <div class="col-8" style="text-align:center"> <h1 class="display-4">You're all set!</h1> <p class="lead"> We can't wait to see you at <b>{{ $event->name }}</b>.<br/> @isset($event['location']) <b>Location: </b> {{ $event->location }}<br/> @endisset @isset($event['start_time']) <b>Date: </b> {{ date("l, F jS, Y \a\\t h:i A" ,strtotime($event->start_time)) }}<br/> @endisset @if($event['cost'] != 0) <b>Cost: </b> ${{ $event->cost }} @endif </p> </div> </div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>Event RSVP | MyRoboJackets</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{{ mix('/css/app.css') }}" rel="stylesheet"> <style type="text/css"> b { font-weight: bold; !important } </style> @include('favicon') </head> <body id="confirmation"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <img class="mt-2 px-5 img-fluid" src="{{ asset('img/recruiting_form_header.svg') }}"> <hr class="my-4"> </div> </div> <div class="row justify-content-center"> <div class="col-8" style="text-align:center"> <h1 class="display-4">You're all set!</h1> <p class="lead"> We can't wait to see you at <b>{{ $event->name }}</b>.<br/> @isset($event['location']) <b>Location: </b> {{ $event->location }}<br/> @endisset @if($event['cost'] != 0) <b>Cost: </b> ${{ $event->cost }} @endif </p> </div> </div> </div> </body> </html>
Add unmigratedDocumentQuery to test migration
import { Comments } from '../../lib/collections/comments' import { registerMigration, migrateDocuments } from './migrationUtils'; registerMigration({ name: "testCommentMigration", idempotent: true, action: async () => { await migrateDocuments({ description: "Checking how long migrating a lot of comments takes", collection: Comments, batchSize: 1000, unmigratedDocumentQuery: { schemaVersion: {$lt: 1} }, migrate: async (documents) => { const updates = documents.map(comment => { return { updateOne: { filter: {_id: comment._id}, update: { $set: { testContents: { originalContents: { data: "htmlReference" }, html: "htmlReference", version: "1.0.0", userId: "userIdReference", editedAt: "postedAtReference" } }, schemaVersion: 1 } } } }) await Comments.rawCollection().bulkWrite( updates, { ordered: false } ); } }) }, });
import { Comments } from '../../lib/collections/comments' import { registerMigration, migrateDocuments } from './migrationUtils'; registerMigration({ name: "testCommentMigration", idempotent: true, action: async () => { await migrateDocuments({ description: "Checking how long migrating a lot of comments takes", collection: Comments, batchSize: 1000, unmigratedDocumentQuery: {}, migrate: async (documents) => { const updates = documents.map(comment => { return { updateOne: { filter: {_id: comment._id}, update: { $set: { testContents: { originalContents: { data: "htmlReference" }, html: "htmlReference", version: "1.0.0", userId: "userIdReference", editedAt: "postedAtReference" } } } } } }) await Comments.rawCollection().bulkWrite( updates, { ordered: false } ); } }) }, });
Remove hard dependency on typeguard
import os from setuptools import find_packages, setup rootpath = os.path.abspath(os.path.dirname(__file__)) # Extract version def extract_version(module='kyokai'): version = None fname = os.path.join(rootpath, module, 'util.py') with open(fname) as f: for line in f: if line.startswith('VERSION'): _, version = line.split('=') version = version.strip()[1:-1] # Remove quotation characters. break return version setup( name='Kyokai', version=extract_version(), packages=find_packages(), url='https://mirai.veriny.tf', license='MIT', author='Isaac Dickinson', author_email='[email protected]', description='A fast, asynchronous web framework for Python 3.5+', classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.5", "Topic :: Internet", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Application Frameworks" ], install_requires=[ "http-parser>=0.8.3", "PyYAML>=3.11", "python-magic", 'typeguard>=1.2.1', 'asphalt' ] )
import os from setuptools import find_packages, setup rootpath = os.path.abspath(os.path.dirname(__file__)) # Extract version def extract_version(module='kyokai'): version = None fname = os.path.join(rootpath, module, 'util.py') with open(fname) as f: for line in f: if line.startswith('VERSION'): _, version = line.split('=') version = version.strip()[1:-1] # Remove quotation characters. break return version setup( name='Kyokai', version=extract_version(), packages=find_packages(), url='https://mirai.veriny.tf', license='MIT', author='Isaac Dickinson', author_email='[email protected]', description='A fast, asynchronous web framework for Python 3.5+', classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.5", "Topic :: Internet", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Application Frameworks" ], install_requires=[ "http-parser>=0.8.3", "uvloop>=0.4.15", "PyYAML>=3.11", "python-magic", 'typeguard', 'asphalt' ] )
Remove slice constraint on fetch
const TANDEM_MONGO_HOST = process.env.TANDEM_MONGO_HOST; const mongo = require('mongodb'); const bluebird = require('bluebird'); const mongoBluebird = require('mongodb-bluebird'); const async = require('async'); const mongoCollection = 'newnews'; module.exports = function(sentimentCallback) { mongoBluebird.connect(TANDEM_MONGO_HOST).then( function(db) { return db.collection(mongoCollection).find() .then(function(rawArticleBatch) { var articles = rawArticleBatch; // query mongo and drop specifically these 20 async.each(articles, function(article, doneCallback) { db.collection(mongoCollection).remove(article) .then(function() { doneCallback(); }); }, function() { sentimentCallback(articles); // close the mongo connection when finished db.close(); } ); }) .catch(function(err) { console.log("An error occured in mongoFetch", err); }); }); }
const TANDEM_MONGO_HOST = process.env.TANDEM_MONGO_HOST; const mongo = require('mongodb'); const bluebird = require('bluebird'); const mongoBluebird = require('mongodb-bluebird'); const async = require('async'); const mongoCollection = 'newnews'; module.exports = function(sentimentCallback) { mongoBluebird.connect(TANDEM_MONGO_HOST).then( function(db) { return db.collection(mongoCollection).find() .then(function(rawArticleBatch) { // only send thru the first 20 articles each hour: // 1000 requests/per day // each article uses 4 queries (split between 2 api keys, = 500 requests/day) // 20 per hour = 480 requests per day var articles = rawArticleBatch.slice(0,20); // query mongo and drop specifically these 20 async.each(articles, function(article, doneCallback) { db.collection(mongoCollection).remove(article) .then(function() { doneCallback(); }); }, function() { sentimentCallback(articles); // close the mongo connection when finished db.close(); } ); }) .catch(function(err) { console.log("An error occured in mongoFetch", err); }); }); }
Fix a bug where the post submit autoform hook wasn't called
AutoForm.hooks({ submitPostForm: { before: { method: function(doc) { this.template.$('button[type=submit]').addClass('loading'); var post = doc; // ------------------------------ Checks ------------------------------ // if (!Meteor.user()) { Messages.flash(i18n.t('you_must_be_logged_in'), 'error'); return false; } // ------------------------------ Callbacks ------------------------------ // // run all post submit client callbacks on properties object successively post = postSubmitClientCallbacks.reduce(function(result, currentFunction) { return currentFunction(result); }, post); return post; } }, onSuccess: function(operation, post) { this.template.$('button[type=submit]').removeClass('loading'); trackEvent("new post", {'postId': post._id}); Router.go('post_page', {_id: post._id}); if (post.status === STATUS_PENDING) { Messages.flash(i18n.t('thanks_your_post_is_awaiting_approval'), 'success'); } }, onError: function(operation, error) { this.template.$('button[type=submit]').removeClass('loading'); Messages.flash(error.message.split('|')[0], 'error'); // workaround because error.details returns undefined Messages.clearSeen(); // $(e.target).removeClass('disabled'); if (error.error == 603) { var dupePostId = error.reason.split('|')[1]; Router.go('post_page', {_id: dupePostId}); } } } });
AutoForm.hooks({ submitPostForm: { before: { submitPost: function(doc) { this.template.$('button[type=submit]').addClass('loading'); var post = doc; // ------------------------------ Checks ------------------------------ // if (!Meteor.user()) { Messages.flash(i18n.t('you_must_be_logged_in'), 'error'); return false; } // ------------------------------ Callbacks ------------------------------ // // run all post submit client callbacks on properties object successively post = postSubmitClientCallbacks.reduce(function(result, currentFunction) { return currentFunction(result); }, post); return post; } }, onSuccess: function(operation, post) { this.template.$('button[type=submit]').removeClass('loading'); trackEvent("new post", {'postId': post._id}); Router.go('post_page', {_id: post._id}); if (post.status === STATUS_PENDING) { Messages.flash(i18n.t('thanks_your_post_is_awaiting_approval'), 'success'); } }, onError: function(operation, error) { this.template.$('button[type=submit]').removeClass('loading'); Messages.flash(error.message.split('|')[0], 'error'); // workaround because error.details returns undefined Messages.clearSeen(); // $(e.target).removeClass('disabled'); if (error.error == 603) { var dupePostId = error.reason.split('|')[1]; Router.go('post_page', {_id: dupePostId}); } } } });
Fix that makes the media uploads work correctly.
from django.conf.urls.defaults import patterns, url, include from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', # Webserver urls url(r'^', include('webserver.home.urls')), url(r'^', include('webserver.profiles.urls')), url(r'^', include('webserver.codemanagement.urls')), # Competition url(r'^', include('competition.urls')), # Django AllAuth url(r'^accounts/', include('allauth.urls')), # Zinnia Blog url(r'^weblog/', include('zinnia.urls')), url(r'^comments/', include('django.contrib.comments.urls')), # Django Admin url(r'^admin/', include(admin.site.urls)), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin_tools/', include('admin_tools.urls')), ) if settings.DEBUG: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT,'show_indexes':True}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ) # Flat pages urlpatterns += patterns( 'django.contrib.flatpages.views', url(r'^(?P<url>.*)$', 'flatpage'), )
from django.conf.urls.defaults import patterns, url, include from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', # Webserver urls url(r'^', include('webserver.home.urls')), url(r'^', include('webserver.profiles.urls')), url(r'^', include('webserver.codemanagement.urls')), # Competition url(r'^', include('competition.urls')), # Django AllAuth url(r'^accounts/', include('allauth.urls')), # Zinnia Blog url(r'^weblog/', include('zinnia.urls')), url(r'^comments/', include('django.contrib.comments.urls')), # Django Admin url(r'^admin/', include(admin.site.urls)), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin_tools/', include('admin_tools.urls')), ) # Flat pages urlpatterns += patterns( 'django.contrib.flatpages.views', url(r'^(?P<url>.*)$', 'flatpage'), ) if settings.DEBUG: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
Add Payment and Image providers by default Also, reordered default providers for easier maintenance
<?php namespace Faker; class Factory { const DEFAULT_LOCALE = 'en_US'; protected static $defaultProviders = array('Address', 'Color', 'Company', 'DateTime', 'File', 'Image', 'Internet', 'Lorem', 'Miscellaneous', 'Payment', 'Person', 'PhoneNumber', 'UserAgent', 'Uuid'); public static function create($locale = self::DEFAULT_LOCALE) { $generator = new Generator(); foreach (static::$defaultProviders as $provider) { $providerClassName = self::getProviderClassname($provider, $locale); $generator->addProvider(new $providerClassName($generator)); } return $generator; } protected static function getProviderClassname($provider, $locale = '') { if ($providerClass = self::findProviderClassname($provider, $locale)) { return $providerClass; } // fallback to default locale if ($providerClass = self::findProviderClassname($provider, static::DEFAULT_LOCALE)) { return $providerClass; } // fallback to no locale $providerClass = self::findProviderClassname($provider); if (class_exists($providerClass)) { return $providerClass; } throw new \InvalidArgumentException(sprintf('Unable to find provider "%s" with locale "%s"', $provider, $locale)); } protected static function findProviderClassname($provider, $locale = '') { $providerClass = 'Faker\\' . ($locale ? sprintf('Provider\%s\%s', $locale, $provider) : sprintf('Provider\%s', $provider)); if (class_exists($providerClass, true)) { return $providerClass; } } }
<?php namespace Faker; class Factory { const DEFAULT_LOCALE = 'en_US'; protected static $defaultProviders = array('Person', 'Address', 'PhoneNumber', 'Company', 'Lorem', 'Internet', 'DateTime', 'Miscellaneous', 'UserAgent', 'Uuid', 'File', 'Color'); public static function create($locale = self::DEFAULT_LOCALE) { $generator = new Generator(); foreach (static::$defaultProviders as $provider) { $providerClassName = self::getProviderClassname($provider, $locale); $generator->addProvider(new $providerClassName($generator)); } return $generator; } protected static function getProviderClassname($provider, $locale = '') { if ($providerClass = self::findProviderClassname($provider, $locale)) { return $providerClass; } // fallback to default locale if ($providerClass = self::findProviderClassname($provider, static::DEFAULT_LOCALE)) { return $providerClass; } // fallback to no locale $providerClass = self::findProviderClassname($provider); if (class_exists($providerClass)) { return $providerClass; } throw new \InvalidArgumentException(sprintf('Unable to find provider "%s" with locale "%s"', $provider, $locale)); } protected static function findProviderClassname($provider, $locale = '') { $providerClass = 'Faker\\' . ($locale ? sprintf('Provider\%s\%s', $locale, $provider) : sprintf('Provider\%s', $provider)); if (class_exists($providerClass, true)) { return $providerClass; } } }
Add translatable behavior by stof
<?php namespace Application\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; /** * @Route("/article") */ class ArticleController extends Controller { /** * @Route("/item/{id}", name="article.item") * @Template() */ public function itemAction($id) { $item = $this->getDoctrine() ->getManager() ->getRepository('\Application\MainBundle\Entity\Article') ->findOneBy(['id' => $id]); return [ 'item' => $item, ]; } /** * @Route("/list", name="article.list") * @Template() */ public function listAction(Request $request) { $em = $this->getDoctrine()->getManager(); $qb = $em->createQueryBuilder(); $query = $qb ->from('\Application\MainBundle\Entity\Article', 'a') ->select('a') ->getQuery() ; $query->setHint( \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker' ); $paginator = $this->get('knp_paginator'); $page = $request->query->get('page', 1); $limit = $this->container->getParameter('pager_limit'); $items = $paginator->paginate($query, $page, $limit); return [ 'items' => $items, ]; } }
<?php namespace Application\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; /** * @Route("/article") */ class ArticleController extends Controller { /** * @Route("/item/{id}", name="article.item") * @Template() */ public function itemAction($id) { $item = $this->getDoctrine() ->getManager() ->getRepository('\Application\MainBundle\Entity\Article') ->findOneBy(['id' => $id]); return [ 'item' => $item, ]; } /** * @Route("/list", name="article.list") * @Template() */ public function listAction(Request $request) { $em = $this->getDoctrine()->getManager(); $qb = $em->createQueryBuilder(); $query = $qb ->from('\Application\MainBundle\Entity\Article', 'a') ->select('a') ->getQuery() ; $paginator = $this->get('knp_paginator'); $page = $request->query->get('page', 1); $limit = $this->container->getParameter('pager_limit'); $items = $paginator->paginate($query, $page, $limit); return [ 'items' => $items, ]; } }
Fix initial textarea row count
var cell_types = cell_types || {}; (function(){ cell_types["mathjs"] = { button_html: "+", on_create: function(element, content){ var extension_content = subqsa( element, ".extension-content" )[0]; element.classList.add("mathjs-cell-type"); var cell_state = "less-detail" element.classList.add("less-detail"); // Render content var ext_content = render("mathjs-cell-type"); extension_content.appendChild(ext_content); var textarea = subqsa(element, "textarea")[0]; // Set initial content textarea.value = content.value; // Adjust number of rows textarea.rows = content.value.split("\n").length; // Enable auto resizer (external lib.) autosize(textarea); // Enable toggle detail button var toggle_button = subqsa(element, ".toggle-detail")[0]; toggle_button.addEventListener("click", switch_state); // Manage cell state (more / less details) function switch_state(){ if(cell_state == "less-detail"){ cell_state = "more-detail"; element.classList.remove("less-detail"); element.classList.add("more-detail"); toggle_button.innerText = "Show less details"; } else { cell_state = "less-detail"; element.classList.add("less-detail"); element.classList.remove("more-detail"); toggle_button.innerText = "Show more details"; } } }, get_value: function(element){ var textarea = subqsa(element, "textarea")[0]; return textarea.value; } }; })();
var cell_types = cell_types || {}; (function(){ cell_types["mathjs"] = { button_html: "+", on_create: function(element, content){ var extension_content = subqsa( element, ".extension-content" )[0]; element.classList.add("mathjs-cell-type"); var cell_state = "less-detail" element.classList.add("less-detail"); // Render content var ext_content = render("mathjs-cell-type"); extension_content.appendChild(ext_content); var textarea = subqsa(element, "textarea")[0]; textarea.value = content.value; autosize(textarea); // Enable toggle detail button var toggle_button = subqsa(element, ".toggle-detail")[0]; toggle_button.addEventListener("click", switch_state); // Manage cell state (more / less details) function switch_state(){ if(cell_state == "less-detail"){ cell_state = "more-detail"; element.classList.remove("less-detail"); element.classList.add("more-detail"); toggle_button.innerText = "Show less details"; } else { cell_state = "less-detail"; element.classList.add("less-detail"); element.classList.remove("more-detail"); toggle_button.innerText = "Show more details"; } } }, get_value: function(element){ var textarea = subqsa(element, "textarea")[0]; return textarea.value; } }; })();
Set Default for Flash Theme in Storybook
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text, number, select } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; import { State, Store } from '@sambego/storybook-state'; import OptionsHelper from '../../utils/helpers/options-helper'; import notes from './documentation/notes.md'; import Info from './documentation/Info'; import Flash from './flash'; import Button from '../button'; const store = new Store({ open: false }); const dismissHandler = () => { store.set({ open: false }); action('cancel')(); }; const openHandler = () => { store.set({ open: true }); action('open')(); }; storiesOf('Flash', module) .addParameters({ info: { propTablesExclude: [Button, State] } }) .add('default', () => { const as = select('as', OptionsHelper.colors, OptionsHelper.colors[0]); const message = text('message', 'This is a flash message'); const timeout = number('timeout', 0); return ( <div> <Button onClick={ openHandler }>Open Flash</Button> <State store={ store }> <Flash open={ store.get('open') } as={ as } message={ message } timeout={ timeout >= 0 ? timeout : undefined } onDismiss={ dismissHandler } /> </State> </div> ); }, { info: { text: Info }, notes: { markdown: notes }, knobs: { escapeHTML: false } });
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text, number, select } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; import { State, Store } from '@sambego/storybook-state'; import OptionsHelper from '../../utils/helpers/options-helper'; import notes from './documentation/notes.md'; import Info from './documentation/Info'; import Flash from './flash'; import Button from '../button'; const store = new Store({ open: false }); const dismissHandler = () => { store.set({ open: false }); action('cancel')(); }; const openHandler = () => { store.set({ open: true }); action('open')(); }; storiesOf('Flash', module) .addParameters({ info: { propTablesExclude: [Button, State] } }) .add('default', () => { const as = select('as', OptionsHelper.colors); const message = text('message', 'This is a flash message'); const timeout = number('timeout', 0); return ( <div> <Button onClick={ openHandler }>Open Flash</Button> <State store={ store }> <Flash open={ store.get('open') } as={ as } message={ message } timeout={ timeout >= 0 ? timeout : undefined } onDismiss={ dismissHandler } /> </State> </div> ); }, { info: { text: Info }, notes: { markdown: notes }, knobs: { escapeHTML: false } });
Remove HTMLEditorField schema component definition, done in core now
<?php namespace DNADesign\Elemental\Models; use SilverStripe\Forms\FieldList; use SilverStripe\ORM\FieldType\DBField; class ElementContent extends BaseElement { private static $icon = 'font-icon-block-content'; private static $db = [ 'HTML' => 'HTMLText' ]; private static $table_name = 'ElementContent'; private static $singular_name = 'content block'; private static $plural_name = 'content blocks'; private static $description = 'HTML text block'; /** * Re-title the HTML field to Content * * {@inheritDoc} */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields ->fieldByName('Root.Main.HTML') ->setTitle(_t(__CLASS__ . '.ContentLabel', 'Content')); }); return parent::getCMSFields(); } public function getSummary() { return DBField::create_field('HTMLText', $this->HTML)->Summary(20); } protected function provideBlockSchema() { $blockSchema = parent::provideBlockSchema(); $blockSchema['content'] = $this->getSummary(); return $blockSchema; } public function getType() { return _t(__CLASS__ . '.BlockType', 'Content'); } }
<?php namespace DNADesign\Elemental\Models; use SilverStripe\Forms\FieldList; use SilverStripe\ORM\FieldType\DBField; class ElementContent extends BaseElement { private static $icon = 'font-icon-block-content'; private static $db = [ 'HTML' => 'HTMLText' ]; private static $table_name = 'ElementContent'; private static $singular_name = 'content block'; private static $plural_name = 'content blocks'; private static $description = 'HTML text block'; /** * Re-title the HTML field to Content * * {@inheritDoc} */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields ->fieldByName('Root.Main.HTML') ->setTitle(_t(__CLASS__ . '.ContentLabel', 'Content')) ->setSchemaComponent('HtmlEditorField'); }); return parent::getCMSFields(); } public function getSummary() { return DBField::create_field('HTMLText', $this->HTML)->Summary(20); } protected function provideBlockSchema() { $blockSchema = parent::provideBlockSchema(); $blockSchema['content'] = $this->getSummary(); return $blockSchema; } public function getType() { return _t(__CLASS__ . '.BlockType', 'Content'); } }
Remove pagination, its overkill here
<?php /** * Allows editing of site banner data "globally". */ class SiteBannerSiteConfigExtension extends DataExtension { public function updateCMSFields(FieldList $fields) { $fields->findOrMakeTab( 'Root.SiteBanner', _t('SiteBanner.TabTitle', 'Site Banners') ); $gridConfig = GridFieldConfig_RecordEditor::create(); $grid = GridField::create('SiteBanners', null, SiteBanner::get()) ->setConfig($gridConfig); $gridConfig->removeComponentsByType('GridFieldPaginator'); $gridConfig->removeComponentsByType('GridFieldPageCount'); if (class_exists('GridFieldSortableRows')) { $grid->getConfig()->addComponent(new GridFieldSortableRows('Sort')); } if (class_exists('Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm')) { $gridConfig->removeComponentsByType('GridFieldDetailForm'); $gridConfig->addComponent(new Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm()); } $fields->addFieldToTab( 'Root.SiteBanner', $grid ); } /** * Get all displayable site banners * * @return DataList */ public function getSiteBanners() { return SiteBanner::get()->filterByCallback(function ($banner) { return $banner->isActive(); }); } }
<?php /** * Allows editing of site banner data "globally". */ class SiteBannerSiteConfigExtension extends DataExtension { public function updateCMSFields(FieldList $fields) { $fields->findOrMakeTab( 'Root.SiteBanner', _t('SiteBanner.TabTitle', 'Site Banners') ); $gridConfig = GridFieldConfig_RecordEditor::create(); $grid = GridField::create('SiteBanners', null, SiteBanner::get()) ->setConfig($gridConfig); if (class_exists('GridFieldSortableRows')) { $grid->getConfig()->addComponent(new GridFieldSortableRows('Sort')); } if (class_exists('Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm')) { $gridConfig->removeComponentsByType('GridFieldDetailForm'); $gridConfig->addComponent(new Heyday\VersionedDataObjects\VersionedDataObjectDetailsForm()); } $fields->addFieldToTab( 'Root.SiteBanner', $grid ); } /** * Get all displayable site banners * * @return DataList */ public function getSiteBanners() { return SiteBanner::get()->filterByCallback(function ($banner) { return $banner->isActive(); }); } }
Add roles argument for createUser command.
# -*- coding: utf-8 *-* import logging import unittest from mongolog import MongoHandler try: from pymongo import MongoClient as Connection except ImportError: from pymongo import Connection class TestAuth(unittest.TestCase): def setUp(self): """ Create an empty database that could be used for logging """ self.db_name = '_mongolog_auth' self.collection_name = 'log' self.user_name = 'MyUsername' self.password = 'MySeCrEtPaSsWoRd' self.conn = Connection() self.db = self.conn[self.db_name] self.collection = self.db[self.collection_name] self.conn.drop_database(self.db_name) self.db.command( 'createUser', self.user_name, pwd=self.password, roles=["readWrite"] ) def tearDown(self): """ Drop used database """ self.conn.drop_database(self.db_name) def testAuthentication(self): """ Logging example with authentication """ log = logging.getLogger('authentication') log.addHandler(MongoHandler(self.collection_name, self.db_name, username=self.user_name, password=self.password)) log.error('test') message = self.collection.find_one({'levelname': 'ERROR', 'msg': 'test'}) self.assertEqual(message['msg'], 'test')
# -*- coding: utf-8 *-* import logging import unittest from mongolog import MongoHandler try: from pymongo import MongoClient as Connection except ImportError: from pymongo import Connection class TestAuth(unittest.TestCase): def setUp(self): """ Create an empty database that could be used for logging """ self.db_name = '_mongolog_auth' self.collection_name = 'log' self.user_name = 'MyUsername' self.password = 'MySeCrEtPaSsWoRd' self.conn = Connection() self.db = self.conn[self.db_name] self.collection = self.db[self.collection_name] self.conn.drop_database(self.db_name) self.db.command( 'createUser', self.user_name, pwd=self.password ) def tearDown(self): """ Drop used database """ self.conn.drop_database(self.db_name) def testAuthentication(self): """ Logging example with authentication """ log = logging.getLogger('authentication') log.addHandler(MongoHandler(self.collection_name, self.db_name, username=self.user_name, password=self.password)) log.error('test') message = self.collection.find_one({'levelname': 'ERROR', 'msg': 'test'}) self.assertEqual(message['msg'], 'test')
Add unidecode as a dependency
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', 'unidecode', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
import re from setuptools import setup init_py = open('wikipediabase/__init__.py').read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py)) metadata['doc'] = re.findall('"""(.+)"""', init_py)[0] setup( name='wikipediabase', version=metadata['version'], description=metadata['doc'], author=metadata['author'], author_email=metadata['email'], url=metadata['url'], packages=[ 'wikipediabase', 'wikipediabase.resolvers', 'wikipediabase.adhoc', 'tests', ], include_package_data=True, install_requires=[ 'edn_format', 'docopt', 'flake8 < 3.0.0', 'unittest2 < 1.0.0', 'overlay-parse', 'lxml', 'sqlitedict', 'requests', 'beautifulsoup4', 'redis', 'redis', 'hiredis', ], dependency_links=[ 'git+https://github.com/fakedrake/overlay_parse#egg=overlay-parse', ], tests_require=[ 'nose>=1.0', 'sqlitedict', ], entry_points={ 'console_scripts': [ 'wikipediabase = wikipediabase.cli:main', ], }, test_suite='nose.collector', license=open('LICENSE').read(), )
Add minify stage when not dev
var webpack = require('webpack'); module.exports = { entry: { main:'./src/frontend/components/App.jsx', admin: './src/frontend/components/admin/AdminDashboard.jsx', networkAdmin: './src/frontend/components/admin/NetworkAdminDashboard.jsx', }, output: { path: './public/javascript', filename: '[name].bundle.js' }, module: { loaders: [ { test: /\.css$/, loader: 'style!css' }, { test: /\.scss$/, loader: 'style!css!sass' }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react', 'stage-0'] } } ] }, plugins: process.env.NODE_ENV ? [ new webpack.optimize.UglifyJsPlugin({minimize: true}) ] : [] };
require('webpack'); module.exports = { entry: { main:'./src/frontend/components/App.jsx', admin: './src/frontend/components/admin/AdminDashboard.jsx', networkAdmin: './src/frontend/components/admin/NetworkAdminDashboard.jsx', }, output: { path: './public/javascript', filename: '[name].bundle.js' }, module: { loaders: [ { test: /\.css$/, loader: 'style!css' }, { test: /\.scss$/, loader: 'style!css!sass' }, { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react', 'stage-0'] } } ] }, plugins: [ ] };
Add lxml to list of install_requires This is literally the exact same thing as #19, but for some reason, that fix isn't included
from distutils.core import setup from setuptools import setup setup( name = 'spice_api', packages = ['spice_api'], # this must be the same as the name above version = '1.0.4', description = 'spice is a pure Python API that wraps around MALs Official API and makes it much better.', long_description = open('README.md').read(), license = 'MIT', author = 'Mehrab Hoque', author_email = '[email protected]', url = 'https://github.com/Utagai/spice', # use the URL to the github repo classifiers = [ 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords = ['spice', 'MyAnimeList', 'API'], # arbitrary keywords install_requires = [ 'requests', 'beautifulsoup4', 'lxml' ], )
from distutils.core import setup from setuptools import setup setup( name = 'spice_api', packages = ['spice_api'], # this must be the same as the name above version = '1.0.4', description = 'spice is a pure Python API that wraps around MALs Official API and makes it much better.', long_description = open('README.md').read(), license = 'MIT', author = 'Mehrab Hoque', author_email = '[email protected]', url = 'https://github.com/Utagai/spice', # use the URL to the github repo classifiers = [ 'Development Status :: 4 - Beta', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords = ['spice', 'MyAnimeList', 'API'], # arbitrary keywords install_requires = [ 'requests', 'beautifulsoup4' ], )
Stop validation error notification stack closes #3383 - Calls closePassive() if a new validation error is thrown to display only the latest validation error
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
Disable failing asserts due to parser generator bug
package org.spoofax.jsglr2.actions; import org.spoofax.jsglr2.characters.ICharacters; import org.spoofax.jsglr2.parsetable.IProduction; import org.spoofax.jsglr2.parsetable.ProductionType; public class Reduce extends Action implements IReduce { private final IProduction production; private final ProductionType productionType; private final int arity; public Reduce(ICharacters characters, IProduction production, ProductionType productionType, int arity) { super(characters); this.production = production; this.productionType = productionType; this.arity = arity; /* * NOTE: according to Eduardo, the type of the action and of the production should match for types REJECT / * PREFER / AVOID at least. There seems to be a bug in the parse table generator. If this bug is fixed the * asserts below should succeed (they are failing now). * * assert !(productionType == ProductionType.REJECT || productionType == ProductionType.PREFER || productionType * == ProductionType.AVOID) || productionType == production.productionType(); * * assert !(production.productionType() == ProductionType.REJECT || production.productionType() == * ProductionType.PREFER || production.productionType() == ProductionType.AVOID) || production.productionType() * == productionType; */ } public IProduction production() { return production; } public ProductionType productionType() { return productionType; } public int arity() { return arity; } }
package org.spoofax.jsglr2.actions; import org.spoofax.jsglr2.characters.ICharacters; import org.spoofax.jsglr2.parsetable.IProduction; import org.spoofax.jsglr2.parsetable.ProductionType; public class Reduce extends Action implements IReduce { private final IProduction production; private final ProductionType productionType; private final int arity; public Reduce(ICharacters characters, IProduction production, ProductionType productionType, int arity) { super(characters); this.production = production; this.productionType = productionType; this.arity = arity; /* * NOTE: according to Eduardo, the type of the action and of the production should match for types REJECT / * PREFER / AVOID at least. There seems to be a bug in the parse table generator. */ assert !(productionType == ProductionType.REJECT || productionType == ProductionType.PREFER || productionType == ProductionType.AVOID) || productionType == production.productionType(); assert !(production.productionType() == ProductionType.REJECT || production.productionType() == ProductionType.PREFER || production.productionType() == ProductionType.AVOID) || production.productionType() == productionType; } public IProduction production() { return production; } public ProductionType productionType() { return productionType; } public int arity() { return arity; } }
Clarify comment about Pyhton versions
""" Scheduler queues """ import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self).push(s) def pop(self): s = super(SerializableQueue, self).pop() if s: return deserialize(s) return SerializableQueue def _pickle_serialize(obj): try: return pickle.dumps(obj, protocol=2) # Python <= 3.4 raises pickle.PicklingError here while # 3.5 <= Python < 3.6 raises AttributeError and # Python >= 3.6 raises TypeError except (pickle.PicklingError, AttributeError, TypeError) as e: raise ValueError(str(e)) PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \ _pickle_serialize, pickle.loads) PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \ _pickle_serialize, pickle.loads) MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \ marshal.dumps, marshal.loads) MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \ marshal.dumps, marshal.loads) FifoMemoryQueue = queue.FifoMemoryQueue LifoMemoryQueue = queue.LifoMemoryQueue
""" Scheduler queues """ import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self).push(s) def pop(self): s = super(SerializableQueue, self).pop() if s: return deserialize(s) return SerializableQueue def _pickle_serialize(obj): try: return pickle.dumps(obj, protocol=2) # Python<=3.4 raises pickle.PicklingError here while # Python>=3.5 raises AttributeError and # Python>=3.6 raises TypeError except (pickle.PicklingError, AttributeError, TypeError) as e: raise ValueError(str(e)) PickleFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \ _pickle_serialize, pickle.loads) PickleLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \ _pickle_serialize, pickle.loads) MarshalFifoDiskQueue = _serializable_queue(queue.FifoDiskQueue, \ marshal.dumps, marshal.loads) MarshalLifoDiskQueue = _serializable_queue(queue.LifoDiskQueue, \ marshal.dumps, marshal.loads) FifoMemoryQueue = queue.FifoMemoryQueue LifoMemoryQueue = queue.LifoMemoryQueue
Add types to ImageProvider and RequiresData
import inspect import json from os.path import exists, join from pathlib import Path from typing import Any, Union from ..services import Services PathOrStr = Union[str,Path] def not_implemented(): frame_info = inspect.currentframe().f_back msg = '' if 'self' in frame_info.f_locals: self = frame_info.f_locals['self'] try: msg += self.__name__ + '#' # for static/class methods except AttributeError: msg += self.__class__.__name__ + '.' msg += frame_info.f_code.co_name + '()' return NotImplementedError(msg) class RequiresData: def __init__(self, data_dir: Path, services: Services) -> None: self.data_dir = data_dir self.services = services def has_required_data(self) -> bool: raise not_implemented() def obtain_data(self) -> bool: raise not_implemented() def data_dir_exists(self, name: PathOrStr) -> bool: return exists(self.data_dir_join(name)) def data_dir_join(self, name: PathOrStr) -> str: return join(self.data_dir, name) def save_json(self, name: PathOrStr, data: Any) -> bool: with open(self.data_dir_join(name), 'w') as fh: json.dump(data, fh, indent=4) return True def load_json(self, name: PathOrStr) -> Any: with open(self.data_dir_join(name)) as fh: return json.load(fh) class ImageProvider(RequiresData): def build_image(self) -> str: raise not_implemented()
import json import inspect from os.path import join, exists def not_implemented(): frame_info = inspect.currentframe().f_back msg = '' if 'self' in frame_info.f_locals: self = frame_info.f_locals['self'] try: msg += self.__name__ + '#' # for static/class methods except AttributeError: msg += self.__class__.__name__ + '.' msg += frame_info.f_code.co_name + '()' return NotImplementedError(msg) class RequiresData: def __init__(self, data_dir, services): self.data_dir = data_dir self.services = services def has_required_data(self): raise not_implemented() def obtain_data(self): raise not_implemented() def data_dir_exists(self, name): return exists(self.data_dir_join(name)) def data_dir_join(self, name): return join(self.data_dir, name) def save_json(self, name, data): with open(self.data_dir_join(name), 'w') as fh: json.dump(data, fh, indent=4) return True def load_json(self, name): with open(self.data_dir_join(name)) as fh: return json.load(fh) class ImageProvider(RequiresData): def build_image(self): raise not_implemented()
Fix indents for minimized JSON
# coding: utf-8 import abc from typing import Any from aiohttp import web from il2fb.ds.airbridge import json class RESTResponse(web.Response, abc.ABC): detail = None @property @abc.abstractmethod def status(self) -> int: """ Status must be explicilty defined by subclasses. """ def __init__( self, payload: dict=None, detail: Any=None, pretty: bool=False, content_type: str='application/json', charset: str='utf-8', **kwargs ): payload = payload if payload is not None else {} detail = detail if detail is not None else self.detail if detail: payload['detail'] = str(detail) indent = 2 if pretty else None text = json.dumps(payload, indent=indent) + '\n' kwargs.setdefault('status', self.status) super().__init__( text=text, charset=charset, content_type=content_type, **kwargs ) class RESTSuccess(RESTResponse): status = 200 class RESTBadRequest(RESTResponse): status = 400 detail = "Bad request" class RESTNotFound(RESTBadRequest): status = 404 detail = "Resource not found" class RESTInternalServerError(RESTResponse): status = 500 detail = ( "The server encountered an unexpected condition that prevented it " "from fulfilling the request" )
# coding: utf-8 import abc from typing import Any from aiohttp import web from il2fb.ds.airbridge import json class RESTResponse(web.Response, abc.ABC): detail = None @property @abc.abstractmethod def status(self) -> int: """ Status must be explicilty defined by subclasses. """ def __init__( self, payload: dict=None, detail: Any=None, pretty: bool=False, content_type: str='application/json', charset: str='utf-8', **kwargs ): payload = payload if payload is not None else {} detail = detail if detail is not None else self.detail if detail: payload['detail'] = str(detail) indent = 2 if pretty else 0 text = json.dumps(payload, indent=indent) + '\n' kwargs.setdefault('status', self.status) super().__init__( text=text, charset=charset, content_type=content_type, **kwargs ) class RESTSuccess(RESTResponse): status = 200 class RESTBadRequest(RESTResponse): status = 400 detail = "Bad request" class RESTNotFound(RESTBadRequest): status = 404 detail = "Resource not found" class RESTInternalServerError(RESTResponse): status = 500 detail = ( "The server encountered an unexpected condition that prevented it " "from fulfilling the request" )
Refactor: Adjust the production build parameter inorder to access all available routes
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'fireplace-app', environment: environment, baseURL: '/fireplace-app', locationType: 'auto', contentSecurityPolicy: {'img-src': "'self' " + "m.fmi.fi "}, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/fireplace-app/'; ENV.locationType = 'auto'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'fireplace-app', environment: environment, baseURL: '/fireplace-app', locationType: 'auto', contentSecurityPolicy: {'img-src': "'self' " + "m.fmi.fi "}, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/fireplace-app/'; } return ENV; };
Fix problem where Provider DoesNotExist. * Occurs on provider and providerlist endpoints. * Came to attention as a side effect of fixing ATMO-176. * Similar changes need to be made all over atmosphere. I'll create a ticket. modified: api/provider.py
""" atmosphere service provider rest api. """ from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from authentication.decorators import api_auth_token_required from core.models.group import Group from core.models.provider import Provider as CoreProvider from api import failureJSON from api.serializers import ProviderSerializer class ProviderList(APIView): """ List of active providers """ @api_auth_token_required def get(self, request): """ List all providers accessible by request user """ username = request.user.username group = Group.objects.get(name=username) try: providers = group.providers.filter(active=True, end_date=None).order_by('id') except CoreProvider.DoesNotExist: errorObj = failureJSON([{ 'code': 404, 'message': 'The provider does not exist.'}]) return Response(errorObj, status=status.HTTP_404_NOT_FOUND) serialized_data = ProviderSerializer(providers, many=True).data return Response(serialized_data) class Provider(APIView): """ Show single provider """ @api_auth_token_required def get(self, request, provider_id): """ return provider if accessible by request user """ username = request.user.username group = Group.objects.get(name=username) try: provider = group.providers.get(id=provider_id, active=True, end_date=None) except CoreProvider.DoesNotExist: errorObj = failureJSON([{ 'code': 404, 'message': 'The provider does not exist.'}]) return Response(errorObj, status=status.HTTP_404_NOT_FOUND) serialized_data = ProviderSerializer(provider).data return Response(serialized_data)
""" atmosphere service provider rest api. """ from rest_framework.views import APIView from rest_framework.response import Response from authentication.decorators import api_auth_token_required from core.models.group import Group from api.serializers import ProviderSerializer class ProviderList(APIView): """ List of active providers """ @api_auth_token_required def get(self, request): """ List all providers accessible by request user """ username = request.user.username group = Group.objects.get(name=username) providers = group.providers.filter(active=True, end_date=None).order_by('id') #providers = CoreProvider.objects.order_by('id') serialized_data = ProviderSerializer(providers, many=True).data return Response(serialized_data) class Provider(APIView): """ Show single provider """ @api_auth_token_required def get(self, request, provider_id): """ return provider if accessible by request user """ username = request.user.username group = Group.objects.get(name=username) provider = group.providers.get(id=provider_id, active=True, end_date=None) serialized_data = ProviderSerializer(provider).data return Response(serialized_data)
Include more information in file replicator exception.
<?php namespace Orbt\ResourceMirror\Resource; use Orbt\ResourceMirror\Exception\ReplicatorException; /** * Basic replicator implementation using file operations to replicate. */ class FileReplicator implements Replicator { /** * Base URL. * @var string */ protected $baseUrl; /** * Target directory. * @var string */ protected $directory; /** * Constructs a file replicator. */ public function __construct($baseUrl, $directory) { $this->baseUrl = rtrim($baseUrl, '/').'/'; $this->directory = rtrim($directory, '\\/').'/'; } /** * {@inheritdoc} */ public function replicate($resource) { $url = $this->baseUrl.$resource->getPath(); if (!$source = @fopen($url, 'rb')) { throw new ReplicatorException(sprintf('Cannot open URL "%s" for reading.', $url)); } $file = $this->directory.$resource->getPath(); @mkdir(dirname($file), 0777, true); if (!$target = @fopen($file, 'wb')) { fclose($source); throw new ReplicatorException(sprintf('Cannot open local file "%s" for writing.', $file)); } stream_copy_to_stream($source, $target); fclose($source); fclose($target); } }
<?php namespace Orbt\ResourceMirror\Resource; use Orbt\ResourceMirror\Exception\ReplicatorException; /** * Basic replicator implementation using file operations to replicate. */ class FileReplicator implements Replicator { /** * Base URL. * @var string */ protected $baseUrl; /** * Target directory. * @var string */ protected $directory; /** * Constructs a file replicator. */ public function __construct($baseUrl, $directory) { $this->baseUrl = rtrim($baseUrl, '/').'/'; $this->directory = rtrim($directory, '\\/').'/'; } /** * {@inheritdoc} */ public function replicate($resource) { $url = $this->baseUrl.$resource->getPath(); if (!$source = @fopen($url, 'rb')) { throw new ReplicatorException('Cannot open URL for reading.'); } $file = $this->directory.$resource->getPath(); @mkdir(dirname($file), 0777, true); if (!$target = @fopen($file, 'wb')) { fclose($source); throw new ReplicatorException('Cannot open local file for writing.'); } stream_copy_to_stream($source, $target); fclose($source); fclose($target); } }
Add Square to presentation map
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Payment extends Model { use SoftDeletes; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = ['method_presentation']; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = ['id']; /** * Get all of the owning payable models */ public function payable() { return $this->morphTo(); } /** * Get the User associated with the Payment model. */ public function user() { return $this->belongsTo('App\User', 'recorded_by'); } /** * Get the presentation-ready format of a Payment Method * * @return String */ public function getMethodPresentationAttribute() { $valueMap = array( 'cash' => 'Cash', 'squarecash' => 'Square Cash', 'check' => 'Check', 'swipe' => 'Swiped Card', 'square' => 'Square' ); $method = $this->method; if (array_key_exists($method, $valueMap)) { return $valueMap[$this->method]; } else { return null; } } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Payment extends Model { use SoftDeletes; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = ['method_presentation']; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = ['id']; /** * Get all of the owning payable models */ public function payable() { return $this->morphTo(); } /** * Get the User associated with the Payment model. */ public function user() { return $this->belongsTo('App\User', 'recorded_by'); } /** * Get the presentation-ready format of a Payment Method * * @return String */ public function getMethodPresentationAttribute() { $valueMap = array( 'cash' => 'Cash', 'squarecash' => 'Square Cash', 'check' => 'Check', 'swipe' => 'Swiped Card' ); $method = $this->method; if (array_key_exists($method, $valueMap)) { return $valueMap[$this->method]; } else { return null; } } }
Make sure content of po files is read in utf8
var through = require('through2'), gutil = require('gulp-util'), po = require('node-po'), PluginError = gutil.PluginError; module.exports = function () { function write (f, enc, cb){ if (f.isNull()) { this.push(file); return cb(); } if (f.isStream()) { this.emit('error', new PluginError('gulp-po-json', 'Streaming not supported')); return cb(); } var pofile = po.parse(f.contents.toString('utf-8')), res = {}, dic = {}, i, l; if (!pofile) { this.emit('error', new PluginError('gulp-po-json', 'Unable to parse file ' + f.path)); return cb(); } res.meta = pofile.headers; res.dic = dic; for (i = 0, l = pofile.items.length; i < l; i += 1) { res.dic[pofile.items[i].msgid] = pofile.items[i].msgstr[0]; } this.push(JSON.stringify(res)); cb(); } function end (cb) { cb(); } return through.obj(write, end); };
var through = require('through2'), gutil = require('gulp-util'), po = require('node-po'), PluginError = gutil.PluginError; module.exports = function () { function write (f, enc, cb){ if (f.isNull()) { this.push(file); return cb(); } if (f.isStream()) { this.emit('error', new PluginError('gulp-po-json', 'Streaming not supported')); return cb(); } var pofile = po.parse(f.contents.toString()), res = {}, dic = {}, i, l; if (!pofile) { this.emit('error', new PluginError('gulp-po-json', 'Unable to parse file ' + f.path)); return cb(); } res.meta = pofile.headers; res.dic = dic; for (i = 0, l = pofile.items.length; i < l; i += 1) { res.dic[pofile.items[i].msgid] = pofile.items[i].msgstr[0]; } this.push(JSON.stringify(res)); cb(); } function end (cb) { cb(); } return through.obj(write, end); };
Fix bug in data collection
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident) if aoid is None: node_table[ident] = aoid = ObjectId() print bson.json_util.dumps({"_id": aoid, "type": "node", "data": {"twitter_id": ident, "type": "audience", "propaganda_urls_exposed_to": record["propaganda_urls_exposed_to"], "geos": record["geos"], "timestamps_of_propaganda": record["timestamps_of_propaganda"]}}) for p in record["propagandists_followed"]: oid = node_table.get(p) if oid is None: node_table[ident] = oid = ObjectId() print bson.json_util.dumps({"_id": oid, "type": "node", "data": {"twitter_id": p, "type": "propagandist"}}) print bson.json_util.dumps({"_id": ObjectId(), "type": "link", "source": aoid, "target": oid, "data": {}}) if __name__ == "__main__": sys.exit(main())
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident) if aoid is None: node_table[ident] = aoid = ObjectId() print bson.json_util.dumps({"_id": aoid, "type": "node", "data": {"twitter_id": ident, "type": "audience", "propaganda_urls_exposed_to": record["propaganda_urls_exposed_to"], "geos": record["geos"], "timestamps_of_propaganda": record["timestamps_of_propaganda"]}}) for p in record["propagandists_followed"]: oid = node_table.get(p) if oid is None: node_table[ident] = oid = ObjectId() print bson.json_util.dumps({"_id": oid, "type": "node", "data": {"twitter_id": ident, "type": "propagandist"}}) print bson.json_util.dumps({"_id": ObjectId(), "type": "link", "source": aoid, "target": oid, "data": {}}) if __name__ == "__main__": sys.exit(main())
Update the path and the url
<?php /* * This file is part of the AlphaLemonThemeEngineBundle and it is distributed * under the MIT License. To use this bundle you must leave * intact this copyright notice. * * Copyright (c) AlphaLemon <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * For extra documentation and help please visit http://alphalemon.com * * @license MIT License */ namespace AlphaLemon\ElFinderBundle\Core\Connector; /** * Configures the connector * * @author AlphaLemon */ class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector { protected function configure() { $request = $this->container->get('request'); $options = array( 'roots' => array( array( 'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED) 'path' => 'bundles/alphalemonelfinder/vendor/ElFinder/files/', // path to files (REQUIRED) 'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED) 'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL) ) ) ); return $options; } }
<?php /* * This file is part of the AlphaLemonThemeEngineBundle and it is distributed * under the MIT License. To use this bundle you must leave * intact this copyright notice. * * Copyright (c) AlphaLemon <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * For extra documentation and help please visit http://alphalemon.com * * @license MIT License */ namespace AlphaLemon\ElFinderBundle\Core\Connector; /** * Configures the connector * * @author AlphaLemon */ class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector { protected function configure() { $request = $this->container->get('request'); $options = array( 'roots' => array( array( 'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED) 'path' => 'bundles/alphalemonelfinder/files/', // path to files (REQUIRED) 'URL' => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED) 'accessControl' => 'access' // disable and hide dot starting files (OPTIONAL) ) ) ); return $options; } }
Fix wrong input/output drata types.
package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <ItinRange, ClusterVector> * Output: <TwoInt, ClusterVector> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } }
package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <TwoInt, ItinTime> * Output: <TwoInt, ItinTime> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } }
Put profile stuff in storage
<?php return array( /* |-------------------------------------------------------------------------- | File extension |-------------------------------------------------------------------------- | Comma seperated list of file extension to be registered with the xslt view. */ 'extension' => 'xsl', /* |-------------------------------------------------------------------------- | XML Conversion settings |-------------------------------------------------------------------------- */ 'xml' => array( 'rootname' => 'data', 'encoding' => 'UTF-8' ), /* |-------------------------------------------------------------------------- | XSLTProcessor settings |-------------------------------------------------------------------------- */ 'xsl' => array( 'phpfunctions' => true, 'profiling' => true, // directory relative to `app` 'profilingdir' => 'storage/profile' ), /* |-------------------------------------------------------------------------- | Automatic attribute conversion |-------------------------------------------------------------------------- | You may declare certain array keys to be set as an xml attribute. `*` is | a wildcard to match every key name. Note that key names refer to their | normalized values, e.g. `foo_bar` would become `foo-bar`, `fooBar` becomes | `foo-bar` etc. */ 'attributes' => array( '*' => array('id', 'created-at') ), /* |-------------------------------------------------------------------------- | Normalizer Settings |-------------------------------------------------------------------------- | Prevent circular references by excluding `app` and `env` in the laravel | context */ 'normalizer' => array( 'ignoredattributes' => array('env', 'app') ), /* |-------------------------------------------------------------------------- | Global Parameters |-------------------------------------------------------------------------- */ 'params' => array( 'foo' => 'bar' ) );
<?php return array( /* |-------------------------------------------------------------------------- | File extension |-------------------------------------------------------------------------- | Comma seperated list of file extension to be registered with the xslt view. */ 'extension' => 'xsl', /* |-------------------------------------------------------------------------- | XML Conversion settings |-------------------------------------------------------------------------- */ 'xml' => array( 'rootname' => 'data', 'encoding' => 'UTF-8' ), /* |-------------------------------------------------------------------------- | XSLTProcessor settings |-------------------------------------------------------------------------- */ 'xsl' => array( 'phpfunctions' => true, 'profiling' => true, // directory relative to `app` 'profilingdir' => 'profile' ), /* |-------------------------------------------------------------------------- | Automatic attribute conversion |-------------------------------------------------------------------------- | You may declare certain array keys to be set as an xml attribute. `*` is | a wildcard to match every key name. Note that key names refer to their | normalized values, e.g. `foo_bar` would become `foo-bar`, `fooBar` becomes | `foo-bar` etc. */ 'attributes' => array( '*' => array('id', 'created-at') ), /* |-------------------------------------------------------------------------- | Normalizer Settings |-------------------------------------------------------------------------- | Prevent circular references by excluding `app` and `env` in the laravel | context */ 'normalizer' => array( 'ignoredattributes' => array('env', 'app') ), /* |-------------------------------------------------------------------------- | Global Parameters |-------------------------------------------------------------------------- */ 'params' => array( 'foo' => 'bar' ) );
Change to allow the date picker to move past the current date.
(function () { "use strict"; angular.module('orange') .directive('datefield', datefield); datefield.$inject = ['$cordovaDatePicker']; function datefield($cordovaDatePicker) { return { scope: { //allow dates in the future as per request // 'maxDateNow': '=' }, require: 'ngModel', link: function (scope, elem, attrs, ngModel) { if (ionic.Platform.isWebView()) { // Add readonly attribute to input to not display keyboard on iOS devices elem.addClass('not-readonly'); elem.attr('readonly', true); } elem.bind('click', function () { if (ionic.Platform.isWebView()) { // Running on device show datepicker var options = { date: ngModel.$viewValue ? new Date(ngModel.$viewValue) : new Date(), mode: 'date', allowOldDates: true, allowFutureDates: true, androidTheme: $cordovaDatePicker.THEME_DEVICE_DEFAULT_DARK }; if (scope.maxDateNow) { options['maxDate'] = device.platform === 'Android' ? Date.now() : new Date(); } $cordovaDatePicker.show(options).then(function (date) { var newValue = date.toJSON().slice(0, 10); //alert(newDate); ngModel.$setViewValue(newValue); elem.val(newValue); }); } else { // Steps for web app here } }) } } } })();
(function () { "use strict"; angular.module('orange') .directive('datefield', datefield); datefield.$inject = ['$cordovaDatePicker']; function datefield($cordovaDatePicker) { return { scope: { 'maxDateNow': '=' }, require: 'ngModel', link: function (scope, elem, attrs, ngModel) { if (ionic.Platform.isWebView()) { // Add readonly attribute to input to not display keyboard on iOS devices elem.addClass('not-readonly'); elem.attr('readonly', true); } elem.bind('click', function () { if (ionic.Platform.isWebView()) { // Running on device show datepicker var options = { date: ngModel.$viewValue ? new Date(ngModel.$viewValue) : new Date(), mode: 'date', allowOldDates: true, allowFutureDates: true, androidTheme: $cordovaDatePicker.THEME_DEVICE_DEFAULT_DARK }; if (scope.maxDateNow) { options['maxDate'] = device.platform === 'Android' ? Date.now() : new Date(); } $cordovaDatePicker.show(options).then(function (date) { var newValue = date.toJSON().slice(0, 10); //alert(newDate); ngModel.$setViewValue(newValue); elem.val(newValue); }); } else { // Steps for web app here } }) } } } })();
Implement the strict filter to use UserId to match the Limit permissions for push
(function (global) { 'use strict'; var app = global.app = global.app || {}; app.PushFactory = (function () { var create = function (sender, recipients) { var filter; if (Array.isArray(recipients) && recipients.length > 0) { // filter on the userId field in each device filter = { "UserId": { "$in": recipients } }; } // custom data object for Android and iOS var customData = { "dateCreated": new Date() }; var pushTitle = "Backend Services Push Sample"; var pushMessage = sender + ": " + "Hello, push notifications!"; // constructing the payload for the notification specifically for each supported mobile platform // following the structure from here: http://docs.telerik.com/platform/backend-services/features/push-notifications/structure var androidPayload = { "data": { "title": pushTitle, "message": pushMessage, "customData": customData } }; var iosPayload = { "aps": { "alert": pushMessage, "badge": 1, "sound": "default" }, "customData": customData }; var wpPayload = { "Toast": { "Title": pushTitle, "Message": pushMessage } }; var notificationObject = { "Filter": JSON.stringify(filter), "Android": androidPayload, "IOS": iosPayload, "WindowsPhone": wpPayload }; return notificationObject; } return { create: create } })(); }(window));
(function (global) { 'use strict'; var app = global.app = global.app || {}; app.PushFactory = (function () { var create = function (sender, recipients) { var filter; if (Array.isArray(recipients) && recipients.length > 0) { // filter on the userId field in each device filter = { "User.Id": { "$in": recipients } }; } // custom data object for Android and iOS var customData = { "dateCreated": new Date() }; var pushTitle = "Backend Services Push Sample"; var pushMessage = sender + ": " + "Hello, push notifications!"; // constructing the payload for the notification specifically for each supported mobile platform // following the structure from here: http://docs.telerik.com/platform/backend-services/features/push-notifications/structure var androidPayload = { "data": { "title": pushTitle, "message": pushMessage, "customData": customData } }; var iosPayload = { "aps": { "alert": pushMessage, "badge": 1, "sound": "default" }, "customData": customData }; var wpPayload = { "Toast": { "Title": pushTitle, "Message": pushMessage } }; var notificationObject = { "Filter": JSON.stringify(filter), "Android": androidPayload, "IOS": iosPayload, "WindowsPhone": wpPayload }; return notificationObject; } return { create: create } })(); }(window));
Replace all occurances of $graph->getNumberOfVertices() replaced with count($graph->getVertices())
<?php use Fhaculty\Graph\Algorithm\Complete; use Fhaculty\Graph\Algorithm\Directed; use Fhaculty\Graph\Graph; use Fhaculty\Graph\Loader\CompleteGraph; class CompleteGraphTest extends TestCase { public function testOne() { $loader = new CompleteGraph(1); $graph = $loader->createGraph(); $expected = new Graph(); $expected->createVertex(); $this->assertGraphEquals($expected, $graph); } public function testUndirected() { $n = 9; $loader = new CompleteGraph($n); $graph = $loader->createGraph(); $this->assertEquals($n, count($graph->getVertices())); $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges()); } public function testDirected() { $n = 8; $loader = new CompleteGraph($n); $loader->setEnableDirectedEdges(true); $graph = $loader->createGraph(); $this->assertEquals($n, count($graph->getVertices())); $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs $alg = new Directed($graph); $this->assertTrue($alg->isDirected()); $alg = new Complete($graph); $this->assertTrue($alg->isComplete()); } }
<?php use Fhaculty\Graph\Algorithm\Complete; use Fhaculty\Graph\Algorithm\Directed; use Fhaculty\Graph\Graph; use Fhaculty\Graph\Loader\CompleteGraph; class CompleteGraphTest extends TestCase { public function testOne() { $loader = new CompleteGraph(1); $graph = $loader->createGraph(); $expected = new Graph(); $expected->createVertex(); $this->assertGraphEquals($expected, $graph); } public function testUndirected() { $n = 9; $loader = new CompleteGraph($n); $graph = $loader->createGraph(); $this->assertEquals($n, $graph->getNumberOfVertices()); $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges()); } public function testDirected() { $n = 8; $loader = new CompleteGraph($n); $loader->setEnableDirectedEdges(true); $graph = $loader->createGraph(); $this->assertEquals($n, $graph->getNumberOfVertices()); $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs $alg = new Directed($graph); $this->assertTrue($alg->isDirected()); $alg = new Complete($graph); $this->assertTrue($alg->isComplete()); } }
Fix one more issue thanks to Scrutinizer
<?php namespace Baddum\Factory418; trait FactoryTrait { /* ATTRIBUTES *************************************************************************/ private static $indexList = []; /* PUBLIC METHODS *************************************************************************/ public function registerClass($className, $indexList) { if (is_object($className)) { $className = get_class($className); } $factoryName = get_called_class(); if (!isset(self::$indexList[$factoryName])) { self::$indexList[$factoryName] = []; } if (!is_array($indexList)) { $indexList = [$indexList]; } foreach ($indexList as $index) { $id = strtolower($index); self::$indexList[$factoryName][$id] = $className; } return $this; } public function newInstance($index) { $factoryName = get_called_class(); if (!isset(self::$indexList[$factoryName])) { return $this->onNoClassRegistered($index); } $id = strtolower($index); if (!isset(self::$indexList[$factoryName][$id])) { return $this->onNoClassRegistered($index); } $className = self::$indexList[$factoryName][$id]; return new $className; } /* PROTECTED METHODS *************************************************************************/ protected function onNoClassRegistered($index) { throw new \RuntimeException('No class registered for the index: ' . $index); } }
<?php namespace Baddum\Factory418; trait FactoryTrait { /* ATTRIBUTES *************************************************************************/ private static $indexList = []; /* PUBLIC METHODS *************************************************************************/ public function registerClass($className, $indexList) { if (is_object($className)) { $className = get_class($className); } $factoryName = get_called_class(); if (!isset(static::$indexList[$factoryName])) { self::$indexList[$factoryName] = []; } if (!is_array($indexList)) { $indexList = [$indexList]; } foreach ($indexList as $index) { $id = strtolower($index); self::$indexList[$factoryName][$id] = $className; } return $this; } public function newInstance($index) { $factoryName = get_called_class(); if (!isset(self::$indexList[$factoryName])) { return $this->onNoClassRegistered($index); } $id = strtolower($index); if (!isset(self::$indexList[$factoryName][$id])) { return $this->onNoClassRegistered($index); } $className = self::$indexList[$factoryName][$id]; return new $className; } /* PROTECTED METHODS *************************************************************************/ protected function onNoClassRegistered($index) { throw new \RuntimeException('No class registered for the index: ' . $index); } }
Tweak wording of password prompt iCloud is branded with a lower case 'i' like most other Apple products.
import getpass import keyring from .exceptions import NoStoredPasswordAvailable KEYRING_SYSTEM = 'pyicloud://icloud-password' def get_password(username, interactive=True): try: return get_password_from_keyring(username) except NoStoredPasswordAvailable: if not interactive: raise return getpass.getpass( 'Enter iCloud password for {username}: '.format( username=username, ) ) def password_exists_in_keyring(username): try: get_password_from_keyring(username) except NoStoredPasswordAvailable: return False return True def get_password_from_keyring(username): result = keyring.get_password( KEYRING_SYSTEM, username ) if result is None: raise NoStoredPasswordAvailable( "No pyicloud password for {username} could be found " "in the system keychain. Use the `--store-in-keyring` " "command-line option for storing a password for this " "username.".format( username=username, ) ) return result def store_password_in_keyring(username, password): return keyring.set_password( KEYRING_SYSTEM, username, password, ) def delete_password_in_keyring(username): return keyring.delete_password( KEYRING_SYSTEM, username, )
import getpass import keyring from .exceptions import NoStoredPasswordAvailable KEYRING_SYSTEM = 'pyicloud://icloud-password' def get_password(username, interactive=True): try: return get_password_from_keyring(username) except NoStoredPasswordAvailable: if not interactive: raise return getpass.getpass( 'ICloud Password for {username}: '.format( username=username, ) ) def password_exists_in_keyring(username): try: get_password_from_keyring(username) except NoStoredPasswordAvailable: return False return True def get_password_from_keyring(username): result = keyring.get_password( KEYRING_SYSTEM, username ) if result is None: raise NoStoredPasswordAvailable( "No pyicloud password for {username} could be found " "in the system keychain. Use the `--store-in-keyring` " "command-line option for storing a password for this " "username.".format( username=username, ) ) return result def store_password_in_keyring(username, password): return keyring.set_password( KEYRING_SYSTEM, username, password, ) def delete_password_in_keyring(username): return keyring.delete_password( KEYRING_SYSTEM, username, )
Allow non-anchor links to click through normally
var RawnetAdmin = window.RawnetAdmin || {}; RawnetAdmin.menu = function(){ function toggleNav(link) { var active = $('#mainNav a.active'), target = $(link.attr('href')), activeMenu = $('#subNav nav.active'); active.removeClass('active'); activeMenu.removeClass('active'); link.addClass('active'); target.addClass('active'); } function openSearch() { var search = $('#searchControl'); search.fadeIn("fast").addClass('open'); search.find('input').focus(); $(document).keyup(function(e) { if (e.keyCode === 27) { search.fadeOut("fast").removeClass('open'); $(document).unbind("keyup"); }else if (e.keyCode === 13) { search.find('form').trigger('submit'); } }); } function init() { var activeLink = $('#subNav a.active'), activeMenu = activeLink.closest('nav'), activeSelector = $('#mainNav a[href="#' + activeMenu.attr('id') + '"]'); activeMenu.addClass('active'); activeSelector.addClass('active'); $(document).on('click', '#mainNav a[href^="#"], #dashboardNav a[href^="#"]', function(e) { e.preventDefault(); toggleNav($(this)); }); $(document).on('click', '#subNav a.search', function(e) { e.preventDefault(); openSearch(); }); } return { init: init }; }();
var RawnetAdmin = window.RawnetAdmin || {}; RawnetAdmin.menu = function(){ function toggleNav(link) { var active = $('#mainNav a.active'), target = $(link.attr('href')), activeMenu = $('#subNav nav.active'); active.removeClass('active'); activeMenu.removeClass('active'); link.addClass('active'); target.addClass('active'); } function openSearch() { var search = $('#searchControl'); search.fadeIn("fast").addClass('open'); search.find('input').focus(); $(document).keyup(function(e) { if (e.keyCode === 27) { search.fadeOut("fast").removeClass('open'); $(document).unbind("keyup"); }else if (e.keyCode === 13) { search.find('form').trigger('submit'); } }); } function init() { var activeLink = $('#subNav a.active'), activeMenu = activeLink.closest('nav'), activeSelector = $('#mainNav a[href="#' + activeMenu.attr('id') + '"]'); activeMenu.addClass('active'); activeSelector.addClass('active'); $(document).on('click', '#mainNav a, #dashboardNav a', function(e) { e.preventDefault(); toggleNav($(this)); }); $(document).on('click', '#subNav a.search', function(e) { e.preventDefault(); openSearch(); }); } return { init: init }; }();
Convert dashed itemKeys to camel cased
import dashesToCamelCase from '../../helpers/string/dashes-to-camel-case'; export default class ComponentExtensionItemSelectorToMembers { itemSelectorToMembers() { let selector = this.options.itemSelector || '[data-js-item]'; let domItemsInSubModules = Array.from(this.el.querySelectorAll( `${this.moduleSelector}`) ); let domItems = Array.from(this.el.querySelectorAll(selector)); this.items = {}; let isContainedInSubmodule = false; domItems.forEach((domItem) => { domItemsInSubModules.forEach((domItemInSubModule) => { if (!isContainedInSubmodule && domItemInSubModule.contains(domItem)) { isContainedInSubmodule = true; } }); if (!isContainedInSubmodule && domItem.dataset.jsItem) { let itemsKey = dashesToCamelCase(domItem.dataset.jsItem); if (this.items[itemsKey + 's'] && (this.items[itemsKey + 's'] instanceof Array)) { // add to pluralized key and array this.items[itemsKey + 's'].push(domItem); } else if (this.items[itemsKey]) { // make pluralized key and array this.items[itemsKey + 's'] = [ this.items[itemsKey], domItem ]; delete this.items[itemsKey]; } else { // just one item this.items[itemsKey] = domItem; } } }); } }
export default class ComponentExtensionItemSelectorToMembers { itemSelectorToMembers() { let selector = this.options.itemSelector || '[data-js-item]'; let domItemsInSubModules = Array.from(this.el.querySelectorAll( `${this.moduleSelector}`) ); let domItems = Array.from(this.el.querySelectorAll(selector)); this.items = {}; let isContainedInSubmodule = false; domItems.forEach((domItem) => { domItemsInSubModules.forEach((domItemInSubModule) => { if (!isContainedInSubmodule && domItemInSubModule.contains(domItem)) { isContainedInSubmodule = true; } }); if (!isContainedInSubmodule && domItem.dataset.jsItem) { if (this.items[domItem.dataset.jsItem + 's'] && (this.items[domItem.dataset.jsItem + 's'] instanceof Array)) { // add to pluralized key and array this.items[domItem.dataset.jsItem + 's'].push(domItem); } else if (this.items[domItem.dataset.jsItem]) { // make pluralized key and array this.items[domItem.dataset.jsItem + 's'] = [ this.items[domItem.dataset.jsItem], domItem ]; delete this.items[domItem.dataset.jsItem]; } else { // just one item this.items[domItem.dataset.jsItem] = domItem; } } }); } }
Add default values for homepage
import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import Header from './components/header/Header'; class Home extends Component { render() { return ( <div id="home"> <Header noWishlist={true} /> <div className="grid-y align-center align-middle"> <h1>Events einfach <em>nachhaltig</em> geplant</h1> <form action="/app"> <div className="cell grid-x"> <label> Wo? <input type="text" defaultValue="Frankfurt" /> </label> <label> Wieviele? <input type="text" defaultValue="10" /> </label> <label> Was? <input type="text" defaultValue="Kongress" /> </label> </div> <button className="cell button success hollow" type="submit"> SENDEN </button> </form> </div> </div> ); } } export default Home;
import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import Header from './components/header/Header'; class Home extends Component { render() { return ( <div id="home"> <Header noWishlist={true} /> <div className="grid-y align-center align-middle"> <h1>Events einfach <em>nachhaltig</em> geplant</h1> <form action="/app"> <div className="cell grid-x"> <label> Wo? <input type="text" /> </label> <label> Wieviele? <input type="text" /> </label> <label> Was? <input type="text" /> </label> </div> <button className="cell button success hollow" type="submit"> SENDEN </button> </form> </div> </div> ); } } export default Home;
Set default UsernameGenerator username format to %s to work with the current routing requirements. Both will need updating when the format is agreed.
<?php namespace Ice\UsernameGeneratorBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('ice_username_generator'); $rootNode ->children() ->scalarNode('username_format') ->defaultValue('%s') ->info('A printf formatted string with a single %s placeholder.') ->end() ->scalarNode('sequence_start') ->validate() ->ifTrue(function ($v) { return !is_int($v); }) ->thenInvalid('Must be an integer but %s found.') ->end() ->defaultValue(1) ->info('The lowest number that will be appended to the User\'s initials to form their username.') ->end() ->end(); return $treeBuilder; } }
<?php namespace Ice\UsernameGeneratorBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('ice_username_generator'); $rootNode ->children() ->scalarNode('username_format') ->defaultValue('%s@ice') ->info('A printf formatted string with a single %s placeholder.') ->end() ->scalarNode('sequence_start') ->validate() ->ifTrue(function ($v) { return !is_int($v); }) ->thenInvalid('Must be an integer but %s found.') ->end() ->defaultValue(1) ->info('The lowest number that will be appended to the User\'s initials to form their username.') ->end() ->end(); return $treeBuilder; } }
Remove no longer needed references for keeping pep8 happy
from twisted.trial.unittest import TestCase from go_metrics.metrics.dummy import Fixtures, DummyMetrics, DummyBackend class TestFixtures(TestCase): def test_add(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(fixtures.items, [{ 'foo': 'bar', 'result': {'baz': 'quux'} }]) def test_add_no_result(self): fixtures = Fixtures() fixtures.add(foo='bar') self.assertEqual(fixtures.items, [{ 'foo': 'bar', 'result': {} }]) def test_match(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) fixtures.add(corge='grault', result={'garply': 'waldo'}) self.assertEqual(fixtures.match(foo='bar'), {'baz': 'quux'}) self.assertEqual(fixtures.match(corge='grault'), {'garply': 'waldo'}) self.assertEqual(fixtures.match(fred='xzyy'), {}) class TestDummyMetrics(TestCase): def test_get(self): backend = DummyBackend() metrics = DummyMetrics(backend, 'owner-1') backend.fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(metrics.get(foo='bar'), {'baz': 'quux'}) class TestDummyBackend(TestCase): pass
from twisted.trial.unittest import TestCase from go_metrics.metrics.dummy import Fixtures, DummyMetrics, DummyBackend DummyBackend, DummyMetrics class TestFixtures(TestCase): def test_add(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(fixtures.items, [{ 'foo': 'bar', 'result': {'baz': 'quux'} }]) def test_add_no_result(self): fixtures = Fixtures() fixtures.add(foo='bar') self.assertEqual(fixtures.items, [{ 'foo': 'bar', 'result': {} }]) def test_match(self): fixtures = Fixtures() fixtures.add(foo='bar', result={'baz': 'quux'}) fixtures.add(corge='grault', result={'garply': 'waldo'}) self.assertEqual(fixtures.match(foo='bar'), {'baz': 'quux'}) self.assertEqual(fixtures.match(corge='grault'), {'garply': 'waldo'}) self.assertEqual(fixtures.match(fred='xzyy'), {}) class TestDummyMetrics(TestCase): def test_get(self): backend = DummyBackend() metrics = DummyMetrics(backend, 'owner-1') backend.fixtures.add(foo='bar', result={'baz': 'quux'}) self.assertEqual(metrics.get(foo='bar'), {'baz': 'quux'}) class TestDummyBackend(TestCase): pass
Make sure we use Python 3 here
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
Move the @Transactional(readOnly = true) annotation to class level
package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing; import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post; import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Arrays; import java.util.List; /** * @author Vlad Mihalcea */ @Service @Transactional(readOnly = true) public class ForumServiceImpl implements ForumService { @PersistenceContext private EntityManager entityManager; @Override @Transactional public Post newPost(String title, String... tags) { Post post = new Post(); post.setTitle(title); post.getTags().addAll( entityManager.createQuery(""" select t from Tag t where t.name in :tags """, Tag.class) .setParameter("tags", Arrays.asList(tags)) .getResultList() ); entityManager.persist(post); return post; } @Override public List<Post> findAllPostsByTitle(String title) { return entityManager.createQuery(""" select p from Post p where p.title = :title """, Post.class) .setParameter("title", title) .getResultList(); } }
package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing; import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post; import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Arrays; import java.util.List; /** * @author Vlad Mihalcea */ @Service public class ForumServiceImpl implements ForumService { @PersistenceContext private EntityManager entityManager; @Override @Transactional public Post newPost(String title, String... tags) { Post post = new Post(); post.setTitle(title); post.getTags().addAll( entityManager.createQuery(""" select t from Tag t where t.name in :tags """, Tag.class) .setParameter("tags", Arrays.asList(tags)) .getResultList() ); entityManager.persist(post); return post; } @Override @Transactional(readOnly = true) public List<Post> findAllPostsByTitle(String title) { return entityManager.createQuery(""" select p from Post p where p.title = :title """, Post.class) .setParameter("title", title) .getResultList(); } }
Fix javascript dependencies for a couple other plugins that aren't AMD modules
// Common configuration for RequireJS var require = { baseUrl: "/scripts", paths: { "jquery": "bower_components/jquery/dist/jquery.min", "knockout": "bower_components/knockout/dist/knockout", "bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min", "text": "bower_components/requirejs-text/text", "domReady": "bower_components/requirejs-domReady/domReady", "moment": "bower_components/moment/min/moment.min", "videojs": "bower_components/videojs/dist/video-js/video", "knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min", "knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min", "perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar", "jquery-expander": "bower_components/jquery-expander/jquery.expander", "bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select", "bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput", }, shim: { "bootstrap": { deps: ["jquery"], exports: "$.fn.popover" }, "jquery-expander": ["jquery"], "perfect-scrollbar": ["jquery"], "bootstrap-select": ["bootstrap"], "bootstrap-tagsinput": ["bootstrap"] } };
// Common configuration for RequireJS var require = { baseUrl: "/scripts", paths: { "jquery": "bower_components/jquery/dist/jquery.min", "knockout": "bower_components/knockout/dist/knockout", "bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min", "text": "bower_components/requirejs-text/text", "domReady": "bower_components/requirejs-domReady/domReady", "moment": "bower_components/moment/min/moment.min", "videojs": "bower_components/videojs/dist/video-js/video", "knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min", "knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min", "perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar", "jquery-expander": "bower_components/jquery-expander/jquery.expander", "bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select", "bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput", }, shim: { "bootstrap": { deps: ["jquery"], exports: "$.fn.popover" }, "jquery-expander": ["jquery"] } };
Update Census statistics method to get groups, sections and teams
import connection from '../../config/database'; module.exports.register = (server, options, next) => { async function getStats(next) { try { const groups = await connection .table('employees') .filter(doc => doc('grp').ne(''))('grp') .distinct() .count(); const divisions = await connection .table('employees') .filter(doc => doc('div').ne(''))('div') .distinct() .count(); const directorates = await connection .table('employees') .filter(doc => doc('directorate').ne(''))('directorate') .distinct() .count(); const branches = await connection .table('employees') .filter(doc => doc('bran').ne(''))('bran') .distinct() .count(); const sections = await connection .table('employees') .filter(doc => doc('sect').ne(''))('sect') .distinct() .count(); const teams = await connection .table('employees') .filter(doc => doc('team').ne(''))('team') .distinct() .count(); const employees = await connection .table('employees') .filter(doc => doc('email').ne(''))('email') .distinct() .count(); const locations = await connection .table('employees') .filter(doc => doc('location_name').ne(''))('location_name') .distinct() .count(); const stats = { organisation: { groups, divisions, directorates, branches, sections, teams, }, employees, locations, }; return next(null, stats); } catch (error) { return next(error); } } server.method('db.getStats', getStats, {}); next(); }; module.exports.register.attributes = { name: 'method.db.getStats', };
import connection from '../../config/database'; module.exports.register = (server, options, next) => { async function getStats(next) { try { const divisions = await connection .table('employees') .filter(doc => doc('div').ne(''))('div') .distinct() .count(); const directorates = await connection .table('employees') .filter(doc => doc('bran').ne(''))('bran') .distinct() .count(); const branches = await connection .table('employees') .filter(doc => doc('sect').ne(''))('sect') .distinct() .count(); const employees = await connection .table('employees') .filter(doc => doc('email').ne(''))('email') .distinct() .count(); const locations = await connection .table('employees') .filter(doc => doc('location_name').ne(''))('location_name') .distinct() .count(); const stats = { organisation: { branches, directorates, divisions }, employees, locations }; return next(null, stats); } catch (error) { return next(error); } } server.method('db.getStats', getStats, {}); next(); }; module.exports.register.attributes = { name: 'method.db.getStats', };
Simplify Settings code a little bit - Fixes error 500 on homepage with clean database
from django.utils import timezone from settings.models import Setting from utils.dates import string_to_datetime class Settings: def __init__(self, values=None): if values is None: return settings = Setting.objects.filter(name__in=values) self.__dict__['settings'] = dict((o.name, o.value) for o in settings) def __getattr__(self, item): return self.__dict__['settings'][item] def __setattr__(self, key, value): Setting.objects.update_or_create(name=key, defaults={'value': value}) def is_sell_available(): try: settings = Settings(['start_sell', 'end_sell']) start_sell = string_to_datetime(settings.start_sell) end_sell = string_to_datetime(settings.end_sell) now = timezone.now() if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0: return True except KeyError: return False return False def is_purchase_available(): try: settings = Settings(['start_purchase', 'end_purchase']) start_purchase = string_to_datetime(settings.start_purchase) end_purchase = string_to_datetime(settings.end_purchase) now = timezone.now() if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0: return True except KeyError: return False return False
from django.utils import timezone from settings.models import Setting from utils.dates import string_to_datetime class Settings: def __init__(self, values=None): if values is None: return settings = Setting.objects.filter(name__in=values) self.__dict__['settings'] = dict((o.name, o.value) for o in settings) def __getattr__(self, item): return str(self.__dict__['settings'].get(item)) def __setattr__(self, key, value): Setting.objects.update_or_create(name=key, defaults={'value': str(value)}) def is_sell_available(): try: settings = Settings(['start_sell', 'end_sell']) start_sell = string_to_datetime(settings.start_sell) end_sell = string_to_datetime(settings.end_sell) now = timezone.now() if (now - start_sell).total_seconds() > 0 and (end_sell - now).total_seconds() > 0: return True except KeyError: return False return False def is_purchase_available(): try: settings = Settings(['start_purchase', 'end_purchase']) start_purchase = string_to_datetime(settings.start_purchase) end_purchase = string_to_datetime(settings.end_purchase) now = timezone.now() if (now - start_purchase).total_seconds() > 0 and (end_purchase - now).total_seconds() > 0: return True except KeyError: return False return False
Fix main camera zTranslation responsive issue
import Geometric from './geometric/geometric.js' export default class Background { static draw(p) { Background.changeColor(p) Background.translateCamera(p) Background.translateCameraByMouse(p) Geometric.draw(p) } static changeColor(p) { const hexColorMax = 255 const radianX2 = p.PI * 2 const fps = 60 const fpsGear = 1 / 20 const radianPerFrame = radianX2 / fps const radianPerFrameGeared = radianPerFrame * fpsGear const fpsReal = fps / fpsGear const frame = p.frameCount % fpsReal const radian = radianPerFrameGeared * frame const sine = p.sin(radian) const sineMapped1 = (sine + 1) / 2 const hexColor = sineMapped1 * hexColorMax p.background(hexColor) } static translateCamera(p) { const xTranslate = p.frameCount * 0.01 const yTranslate = 0 let zTranslate = -(p.width / 3) if (window.screen.width < 600) { zTranslate = window.screen.width / 5 } p.translate(xTranslate, yTranslate, zTranslate) } static translateCameraByMouse(p) { const xTranslate = -p.mouseX / 10 const yTranslate = -p.mouseY / 10 p.translate(xTranslate, yTranslate) } }
import Geometric from './geometric/geometric.js' export default class Background { static draw(p) { Background.changeColor(p) Background.translateCamera(p) Background.translateCameraByMouse(p) Geometric.draw(p) } static changeColor(p) { const hexColorMax = 255 const radianX2 = p.PI * 2 const fps = 60 const fpsGear = 1 / 20 const radianPerFrame = radianX2 / fps const radianPerFrameGeared = radianPerFrame * fpsGear const fpsReal = fps / fpsGear const frame = p.frameCount % fpsReal const radian = radianPerFrameGeared * frame const sine = p.sin(radian) const sineMapped1 = (sine + 1) / 2 const hexColor = sineMapped1 * hexColorMax p.background(hexColor) } static translateCamera(p) { const xTranslate = p.frameCount * 0.01 const yTranslate = 0 const zTranslate = -(p.windowHeight / 2) p.translate(xTranslate, yTranslate, zTranslate) } static translateCameraByMouse(p) { const xTranslate = -p.mouseX / 10 const yTranslate = -p.mouseY / 10 p.translate(xTranslate, yTranslate) } }
Add type hints for mocked dependencies
<?php declare(strict_types=1); namespace Mihaeu\TestGenerator; use PhpParser\NodeTraverser; use PhpParser\NodeVisitor\NameResolver; use PhpParser\Parser; use PHPUnit\Framework\TestCase; use PHPUnit_Framework_MockObject_MockObject as Mock; /** * @covers Mihaeu\TestGenerator\TestGenerator */ class TestGeneratorTest extends TestCase { /** @var TestGenerator */ private $testGenerator; /** @var Parser | Mock */ private $parser; /** @var NameResolver | Mock */ private $nameResolver; /** @var ClassAnalyser | Mock */ private $classAnalyser; /** @var NodeTraverser | Mock */ private $nodeTraverser; public function setUp() { $this->parser = $this->createMock(Parser::class); $this->nameResolver = $this->createMock(NameResolver::class); $this->classAnalyser = $this->createMock(ClassAnalyser::class); $this->nodeTraverser = $this->createMock(NodeTraverser::class); $this->testGenerator = new TestGenerator( $this->parser, $this->nameResolver, $this->classAnalyser, $this->nodeTraverser ); } public function testDoesNotPrintTemplateIfFileDoesNotHaveAConstructor() { $this->parser->method('parse')->willReturn([]); $file = $this->createMock(PhpFile::class); $file->method('content')->willReturn('<?php class A {}'); assertEmpty($this->testGenerator->run($file)); } }
<?php declare(strict_types=1); namespace Mihaeu\TestGenerator; use PhpParser\NodeTraverser; use PhpParser\NodeVisitor\NameResolver; use PhpParser\Parser; use PHPUnit\Framework\TestCase; /** * @covers Mihaeu\TestGenerator\TestGenerator */ class TestGeneratorTest extends TestCase { /** @var TestGenerator */ private $testGenerator; /** @var Parser */ private $parser; /** @var NameResolver */ private $nameResolver; /** @var ClassAnalyser */ private $classAnalyser; /** @var NodeTraverser */ private $nodeTraverser; public function setUp() { $this->parser = $this->createMock(Parser::class); $this->nameResolver = $this->createMock(NameResolver::class); $this->classAnalyser = $this->createMock(ClassAnalyser::class); $this->nodeTraverser = $this->createMock(NodeTraverser::class); $this->testGenerator = new TestGenerator( $this->parser, $this->nameResolver, $this->classAnalyser, $this->nodeTraverser ); } public function testDoesNotPrintTemplateIfFileDoesNotHaveAConstructor() { $this->parser->method('parse')->willReturn([]); $file = $this->createMock(PhpFile::class); $file->method('content')->willReturn('<?php class A {}'); assertEmpty($this->testGenerator->run($file)); } }
Add appId asap, however we should figure out a better flow
/*jshint esversion:6, node:true*/ 'use strict'; const extend = require('gextend'); var DEFAULTS = { middleware: require('./middleware') }; module.exports = function(options) { return { init: function(context, config) { config = extend({}, options, config); const express = require('express'); var app = express(); /* * Enable middleware to use context, * i.e. to publish an event system wide. * context.emit('web.request.createUser', user); */ config.context = context; /* * Create a logger for our express app. * This can be trickled down to middleware * as well. */ config.logger = context.getLogger(config.moduleid); //TODO: This should be pulled out of here and implmented by //configurator. setup(app, config); return app; } }; }; function setup(app, config) { config = extend({}, DEFAULTS, config); //TODO: Should we have policies & middleware? var middleware = config.middleware; var use = config.middleware.use; use.map((id) => { if (!middleware.hasOwnProperty(id)) { missingMiddleware(config, id); } middleware[id](app, config); }); /* * Make sub app aware of it's own * module id. */ app.appId = config.moduleid; } function missingMiddleware(config, middleware) { let message = 'Sub app "' + config.moduleid + '" has no middleware "' + middleware + '"'; throw new Error(message); }
/*jshint esversion:6, node:true*/ 'use strict'; const extend = require('gextend'); var DEFAULTS = { middleware: require('./middleware') }; module.exports = function(options){ return { init: function(context, config){ config = extend({}, options, config); const express = require('express'); var app = express(); /* * Enable middleware to use context, * i.e. to publish an event system wide. * context.emit('web.request.createUser', user); */ config.context = context; /* * Create a logger for our express app. * This can be trickled down to middleware * as well. */ config.logger = context.getLogger(config.moduleid); //TODO: This should be pulled out of here and implmented by //configurator. setup(app, config); return app; } }; }; function setup(app, config){ config = extend({}, DEFAULTS, config); //TODO: Should we have policies & middleware? var middleware = config.middleware; var use = config.middleware.use; use.map((id)=>{ if(!middleware.hasOwnProperty(id)){ missingMiddleware(config, id); } middleware[id](app, config); }); } function missingMiddleware(config, middleware){ let message = 'Sub app "' + config.moduleid + '" has no middleware "' + middleware + '"'; throw new Error(message); }
Refactor dramas controller for authorization
(function(){ 'use strict'; angular .module('secondLead') .controller('DramasCtrl', [ 'DramaModel', 'Gridster', 'ListModel', 'Restangular', 'UserModel', function (DramaModel, Gridster, ListModel, Restangular, UserModel){ var ctrl = this; ctrl.items = DramaModel.getAll; ctrl.user = ''; var authorized = function () { if(UserModel.currentUser()){ ctrl.user = UserModel.currentUser(); ctrl.userLists = ListModel.currentUserLists(); } }; authorized(); ctrl.selectedList = {}; ctrl.gridsterOpts = { columns: 4, width: 'auto', colWidth: 'auto', rowHeight: 'match', margins: [5, 5], outerMargin: true, isMobile: false, mobileBreakPoint: 750, mobileModeEnabled: true, minColumns: 1, minRows: 2, maxRows: 100, defaultSizeX: 1, defaultSizeY: 1, minSizeX: 1, maxSizeX: null, minSizeY: 1, maxSizeY: null, resizable: { enabled: false }, draggable: { enabled: false } }; ctrl.currentPage = 1; ctrl.pageSize = 32; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .controller('DramasCtrl', [ 'DramaModel', 'Gridster', 'ListModel', 'Restangular', 'UserModel', function(DramaModel, Gridster, ListModel, Restangular, UserModel) { var ctrl = this; ctrl.items = DramaModel.getAll; ctrl.user = UserModel.currentUser(); ctrl.userLists = ListModel.currentUserLists(); ctrl.selectedList = {}; ctrl.gridsterOpts = { columns: 4, width: 'auto', colWidth: 'auto', rowHeight: 'match', margins: [5, 5], outerMargin: true, isMobile: false, mobileBreakPoint: 750, mobileModeEnabled: true, minColumns: 1, minRows: 2, maxRows: 100, defaultSizeX: 1, defaultSizeY: 1, minSizeX: 1, maxSizeX: null, minSizeY: 1, maxSizeY: null, resizable: { enabled: false }, draggable: { enabled: false } }; ctrl.currentPage = 1; ctrl.pageSize = 32; }]) })();
Add warning log level for auth checks
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import request as flask_request from flask import abort import logging import os def gen_auth_token(id,expiration=10000): """Generate auth token""" try: s = Serializer(os.environ['API_KEY'],expires_in=expiration) except KeyError: logging.fatal("No API_KEY env") abort(500) return s.dumps({'id':id}) def verify_auth_token(token): """Verify auth token""" try: s = Serializer(os.environ['API_KEY']) except KeyError: logging.fatal("No API_KEY env") abort(500) # check the token and throw respective exception try: user = s.loads(token) except Exception as e: logging.warning("Bad token") abort(401) return user def enable_auth(func): """Decorator to enable auth""" def wrapper(*args,**kwargs): re = flask_request # deny if not authorized if not re.headers.has_key("Authorization"): logging.warning("No token found") abort(401) auth = re.headers.get("Authorization").split(" ") # proces token validate = verify_auth_token(auth[1]) logging.debug("Valid auth! Yay") return func(*args,**kwargs) return wrapper
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import request as flask_request from flask import abort import logging import os def gen_auth_token(id,expiration=10000): """Generate auth token""" try: s = Serializer(os.environ['API_KEY'],expires_in=expiration) except KeyError: logging.fatal("No API_KEY env") abort(500) return s.dumps({'id':id}) def verify_auth_token(token): """Verify auth token""" try: s = Serializer(os.environ['API_KEY']) except KeyError: logging.fatal("No API_KEY env") abort(500) # check the token and throw respective exception try: user = s.loads(token) except Exception as e: logging.info(e) abort(401) return user def enable_auth(func): """Decorator to enable auth""" def wrapper(*args,**kwargs): re = flask_request # deny if not authorized if not re.headers.has_key("Authorization"): logging.info("No token found") abort(401) auth = re.headers.get("Authorization").split(" ") # proces token validate = verify_auth_token(auth[1]) logging.debug("Valid auth! Yay") return func(*args,**kwargs) return wrapper
Add example cases for block:link
({ block : 'page', title : 'bem-components: link', mods : { theme : 'normal' }, head : [ { elem : 'css', url : '_simple.css' }, { elem : 'js', url : '_simple.js' } ], content : ['default', 'simple', 'normal'].map(function(theme, i) { var content = [ { block : 'link', content : 'with no url' }, { block : 'link', url : 'http://example.com/', content : 'plain url' }, { block : 'link', url : { block : 'link-content', tag : '', content : '/action' }, content : 'bemjson url' }, { block : 'link', url : 'http://example.com/', title : 'One of the largest internet companies in Europe', content : 'with title' }, { block : 'link', url : 'http://example.com/', title : 'One of the largest internet companies in Europe', target : '_blank', content : 'blank target' }, { block : 'link', mods : { pseudo : true }, content : 'pseudo link' }, { block : 'link', url : 'http://example.com/', tabIndex : -1, content : 'out of tab order' } ].map(function(link, j) { link.mods || (link.mods = {}); i && (link.mods.theme = theme); return [ j > 0 && { tag : 'br' }, link ] }); content.unshift({ tag : 'h2', content : theme }); i && content.unshift({ tag : 'hr' }); return content; }) })
({ block : 'page', title : 'bem-components: link', mods : { theme : 'normal' }, head : [ { elem : 'css', url : '_simple.css' }, { elem : 'js', url : '_simple.js' } ], content : [ { block : 'link', content : 'Empty link 1' }, { block : 'link', url : { block : 'link-content', tag : '', content : '/action' }, content : 'url with bemjson' }, { block : 'link', url : 'http://yandex.ru', content : 'yandex.ru' }, { block : 'link', url : 'http://yandex.com', title : 'One of the largest internet companies in Europe', content : 'yandex.com' }, { block : 'link', url : 'http://yandex.com.tr', title : 'One of the largest internet companies in Europe', target : '_blank', content : 'yandex.com.tr' }, { block : 'link', mods : { pseudo : true }, content : 'Pseudo link' }, { block : 'link', tabIndex : -1, content : 'yandex.ru' } ].map(function(l) { return { tag : 'div', content : l } }) })
Make a urlgenerator creates links protocol insensitive
<?php class UrlGenerator { public static function generate_thumb_url($filename, $type = '', $size = '_thumb') { if (empty($filename)) { return ''; // Fallback error image } if (ENVIRONMENT === 'production') { $host = '//img.pickartyou.com/'; } else { $host = '/uploads/'; } if (!empty($type)) { $host .= $type . '/'; } $path_parts = pathinfo($filename); if (!isset($path_parts['extension'])) { return ''; // Fallback error image } return $host . $path_parts['filename'] . $size . '.' . $path_parts['extension']; } public static function generate_original_image_url($filename, $type = '') { if (empty($filename)) { return ''; // Fallback error image } if (ENVIRONMENT === 'production') { $host = '//img.pickartyou.com/'; } else { $host = '/uploads/'; } if (!empty($type)) { $host .= $type . '/'; } return $host . $filename; } public static function generate_static_url($filename) { $full_file_path = __DIR__ . '/../../static/' . $filename; if (file_exists($full_file_path)) { $filename .= '?' . filemtime($full_file_path); } if (ENVIRONMENT === 'production') { $host = '//static.pickartyou.com/'; } else { $host = '../../static/'; } return $host . $filename; } }
<?php class UrlGenerator { public static function generate_thumb_url($filename, $type = '', $size = '_thumb') { if (empty($filename)) { return ''; // Fallback error image } if (ENVIRONMENT === 'production') { $host = 'http://img.pickartyou.com/'; } else { $host = '/uploads/'; } if (!empty($type)) { $host .= $type . '/'; } $path_parts = pathinfo($filename); if (!isset($path_parts['extension'])) { return ''; // Fallback error image } return $host . $path_parts['filename'] . $size . '.' . $path_parts['extension']; } public static function generate_original_image_url($filename, $type = '') { if (empty($filename)) { return ''; // Fallback error image } if (ENVIRONMENT === 'production') { $host = 'http://img.pickartyou.com/'; } else { $host = '/uploads/'; } if (!empty($type)) { $host .= $type . '/'; } return $host . $filename; } public static function generate_static_url($filename) { $full_file_path = __DIR__ . '/../../static/' . $filename; if (file_exists($full_file_path)) { $filename .= '?' . filemtime($full_file_path); } if (ENVIRONMENT === 'production') { $host = 'http://static.pickartyou.com/'; } else { $host = '../../static/'; } return $host . $filename; } }
Remove "html" from the inputFormats list All HTML is not reshape.
'use strict' const reshape = require('reshape') exports.name = 'reshape' exports.outputFormat = 'html' exports.renderAsync = function (str, options, locals) { return new Promise((resolve, reject) => { const plugins = [] options = options || {} options.plugins = options.plugins || {} if (Array.isArray(options.plugins)) { for (const plugin of options.plugins) { if (typeof plugin === 'string') { // eslint-disable-next-line import/no-dynamic-require plugins.push(require(plugin)()) } else { plugins.push(plugin) } } } else if (typeof options.plugins === 'object') { for (const key in options.plugins) { if ({}.hasOwnProperty.call(options.plugins, key)) { const settings = options.plugins[key] || {} // eslint-disable-next-line import/no-dynamic-require plugins.push(require(key)(settings)) } } } if (typeof options.parser === 'string') { // eslint-disable-next-line import/no-dynamic-require options.parser = require(options.parser) } const modifiedOptions = options modifiedOptions.plugins = plugins // Process with Reshape. reshape(modifiedOptions) .process(str) .then(result => { resolve(result.output(locals)) }, reject) }) }
'use strict' const reshape = require('reshape') exports.name = 'reshape' exports.inputFormats = ['reshape', 'html'] exports.outputFormat = 'html' exports.renderAsync = function (str, options, locals) { return new Promise((resolve, reject) => { const plugins = [] options = options || {} options.plugins = options.plugins || {} if (Array.isArray(options.plugins)) { for (const plugin of options.plugins) { if (typeof plugin === 'string') { // eslint-disable-next-line import/no-dynamic-require plugins.push(require(plugin)()) } else { plugins.push(plugin) } } } else if (typeof options.plugins === 'object') { for (const key in options.plugins) { if ({}.hasOwnProperty.call(options.plugins, key)) { const settings = options.plugins[key] || {} // eslint-disable-next-line import/no-dynamic-require plugins.push(require(key)(settings)) } } } if (typeof options.parser === 'string') { // eslint-disable-next-line import/no-dynamic-require options.parser = require(options.parser) } const modifiedOptions = options modifiedOptions.plugins = plugins // Process with Reshape. reshape(modifiedOptions) .process(str) .then(result => { resolve(result.output(locals)) }, reject) }) }
Fix ES index setup in XFormManagementTest
from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest, QueryDict from django.test import TestCase, Client from corehq.apps.data_interfaces.views import XFormManagementView from corehq.apps.domain.shortcuts import create_domain from corehq.apps.users.models import WebUser from corehq.pillows.mappings.xform_mapping import XFORM_INDEX_INFO from corehq.util.elastic import reset_es_index class XFormManagementTest(TestCase): @classmethod def setUpClass(cls): reset_es_index(XFORM_INDEX_INFO) cls.domain = create_domain('xform-management-test') cls.web_user = WebUser.create('xform-management-test', 'test', 'test', is_superuser=True) Client().force_login(cls.web_user.get_django_user()) @classmethod def tearDownClass(cls): cls.web_user.delete() cls.domain.delete() def test_get_xform_ids__sanity_check(self): # This helper has to mock a request in a brittle way. # If permissions are wrong, instead of returning a list, # it will return an HttpResponse containing the permission error. # This can break when permissions change. # So, just test that we aren't hitting that situation and that the response is a list. request = HttpRequest() request.POST = QueryDict('select_all=') request.couch_user = self.web_user SessionMiddleware().process_request(request) view = XFormManagementView() view.args = (self.domain.name,) view.request = request assert isinstance(view.get_xform_ids(request), list)
from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest, QueryDict from django.test import TestCase, Client from corehq.apps.data_interfaces.views import XFormManagementView from corehq.apps.domain.shortcuts import create_domain from corehq.apps.users.models import WebUser class XFormManagementTest(TestCase): @classmethod def setUpClass(cls): cls.domain = create_domain('xform-management-test') cls.web_user = WebUser.create('xform-management-test', 'test', 'test', is_superuser=True) Client().force_login(cls.web_user.get_django_user()) @classmethod def tearDownClass(cls): cls.web_user.delete() cls.domain.delete() def test_get_xform_ids__sanity_check(self): # This helper has to mock a request in a brittle way. # If permissions are wrong, instead of returning a list, # it will return an HttpResponse containing the permission error. # This can break when permissions change. # So, just test that we aren't hitting that situation and that the response is a list. request = HttpRequest() request.POST = QueryDict('select_all=') request.couch_user = self.web_user SessionMiddleware().process_request(request) view = XFormManagementView() view.args = (self.domain.name,) view.request = request assert isinstance(view.get_xform_ids(request), list)
Fix path for collection entrypoint Signed-off-by: Julius Härtl <[email protected]>
const path = require('path'); const { VueLoaderPlugin } = require('vue-loader'); module.exports = { entry: { deck: path.join(__dirname, 'src', 'main.js'), collections: path.join(__dirname, 'src', 'init-collections.js'), }, output: { filename: '[name].js', path: __dirname + '/js', publicPath: '/js/', jsonpFunction: 'webpackJsonpOCADeck' }, module: { rules: [ { test: /\.css$/, use: ['vue-style-loader', 'css-loader'] }, { test: /\.scss$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ] }, { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, plugins: [new VueLoaderPlugin()], resolve: { alias: { vue$: 'vue/dist/vue.esm.js' }, extensions: ['*', '.js', '.vue', '.json'] } };
const path = require('path'); const { VueLoaderPlugin } = require('vue-loader'); module.exports = { entry: { deck: path.join(__dirname, 'src', 'main.js'), collections: ['./src/init-collections.js'] }, output: { filename: '[name].js', path: __dirname + '/js', publicPath: '/js/', jsonpFunction: 'webpackJsonpOCADeck' }, module: { rules: [ { test: /\.css$/, use: ['vue-style-loader', 'css-loader'] }, { test: /\.scss$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ] }, { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, plugins: [new VueLoaderPlugin()], resolve: { alias: { vue$: 'vue/dist/vue.esm.js' }, extensions: ['*', '.js', '.vue', '.json'] } };
Use filesystem for all file access.
<?php namespace Studio\Creator; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use Studio\Parts\PartInterface; use Studio\Package; use Studio\Shell\TaskRunner; class SkeletonCreator implements CreatorInterface { /** * @var string */ protected $path; /** * @var Filesystem */ protected $filesystem; /** * @var TaskRunner */ protected $shell; /** * @var PartInterface[] */ protected $parts; public function __construct($path, TaskRunner $shell) { $this->path = $path; $this->filesystem = new Filesystem(new Local($path)); $this->shell = $shell; } public function addPart(PartInterface $part) { $this->parts[] = $part; } /** * Create the new package. * * @return \Studio\Package */ public function create() { $this->initPackage(); $this->installParts(); return Package::fromFolder($this->path); } protected function initPackage() { $this->shell->process('composer init', $this->path) ->run(); } protected function installParts() { $config = json_decode($this->filesystem->read('composer.json')); foreach ($this->parts as $part) { $part->setupPackage($config, $this->filesystem); } $this->filesystem->write('composer.json', json_encode($config, JSON_PRETTY_PRINT)); } }
<?php namespace Studio\Creator; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use Studio\Parts\PartInterface; use Studio\Package; use Studio\Shell\TaskRunner; class SkeletonCreator implements CreatorInterface { /** * @var string */ protected $path; /** * @var Filesystem */ protected $filesystem; /** * @var TaskRunner */ protected $shell; /** * @var PartInterface[] */ protected $parts; public function __construct($path, TaskRunner $shell) { $this->path = $path; $this->filesystem = new Filesystem(new Local($path)); $this->shell = $shell; } public function addPart(PartInterface $part) { $this->parts[] = $part; } /** * Create the new package. * * @return \Studio\Package */ public function create() { $this->initPackage(); $this->installParts(); return Package::fromFolder($this->path); } protected function initPackage() { $this->shell->process('composer init', $this->path) ->run(); } protected function installParts() { $composerFile = $this->path . '/composer.json'; $config = json_decode(file_get_contents($composerFile)); foreach ($this->parts as $part) { $part->setupPackage($config, $this->filesystem); } file_put_contents($composerFile, json_encode($config, JSON_PRETTY_PRINT)); } }