text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add Encoding JSON in Java Example
/** * @file JSONEncodeDemo.java * @author Valery Samovich * @version 1.0.0 * @date 11/19/2014 * * Following example to encode JSON Object using Java JSONObject with is * subclass of java.util.HashMap. */ package com.valerysamovich.java.advanced.json; import org.json.simple.JSONObject; public class JSONEncodeDemo { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); System.out.print(obj); } }
/** * @file JSONEncodeDemo.java * @author Valery Samovich * @version 1.0.0 * @date 11/19/2014 * * Following example to encode JSON Object using Java JSONObject with is * subclass of java.util.HashMap. */ package com.valerysamovich.java.advanced.json; import org.json.simple.JSONObject; public class JSONEncodeDemo { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); System.out.print(obj); } }
Fix failing test w/ incomplete regex
import re def test_tmp_file_is_gone(host): tmpfile = '/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress' f = host.file(tmpfile) assert not f.exists def test_command_line_tools_dir(host): f = host.file('/Library/Developer/CommandLineTools') assert f.exists assert f.is_directory assert f.user == 'root' assert f.group == 'admin' assert f.mode == 0o755 def test_clt_package_metadata(host): c = host.command('pkgutil --pkg-info=com.apple.pkg.CLTools_Executables') assert c.rc == 0 def test_git_is_useable(host): c = host.command('/usr/bin/git --version') assert c.rc == 0 assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+(\.\d+)*\)$', c.stdout)
import re def test_tmp_file_is_gone(host): tmpfile = '/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress' f = host.file(tmpfile) assert not f.exists def test_command_line_tools_dir(host): f = host.file('/Library/Developer/CommandLineTools') assert f.exists assert f.is_directory assert f.user == 'root' assert f.group == 'admin' assert f.mode == 0o755 def test_clt_package_metadata(host): c = host.command('pkgutil --pkg-info=com.apple.pkg.CLTools_Executables') assert c.rc == 0 def test_git_is_useable(host): c = host.command('/usr/bin/git --version') assert c.rc == 0 assert re.match('^git version \d+(.\d+)* \(Apple Git-\d+\)$', c.stdout)
Add ability to disable frame evaluation
import os import sys IS_PY36_OR_OLDER = False if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3: IS_PY36_OR_OLDER = True set_frame_eval = None stop_frame_eval = None use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None) if use_frame_eval == 'NO': frame_eval_func, stop_frame_eval = None, None else: if IS_PY36_OR_OLDER: try: from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval except ImportError: from _pydev_bundle.pydev_monkey import log_error_once dirname = os.path.dirname(__file__) log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % ( sys.executable, os.path.join(dirname, 'setup.py')))
import os import sys IS_PY36_OR_OLDER = False if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3: IS_PY36_OR_OLDER = True set_frame_eval = None stop_frame_eval = None if IS_PY36_OR_OLDER: try: from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval except ImportError: from _pydev_bundle.pydev_monkey import log_error_once dirname = os.path.dirname(__file__) log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % ( sys.executable, os.path.join(dirname, 'setup.py')))
Make HTTP01Responder's resource be at the token's path * Not /.well-known/acme-challenge/<token>, just /<token> * Use twisted.web.static.Data as the child resource
""" ``http-01`` challenge implementation. """ from twisted.web.resource import Resource from twisted.web.static import Data from zope.interface import implementer from txacme.interfaces import IResponder @implementer(IResponder) class HTTP01Responder(object): """ An ``http-01`` challenge responder for txsni. """ challenge_type = u'http-01' def __init__(self): self.resource = Resource() def start_responding(self, server_name, challenge, response): """ Add the child resource. """ self.resource.putChild( challenge.encode('token'), Data(self.response.key_authorization.encode(), 'text/plain')) def stop_responding(self, server_name, challenge, response): """ Remove the child resource. """ encoded_token = challenge.encode('token') if self.resource.getStaticEntity(encoded_token) is not None: self.resource.delEntity(encoded_token) __all__ = ['HTTP01Responder']
""" ``http-01`` challenge implementation. """ from twisted.web.http import OK from twisted.web.resource import Resource from zope.interface import implementer from txacme.interfaces import IResponder @implementer(IResponder) class HTTP01Responder(object): """ An ``http-01`` challenge responder for txsni. """ challenge_type = u'http-01' def __init__(self): self.resource = Resource() def start_responding(self, server_name, challenge, response): """ Add the child resource. """ self.resource.putChild(challenge.path, _HTTP01Resource(response)) def stop_responding(self, server_name, challenge, response): """ Remove the child resource. """ if self.resource.getStaticEntity(challenge.path) is not None: self.resource.delEntity(challenge.path) class _HTTP01Resource(Resource): isLeaf = True def __init__(self, response): self.response = response def render_GET(self, request): request.setResponseCode(OK) return self.response.key_authorization.encode() __all__ = ['HTTP01Responder']
Allow a list of static values.
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This will set a field on a document with a value * * @author kwatters * */ public class SetStaticFieldValue extends AbstractStage { private String fieldName = null; private String value = null; private List<String> values = null; @Override public void startStage(StageConfiguration config) { if (config != null) { fieldName = config.getStringParam("fieldName"); value = config.getStringParam("value"); values = config.getListParam("values"); } } @Override public List<Document> processDocument(Document doc) { if (values != null) { for (String value : values) { doc.addToField(fieldName, value); } } else { doc.addToField(fieldName, value); } return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // Only required if this stage does any batching. NO-OP here. } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This will set a field on a document with a value * * @author kwatters * */ public class SetStaticFieldValue extends AbstractStage { private String fieldName = null; private String value = null; @Override public void startStage(StageConfiguration config) { if (config != null) { fieldName = config.getStringParam("fieldName"); value = config.getStringParam("value"); } } @Override public List<Document> processDocument(Document doc) { doc.addToField(fieldName, value); return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // Only required if this stage does any batching. NO-OP here. } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
Check config for jukebox mode
<?php namespace App\Listeners; use App\Events\SomeEvent; use App\Events\SongChanged; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class SongChangedEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SongChanged $event) { // //\Log::alert('song change event fired'); echo "song change event fired" . PHP_EOL; if(($event->status['nextsongid'] == 0) && (config('jukebox.jukebox_mode')) ){ //todo: queue song from playlist } } }
<?php namespace App\Listeners; use App\Events\SomeEvent; use App\Events\SongChanged; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class SongChangedEventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SongChanged $event) { // //\Log::alert('song change event fired'); echo "song change event fired" . PHP_EOL; if(($event->status['nextsongid'] == 0) && (Config::get('jukeboxMode')) ){ //todo: queue song from playlist } } }
Change some comments as documentation
# Script to change the UID of Users # # Author: Christoph Stoettner # E-Mail: christoph.stoettner@stoeps.de # # example: wsadmin.sh -lang jython -f changeUID.py file.csv # # Format of CSV-File: # uid;mailaddress # don't mask strings with " # import sys import os # Check OS on windows .strip('\n') is not required # Import Connections Admin Commands for Profiles execfile( "profilesAdmin.py" ) print "\nReading from file: " + sys.argv[0] myfile = open( sys.argv[1], 'r' ) for line in myfile.readlines(): if( ";" in line ) : data = line.split( ";" ) print "Working on user " + data[1] email = data[1].strip() uid = data[0].strip() ProfilesService.updateUser( str( email ), uid = str( uid ) ) ProfilesService.publishUserData( email ) print '\nDONE \n'
# Script to change the UID of Users # # Author: Christoph Stoettner # E-Mail: christoph.stoettner@stoeps.de # # example: wsadmin.sh -lang jython -f changeUID.py file.csv # # Format of CSV-File: # uid;mailaddress # import sys import os # Check OS on windows .strip('\n') is not required # Import Connections Admin Commands for Profiles execfile( "profilesAdmin.py" ) print "\nReading from file: " + sys.argv[0] myfile = open( sys.argv[1], 'r' ) for line in myfile.readlines(): if( ";" in line ) : data = line.split( ";" ) print "Working on user " + data[1] email = data[1].strip() uid = data[0].strip() ProfilesService.updateUser( str( email ), uid = str( uid ) ) ProfilesService.publishUserData( email ) print '\nDONE \n'
BB-1505: Check performance - run if sequences supported
<?php namespace Oro\Bundle\DashboardBundle\Migrations\Schema\v1_7; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Extension\DatabasePlatformAwareInterface; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroDashboardBundle implements Migration, DatabasePlatformAwareInterface { /** * @var AbstractPlatform */ protected $platform; /** * {@inheritdoc} */ public function setDatabasePlatform(AbstractPlatform $platform) { $this->platform = $platform; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { /** * After v1_3 migration * Undefined table: 7 ERROR: relation "oro_dashboard_active_id_seq" does not exist */ if ($this->platform->supportsSequences()) { $queries->addPostQuery( 'ALTER SEQUENCE IF EXISTS oro_dashboard_active_copy_id_seq RENAME TO oro_dashboard_active_id_seq;' ); } } }
<?php namespace Oro\Bundle\DashboardBundle\Migrations\Schema\v1_7; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroDashboardBundle implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { /** * After v1_3 migration * Undefined table: 7 ERROR: relation "oro_dashboard_active_id_seq" does not exist */ $queries->addPostQuery( 'ALTER SEQUENCE IF EXISTS oro_dashboard_active_copy_id_seq RENAME TO oro_dashboard_active_id_seq;' ); } }
Add send_message option to CheckRequirements
package com.elmakers.mine.bukkit.action.builtin; import java.util.ArrayList; import java.util.Collection; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.action.CheckAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.requirements.Requirement; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; public class CheckRequirementsAction extends CheckAction { private Collection<Requirement> requirements; private boolean sendMessage; @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); sendMessage = parameters.getBoolean("send_message"); requirements = new ArrayList<>(); Collection<ConfigurationSection> requirementConfigurations = ConfigurationUtils.getNodeList(parameters, "requirements"); if (requirementConfigurations != null) { for (ConfigurationSection requirementConfiguration : requirementConfigurations) { requirements.add(new Requirement(requirementConfiguration)); } } } @Override protected boolean isAllowed(CastContext context) { String message = context.getController().checkRequirements(context, requirements); if (sendMessage && message != null) { context.getMage().sendMessage(message); } return message == null; } }
package com.elmakers.mine.bukkit.action.builtin; import java.util.ArrayList; import java.util.Collection; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.action.CheckAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.requirements.Requirement; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; public class CheckRequirementsAction extends CheckAction { private Collection<Requirement> requirements; @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); requirements = new ArrayList<>(); Collection<ConfigurationSection> requirementConfigurations = ConfigurationUtils.getNodeList(parameters, "requirements"); if (requirementConfigurations != null) { for (ConfigurationSection requirementConfiguration : requirementConfigurations) { requirements.add(new Requirement(requirementConfiguration)); } } } @Override protected boolean isAllowed(CastContext context) { return context.getController().checkRequirements(context, requirements) == null; } }
:bug: Fix the inaccessible pages within the involvement package
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.conf.urls import include, url from search import views as search_views from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls urlpatterns = [ url(r'', include('involvement.urls')), # Needs to be imported before wagtail admin url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^accounts/', include('members.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: url(r'', include(wagtail_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT )
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.conf.urls import include, url from search import views as search_views from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls urlpatterns = [ url(r'^admin/', include(wagtailadmin_urls)), url(r'', include('involvement.urls')), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^accounts/', include('members.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: url(r'', include(wagtail_urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT )
Correct representation of floats and uuids
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, float): return '%.14f' % value elif isinstance(value, UUID): return '{%s}' % str(value).upper() elif value is None: return '-' else: return str(value) def encode(lists, indent=2, level=0): if indent == 0: raise ValueError('Indent should be present') result = '<' for i, item in enumerate(lists): if not isinstance(item, list): raise TypeError('%r is not RPP serializable' % item) if i > 0: result += ' ' * (level + 1) * indent if all(not isinstance(x, list) for x in item): name, values = item[0].upper(), item[1:] strvalues = map(tostr, values) result += ' '.join([name] + strvalues) else: result += encode(item, level=(level + 1)) result += '\n' if indent else ' ' result += (' ' * level * indent) + '>' return result
from uuid import UUID from scanner import Symbol def tostr(value): if isinstance(value, Symbol): return str(value) elif isinstance(value, str): return '"%s"' % value elif isinstance(value, UUID): return '{%s}' % value elif value is None: return '-' else: return str(value) def encode(lists, indent=2, level=0): result = '<' for i, item in enumerate(lists): if not isinstance(item, list): raise TypeError("%r is not RPP serializable" % item) if i > 0: result += ' ' * (level + 1) * indent if all(not isinstance(x, list) for x in item): name, values = item[0].upper(), item[1:] strvalues = map(tostr, values) result += ' '.join([name] + strvalues) else: result += encode(item, level=(level + 1)) result += '\n' if indent else ' ' result += (' ' * level * indent) + '>' return result
Update momentjs locale globally when language is switched.
// @ngInject export default class LanguageUtilsService { // @ngInject constructor($translate, $http, ENV) { this.$translate = $translate; this.$http = $http; this.ENV = ENV; } getCurrentLanguage() { return this.current; } setCurrentLanguage(language) { this.current = language; this.$translate.use(language.code); moment.locale(language.code); this.$http.defaults.headers.common['Accept-Language'] = language.code; } checkLanguage() { // Check if current language is listed in choices and // switch to default language if current choice is invalid. const key = this.$translate.storageKey(); const storage = this.$translate.storage(); const code = storage.get(key); const current = this.findLanguageByCode(code) || this.findLanguageByCode(this.ENV.defaultLanguage); this.setCurrentLanguage(current); } findLanguageByCode(code) { if (!code) { return; } return this.getChoices().filter(language => language.code === code)[0]; } getChoices() { return this.ENV.languageChoices; } }
// @ngInject export default class LanguageUtilsService { // @ngInject constructor($translate, $http, ENV) { this.$translate = $translate; this.$http = $http; this.ENV = ENV; } getCurrentLanguage() { return this.current; } setCurrentLanguage(language) { this.current = language; this.$translate.use(language.code); this.$http.defaults.headers.common['Accept-Language'] = language.code; } checkLanguage() { // Check if current language is listed in choices and // switch to default language if current choice is invalid. const key = this.$translate.storageKey(); const storage = this.$translate.storage(); const code = storage.get(key); const current = this.findLanguageByCode(code) || this.findLanguageByCode(this.ENV.defaultLanguage); this.setCurrentLanguage(current); } findLanguageByCode(code) { if (!code) { return; } return this.getChoices().filter(language => language.code === code)[0]; } getChoices() { return this.ENV.languageChoices; } }
RUN-316: Move magento extensions into a dedicated directory
#!/usr/bin/env php <?php use LizardsAndPumpkins\MagentoConnector\Api\Api; require __DIR__ . '/vendor/autoload.php'; require 'app/Mage.php'; Mage::app(); class PollsExportQueue { private static $sleepMicroSeconds = 500000; private static $iterationsUntilExit = 200; public static function run() { $iteration = 0; do { /** @var LizardsAndPumpkins_MagentoConnector_Model_Export_CatalogExporter $exporter */ $exporter = Mage::getModel('lizardsAndPumpkins_magentoconnector/export_catalogExporter'); $filename = $exporter->exportProductsInQueue(); if ($exporter->wasSomethingExported()) { sleep(10); $apiUrl = Mage::getStoreConfig('lizardsAndPumpkins/magentoconnector/api_url'); (new Api($apiUrl))->triggerProductImport($filename); } usleep(self::$sleepMicroSeconds); } while ($iteration++ < self::$iterationsUntilExit); } } PollsExportQueue::run();
#!/usr/bin/env php <?php use LizardsAndPumpkins\MagentoConnector\Api\Api; require __DIR__ . '/vendor/autoload.php'; require 'app/Mage.php'; Mage::app(); class PollsExportQueue { private static $sleepMicroSeconds = 500000; private static $iterationsUntilExit = 200; public static function run() { $iteration = 0; do { /** @var LizardsAndPumpkins_MagentoConnector_Model_Export_CatalogExporter $exporter */ $exporter = Mage::getModel('lizardsAndPumpkins_magentoconnector/export_catalogExporter'); $filename = $exporter->exportProductsInQueue(); if ($exporter->wasSomethingExported()) { $apiUrl = Mage::getStoreConfig('lizardsAndPumpkins/magentoconnector/api_url'); (new Api($apiUrl))->triggerProductImport($filename); } usleep(self::$sleepMicroSeconds); } while ($iteration++ < self::$iterationsUntilExit); } } PollsExportQueue::run();
Add exception handling for FileExistsError
import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `%s`', path) def create_path(path): try: os.mkdir(path) except FileExistsError: pass except OSError as e: logger.warning('Could not create path `%s`, exception %s', path, e) def get_tmp_path(path): return os.path.join('/tmp', path) def create_tmp_dir(dir_name): create_path(get_tmp_path(dir_name)) def delete_tmp_dir(dir_name): delete_path(get_tmp_path(dir_name)) def copy_to_tmp_dir(path, dir_name): tmp_path = get_tmp_path(dir_name) if os.path.exists(tmp_path): return tmp_path try: shutil.copytree(path, tmp_path) except FileExistsError as e: logger.warning('Path already exists `%s`, exception %s', path, e) return tmp_path
import logging import os import shutil logger = logging.getLogger('polyaxon.libs.paths') def delete_path(path): if not os.path.exists(path): return try: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) except OSError: logger.warning('Could not delete path `%s`', path) def create_path(path): try: os.mkdir(path) except FileExistsError: pass except OSError as e: logger.warning('Could not create path `%s`, exception %s', path, e) def get_tmp_path(path): return os.path.join('/tmp', path) def create_tmp_dir(dir_name): create_path(get_tmp_path(dir_name)) def delete_tmp_dir(dir_name): delete_path(get_tmp_path(dir_name)) def copy_to_tmp_dir(path, dir_name): tmp_path = get_tmp_path(dir_name) if os.path.exists(tmp_path): return tmp_path shutil.copytree(path, tmp_path) return tmp_path
Set script permissions during install
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup import os setup( name='openhim-report-tasks', version='0.1.0', author='Jembi Health Systems NPC', packages=['openhimtasks'], description='OpenHIM Report and Alerting Tasks', long_description=open('README.md').read(), install_requires=[ "mysql-python", ], data_files=[('/etc/cron.daily', ['openhim_reports.sh']), ('/etc/cron.hourly', ['openhim_alerts.sh']), ('/etc', ['openhim-report-tasks.conf']), ], ) # Setup /etc source conf files with open('/etc/openhim-report-tasks.source', 'w') as src: src.write(os.getcwd()) # Cron script permissions os.chmod('/etc/cron.daily/openhim_reports.sh', 0755) os.chmod('/etc/cron.hourly/openhim_alerts.sh', 0755)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup import os setup( name='openhim-report-tasks', version='0.1.0', author='Jembi Health Systems NPC', packages=['openhimtasks'], description='OpenHIM Report and Alerting Tasks', long_description=open('README.md').read(), install_requires=[ "mysql-python", ], data_files=[('/etc/cron.daily', ['openhim_reports.sh']), ('/etc/cron.hourly', ['openhim_alerts.sh']), ('/etc', ['openhim-report-tasks.conf']), ], ) # Setup /etc source conf files with open('/etc/openhim-report-tasks.source', 'w') as src: src.write(os.getcwd())
Update static files example for v6
package main import ( "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" "gopkg.in/kataras/iris.v6/adaptors/view" ) type page struct { Title string } func main() { app := iris.New() app.Adapt( iris.DevLogger(), httprouter.New(), view.HTML("./templates", ".html"), ) app.OnError(iris.StatusForbidden, func(ctx *iris.Context) { ctx.HTML(iris.StatusForbidden, "<h1> You are not allowed here </h1>") }) // http://localhost:8080/css/bootstrap.min.css app.StaticWeb("/css", "./resources/css") // http://localhost:8080/js/jquery-2.1.1.js app.StaticWeb("/js", "./resources/js") app.Get("/", func(ctx *iris.Context) { ctx.MustRender("something.html", page{Title: "Home"}) }) app.Listen("localhost:8080") }
package main import ( "github.com/kataras/go-template/html" "gopkg.in/kataras/iris.v6" ) type page struct { Title string } func main() { iris.UseTemplate(html.New()).Directory("./templates/web/default", ".html") iris.OnError(iris.StatusForbidden, func(ctx *iris.Context) { ctx.HTML(iris.StatusForbidden, "<h1> You are not allowed here </h1>") }) // http://localhost:8080/css/bootstrap.min.css iris.StaticWeb("/css", "./resources/css") // http://localhost:8080/js/jquery-2.1.1.js iris.StaticWeb("/js", "./resources/js") iris.Get("/", func(ctx *iris.Context) { ctx.MustRender("something.html", page{Title: "Home"}) }) iris.Listen(":8080") }
Put tests_require into extras_require also
from setuptools import setup, find_packages try: import nose.commands extra_args = dict( cmdclass={'test': nose.commands.nosetests}, ) except ImportError: extra_args = dict() # TODO: would this work? (is the file included in the dist?) #tests_require = [l.strip() for l in open('test-requirements.txt').readlines()] tests_require = ['mock'] setup( name='dear_astrid', version='0.1.0', author='Randy Stauner', author_email='randy@magnificent-tears.com', packages=find_packages(), #['dear_astrid', 'dear_astrid.test'], #scripts=['bin/dear_astrid.py'], url='http://github.com/rwstauner/dear_astrid/', license='MIT', description='Migrate tasks from Astrid backup xml', long_description=open('README.rst').read(), install_requires=[ 'pyrtm>=0.4.1', ], setup_requires=['nose>=1.0'], tests_require=tests_require, extras_require={ 'test': tests_require, }, **extra_args )
from setuptools import setup, find_packages try: import nose.commands extra_args = dict( cmdclass={'test': nose.commands.nosetests}, ) except ImportError: extra_args = dict() setup( name='dear_astrid', version='0.1.0', author='Randy Stauner', author_email='randy@magnificent-tears.com', packages=find_packages(), #['dear_astrid', 'dear_astrid.test'], #scripts=['bin/dear_astrid.py'], url='http://github.com/rwstauner/dear_astrid/', license='MIT', description='Migrate tasks from Astrid backup xml', long_description=open('README.rst').read(), install_requires=[ 'pyrtm>=0.4.1', ], setup_requires=['nose>=1.0'], tests_require=[ 'nose', 'mock', ], **extra_args )
Make min height = 300px
import React from 'react' import { inject, observer } from 'mobx-react' import Window from './Window' import DragPreview from './DragPreview' @inject('windowStore') @observer export default class App extends React.Component { resize = () => { const bottom = Math.max( ...Object.values(this.refs).map( x => x.getBoundingClientRect().bottom ) ) const height = `${Math.max(bottom, 300)}px` document.getElementsByTagName('html')[0].style.height = height document.body.style.height = height } componentDidUpdate = this.resize componentDidMount = this.resize render () { const { windowStore: { windows } } = this.props const winList = windows.map((win) => ( <Window key={win.id} ref={win.id} containment={() => this.containment} dragPreview={() => this.dragPreview} {...win} /> )) return ( <div ref={(el) => { this.containment = el || this.containment }} style={{ overflow: 'auto', flex: '1 1 auto' }}> <DragPreview setDragPreview={(dragPreview) => { this.dragPreview = dragPreview }} /> {winList} </div> ) } }
import React from 'react' import { inject, observer } from 'mobx-react' import Window from './Window' import DragPreview from './DragPreview' @inject('windowStore') @observer export default class App extends React.Component { resize = () => { const bottom = Math.max( ...Object.values(this.refs).map( x => x.getBoundingClientRect().bottom ) ) const height = `${bottom}px` document.getElementsByTagName('html')[0].style.height = height document.body.style.height = height } componentDidUpdate = this.resize componentDidMount = this.resize render () { const { windowStore: { windows } } = this.props const winList = windows.map((win) => ( <Window key={win.id} ref={win.id} containment={() => this.containment} dragPreview={() => this.dragPreview} {...win} /> )) return ( <div ref={(el) => { this.containment = el || this.containment }} style={{ overflow: 'auto', flex: '1 1 auto' }}> <DragPreview setDragPreview={(dragPreview) => { this.dragPreview = dragPreview }} /> {winList} </div> ) } }
Disable autoreload in integration tests
import os import subprocess import pytest from chalice.utils import OSUtils CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.join(CURRENT_DIR, 'testapp') @pytest.fixture def local_app(tmpdir): temp_dir_path = str(tmpdir) OSUtils().copytree(PROJECT_DIR, temp_dir_path) old_dir = os.getcwd() try: os.chdir(temp_dir_path) yield temp_dir_path finally: os.chdir(old_dir) def test_stack_trace_printed_on_error(local_app): app_file = os.path.join(local_app, 'app.py') with open(app_file, 'w') as f: f.write( 'from chalice import Chalice\n' 'app = Chalice(app_name="test")\n' 'foobarbaz\n' ) p = subprocess.Popen(['chalice', 'local', '--no-autoreload'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.communicate()[1].decode('ascii') rc = p.returncode assert rc == 2 assert 'Traceback' in stderr assert 'foobarbaz' in stderr
import os import subprocess import pytest from chalice.utils import OSUtils CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.join(CURRENT_DIR, 'testapp') @pytest.fixture def local_app(tmpdir): temp_dir_path = str(tmpdir) OSUtils().copytree(PROJECT_DIR, temp_dir_path) old_dir = os.getcwd() try: os.chdir(temp_dir_path) yield temp_dir_path finally: os.chdir(old_dir) def test_stack_trace_printed_on_error(local_app): app_file = os.path.join(local_app, 'app.py') with open(app_file, 'w') as f: f.write( 'from chalice import Chalice\n' 'app = Chalice(app_name="test")\n' 'foobarbaz\n' ) p = subprocess.Popen(['chalice', 'local'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stderr = p.communicate()[1].decode('ascii') rc = p.returncode assert rc == 2 assert 'Traceback' in stderr assert 'foobarbaz' in stderr
Remove lingering reference to linked changelog.
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import subprocess import pkg_resources pkg_resources.require('jaraco.packaging>=2.0') pkg_resources.require('wheel') def before_upload(): BootstrapBookmark.add() def after_push(): BootstrapBookmark.push() files_with_versions = ( 'ez_setup.py', 'setuptools/version.py', ) # bdist_wheel must be included or pip will break dist_commands = 'sdist', 'bdist_wheel' test_info = "Travis-CI tests: http://travis-ci.org/#!/jaraco/setuptools" os.environ["SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES"] = "1" class BootstrapBookmark: name = 'bootstrap' @classmethod def add(cls): cmd = ['hg', 'bookmark', '-i', cls.name, '-f'] subprocess.Popen(cmd) @classmethod def push(cls): """ Push the bootstrap bookmark """ push_command = ['hg', 'push', '-B', cls.name] # don't use check_call here because mercurial will return a non-zero # code even if it succeeds at pushing the bookmark (because there are # no changesets to be pushed). !dm mercurial subprocess.call(push_command)
""" Setuptools is released using 'jaraco.packaging.release'. To make a release, install jaraco.packaging and run 'python -m jaraco.packaging.release' """ import os import subprocess import pkg_resources pkg_resources.require('jaraco.packaging>=2.0') pkg_resources.require('wheel') def before_upload(): BootstrapBookmark.add() def after_push(): os.remove('CHANGES (links).txt') BootstrapBookmark.push() files_with_versions = ( 'ez_setup.py', 'setuptools/version.py', ) # bdist_wheel must be included or pip will break dist_commands = 'sdist', 'bdist_wheel' test_info = "Travis-CI tests: http://travis-ci.org/#!/jaraco/setuptools" os.environ["SETUPTOOLS_INSTALL_WINDOWS_SPECIFIC_FILES"] = "1" class BootstrapBookmark: name = 'bootstrap' @classmethod def add(cls): cmd = ['hg', 'bookmark', '-i', cls.name, '-f'] subprocess.Popen(cmd) @classmethod def push(cls): """ Push the bootstrap bookmark """ push_command = ['hg', 'push', '-B', cls.name] # don't use check_call here because mercurial will return a non-zero # code even if it succeeds at pushing the bookmark (because there are # no changesets to be pushed). !dm mercurial subprocess.call(push_command)
Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
Switch icalendar event listing frontend to use event instances instead of events.
<?php /** * This is the output for an event listing in icalendar format. * @package UNL_UCBCN_Frontend */ foreach ($this->events as $e) { $out = array(); $out[] = 'BEGIN:VEVENT'; //$out[] = 'SEQUENCE:5'; if (isset($e->eventdatetime->starttime)) { $out[] = 'DTSTART;TZID=US/Central:'.date('Ymd\THis',strtotime($e->eventdatetime->starttime)); } $out[] = 'DTSTAMP:'.date('Ymd\THis',strtotime($e->event->datecreated)); $out[] = 'SUMMARY:'.strip_tags($e->event->title); $out[] = 'DESCRIPTION:'.strip_tags($e->event->description); //$out[] = 'URL:http://abc.com/pub/calendars/jsmith/mytime.ics'; //$out[] = 'UID:EC9439B1-FF65-11D6-9973-003065F99D04'; if (isset($eventdatetime->endtime)) { $out[] = 'DTEND;TZID=US/Central:'.date('Ymd\THis',strtotime($e->eventdatetime->endtime)); } $out[] = 'END:VEVENT'; echo implode("\n",$out)."\n"; } ?>
<?php /** * This is the output for an event listing in icalendar format. * @package UNL_UCBCN_Frontend */ foreach ($this->events as $e) { $eventdatetime = $e->getLink('id','eventdatetime','event_id'); $out = array(); $out[] = 'BEGIN:VEVENT'; //$out[] = 'SEQUENCE:5'; if (isset($eventdatetime->starttime)) { $out[] = 'DTSTART;TZID=US/Central:'.date('Ymd\THis',strtotime($eventdatetime->starttime)); } $out[] = 'DTSTAMP:'.date('Ymd\THis',strtotime($e->datecreated)); $out[] = 'SUMMARY:'.strip_tags($e->title); $out[] = 'DESCRIPTION:'.strip_tags($e->description); //$out[] = 'URL:http://abc.com/pub/calendars/jsmith/mytime.ics'; //$out[] = 'UID:EC9439B1-FF65-11D6-9973-003065F99D04'; if (isset($eventdatetime->endtime)) { $out[] = 'DTEND;TZID=US/Central:'.date('Ymd\THis',strtotime($eventdatetime->endtime)); } $out[] = 'END:VEVENT'; echo implode("\n",$out)."\n"; } ?>
Create username and password method
<?php require_once __DIR__ . '/login.php'; require_once __DIR__ . '/../lib/utils.php'; class LoginDoubleChecker extends RawDataContainer { static protected function requiredFieldSchema(): array { return [ 'login' => 'LoginInfo', 'db-query-set' => 'DatabaseQuerySet', ]; } public function verify(): void { if (!$this->checkAll()) throw SecurityException::permission(); } public function checkAll(): bool { return $this->checkLogin() && $this->checkPermission(); } public function checkLogin(): bool { [ 'cookie' => $cookie, 'session' => $session, 'login' => $login, 'db-query-set' => $dbQuerySet, ] = $this->getData(); return Login::checkLogin( $login->assign([ 'cookie' => $cookie, 'session' => $session, 'db-query-set' => $dbQuerySet, ])->getData() )->isLoggedIn(); } public function checkPermission(): bool { return $this->get('login')->isAdmin(); } public function username(): string { return $this->get('login')->username(); } public function password(): string { return $this->get('login')->password(); } } class SecurityException extends Exception { static public function permission(): self { return new static('Permission Denied'); } } ?>
<?php require_once __DIR__ . '/login.php'; require_once __DIR__ . '/../lib/utils.php'; class LoginDoubleChecker extends RawDataContainer { static protected function requiredFieldSchema(): array { return [ 'login' => 'LoginInfo', 'db-query-set' => 'DatabaseQuerySet', ]; } public function verify(): void { if (!$this->checkAll()) throw SecurityException::permission(); } public function checkAll(): bool { return $this->checkLogin() && $this->checkPermission(); } public function checkLogin(): bool { [ 'cookie' => $cookie, 'session' => $session, 'login' => $login, 'db-query-set' => $dbQuerySet, ] = $this->getData(); return Login::checkLogin( $login->assign([ 'cookie' => $cookie, 'session' => $session, 'db-query-set' => $dbQuerySet, ])->getData() )->isLoggedIn(); } public function checkPermission(): bool { return $this->get('login')->isAdmin(); } } class SecurityException extends Exception { static public function permission(): self { return new static('Permission Denied'); } } ?>
Remove the unused logger (for the wrong class), Luke!
package nl.vpro.poel.service; import nl.vpro.poel.domain.Group; import nl.vpro.poel.dto.GroupForm; import nl.vpro.poel.repository.GroupRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class GroupServiceImpl implements GroupService { private final GroupRepository groupRepository; @Autowired public GroupServiceImpl(GroupRepository groupRepository) { this.groupRepository = groupRepository; } @Override public Optional<Group> findById(Long id) { return Optional.ofNullable(groupRepository.findOne(id)); } @Override public Optional<Group> findByName(String name) { return Optional.ofNullable(groupRepository.findByName(name)); } @Override public List<Group> findAll() { return groupRepository.findAll(); } @Override public void setGroups(GroupForm groupForm) { // TODO save posted groups } }
package nl.vpro.poel.service; import nl.vpro.poel.domain.Group; import nl.vpro.poel.dto.GroupForm; import nl.vpro.poel.repository.GroupRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @Service public class GroupServiceImpl implements GroupService { private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class); private final GroupRepository groupRepository; @Autowired public GroupServiceImpl(GroupRepository groupRepository) { this.groupRepository = groupRepository; } @Override public Optional<Group> findById(Long id) { return Optional.ofNullable(groupRepository.findOne(id)); } @Override public Optional<Group> findByName(String name) { return Optional.ofNullable(groupRepository.findByName(name)); } @Override public List<Group> findAll() { return groupRepository.findAll(); } @Override public void setGroups(GroupForm groupForm) { // TODO save posted groups } }
Update the stats lists and add a 3D only version
# Licensed under an MIT open source license - see LICENSE ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] threeD_statistics_list = \ ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale", "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS", "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
# Licensed under an MIT open source license - see LICENSE ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break", "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"]
Fix test to use main unit test files standards The main unit test file tested action creators against `reducer().status` instead of the full state. There seems to be inconsistencies in the payload for action creators which caused these tests to fail. I have updated the tests to only check the status instead of the entire state.
import { describe } from 'riteway'; import dsm from '../dsm'; const SIGNED_OUT = 'signed_out'; const AUTHENTICATING = 'authenticating'; const actionStates = [ ['initialize', SIGNED_OUT, ['sign in', AUTHENTICATING // ['report error', 'error', // ['handle error', 'signed out'] // ], // ['sign-in success', 'signed in'] ] ] ]; const { reducer, actionCreators: { initialize, signIn } } = dsm({ component: 'user-authentication', description: 'authenticate user', actionStates }); describe('userAuthenticationReducer', async should => { { const {assert} = should('use "signed out" as initialized state'); assert({ given: '["initialize", "signed out", /*...*/', actual: reducer().status, expected: SIGNED_OUT }); } { const {assert} = should('transition into authenticating state'); const initialState = reducer(undefined, initialize()); assert({ given: 'signed out initial state & signIn action', actual: reducer(initialState, signIn()).status, expected: AUTHENTICATING }); } });
import { describe } from 'riteway'; import dsm from '../dsm'; const SIGNED_OUT = 'signed_out'; const AUTHENTICATING = 'authenticating'; const actionStates = [ ['initialize', SIGNED_OUT, ['sign in', AUTHENTICATING // ['report error', 'error', // ['handle error', 'signed out'] // ], // ['sign-in success', 'signed in'] ] ] ]; const { reducer, actionCreators: { initialize, signIn } } = dsm({ component: 'user-authentication', description: 'authenticate user', actionStates }); const createState = ({ status = SIGNED_OUT, payload = { type: 'empty' } } = {}) => ({ status, payload }); describe('userAuthenticationReducer', async should => { { const {assert} = should('use "signed out" as initialized state'); assert({ given: '["initialize", "signed out", /*...*/', actual: reducer(), expected: createState() }); } { const {assert} = should('transition into authenticating state'); const initialState = reducer(undefined, initialize()); assert({ given: 'signed out initial state & signIn action', actual: reducer(initialState, signIn()), expected: createState({ status: 'authenticating' }) }); } });
Rename default Grunt task to "build".
module.exports = function (grunt) { grunt.initConfig({ cssmin: { dist: { files: { 'dist/css/application.min.css': ['dist/css/application.min.css'] } } }, processhtml: { dist: { files: { 'dist/index.html': ['src/index.html'] } } }, uglify: { dist: { files: { 'dist/js/application.min.js': ['src/js/*.js'] } } }, uncss: { dist: { files: { 'dist/css/application.min.css': ['src/index.html'] } } } }); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-processhtml'); grunt.loadNpmTasks('grunt-uncss'); grunt.registerTask('build', [ 'uglify', 'uncss', 'cssmin', 'processhtml', ]); };
module.exports = function (grunt) { grunt.initConfig({ cssmin: { dist: { files: { 'dist/css/application.min.css': ['dist/css/application.min.css'] } } }, processhtml: { dist: { files: { 'dist/index.html': ['src/index.html'] } } }, uglify: { dist: { files: { 'dist/js/application.min.js': ['src/js/*.js'] } } }, uncss: { dist: { files: { 'dist/css/application.min.css': ['src/index.html'] } } } }); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-processhtml'); grunt.loadNpmTasks('grunt-uncss'); grunt.registerTask('default', [ 'uglify', 'uncss', 'cssmin', 'processhtml', ]); };
Remove state in favor of class variable
const React = require('react'); const { getFocusableNodesInElement, reconcileNodeArrays, setNodeAttributes } = require('utils/FocusManagement'); module.exports = class RestrictFocus extends React.Component { constructor (props, context) { super(props, context); this._wrapper = React.createRef(); this.focusableDOMNodes = []; } componentDidMount () { const focusableNodesInDocument = getFocusableNodesInElement(document); const focusableNodesInWrapper = getFocusableNodesInElement(this._wrapper); this.focusableDOMNodes = reconcileNodeArrays( focusableNodesInDocument, focusableNodesInWrapper ); this.focusableDOMNodes.forEach(node => { setNodeAttributes(node, { tabindex: -1, 'aria-hidden': true }); }); console.log('DidMount Test', { focusableNodesInDocument, focusableNodesInWrapper, focusableDOMNodes: this.focusableDOMNodes }); } componentWillUnmount () { this.focusableDOMNodes.forEach(node => { setNodeAttributes(node, { tabindex: 0, 'aria-hidden': false }); }); } render () { return ( <div ref={ref => this._wrapper = ref}> {this.props.children} </div> ); } };
const React = require('react'); const { getFocusableNodesInElement, reconcileNodeArrays, setNodeAttributes } = require('utils/FocusManagement'); module.exports = class RestrictFocus extends React.Component { constructor (props, context) { super(props, context); this._wrapper = React.createRef(); this.state = { focusableDOMNodes: [] }; } componentDidMount () { this.setState({ focusableDOMNodes: reconcileNodeArrays( getFocusableNodesInElement(document), getFocusableNodesInElement(this._wrapper.current)) }, () => { this.state.focusableDOMNodes.forEach(node => { setNodeAttributes(node, { tabindex: -1, 'aria-hidden': true }); }); }); } componentWillUnmount () { this.state.focusableDOMNodes.forEach(node => { setNodeAttributes(node, { tabindex: 0, 'aria-hidden': false }); }); } render () { return ( <div ref={ref => this._wrapper = ref}> {this.props.children} </div> ); } };
Improve reliablity of python article fetcher
# -*- coding: utf-8 -*- from newspaper import Article from goose import Goose import requests import json import sys article = Article(sys.argv[1]) article.download() if not article.html: r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' }) article.set_html(r.text) article.parse() article.nlp() published = '' if article.publish_date: published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S") # Get body with goose g = Goose() goose_article = g.extract(raw_html=article.html) body = goose_article.cleaned_text summary = goose_article.meta_description # Maybe use https://github.com/xiaoxu193/PyTeaser if not summary: summary = article.summary if not body or len(body) < len(article.text): body = article.text json_str = json.dumps({ 'author': ", ".join(article.authors), 'image': article.top_image, 'keywords': article.keywords, 'published': published, 'summary': summary, 'body': body, 'title': article.title, 'videos': article.movies }, sort_keys=True, ensure_ascii=False) print(json_str)
# -*- coding: utf-8 -*- from newspaper import Article from goose import Goose import json import sys article = Article(sys.argv[1]) article.download() article.parse() article.nlp() published = '' if article.publish_date: published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S") # Get body with goose g = Goose() goose_article = g.extract(raw_html=article.html) body = goose_article.cleaned_text summary = goose_article.meta_description # Maybe use https://github.com/xiaoxu193/PyTeaser if not summary: summary = article.summary if not body or len(body) < len(article.text): body = article.text json_str = json.dumps({ 'author': ", ".join(article.authors), 'image': article.top_image, 'keywords': article.keywords, 'published': published, 'summary': summary, 'body': body, 'title': article.title, 'videos': article.movies }, sort_keys=True, ensure_ascii=False) print(json_str)
WIP: Upgrade to Splash V2 Standards
<?php /* * This file is part of SplashSync Project. * * Copyright (C) 2015-2019 Splash Sync <www.splashsync.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Splash\Core\SplashCore as Splash; /** * Declare fatal Error Handler => Called in case of Script Exceptions */ function fatal_handler() { //====================================================================// // Read Last Error $error = error_get_last(); if (!$error) { return; } //====================================================================// // Fatal Error if (E_ERROR == $error["type"]) { //====================================================================// // Parse Error in Response. Splash::com()->fault($error); //====================================================================// // Process methods & Return the results. Splash::com()->handle(); //====================================================================// // Non Fatal Error } else { Splash::log()->war($error["message"]." on File ".$error["file"]." Line ".$error["line"]); } }
<?php /* * This file is part of SplashSync Project. * * Copyright (C) 2015-2019 Splash Sync <www.splashsync.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Splash\Core\SplashCore as Splash; /** * @abstract Declare fatal Error Handler => Called in case of Script Exceptions */ function fatal_handler() { //====================================================================// // Read Last Error $error = error_get_last(); if (!$error) { return; } //====================================================================// // Fatal Error if (E_ERROR == $error["type"]) { //====================================================================// // Parse Error in Response. Splash::com()->fault($error); //====================================================================// // Process methods & Return the results. Splash::com()->handle(); //====================================================================// // Non Fatal Error } else { Splash::log()->war($error["message"]." on File ".$error["file"]." Line ".$error["line"]); } }
Revert "Fix ignoring mock artifacts on release" This reverts commit e7bded655b8c336b132968930fa60d339be8115b.
#!/usr/bin/env node // This script removes the build artifacts of ignored contracts. const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const match = require('micromatch'); function readJSON (path) { return JSON.parse(fs.readFileSync(path)); } cp.spawnSync('npm', ['run', 'compile'], { stdio: 'inherit' }); const pkgFiles = readJSON('package.json').files; // Get only negated patterns. const ignorePatterns = pkgFiles .filter(pat => pat.startsWith('!')) // Remove the negation part. Makes micromatch usage more intuitive. .map(pat => pat.slice(1)); const ignorePatternsSubtrees = ignorePatterns // Add **/* to ignore all files contained in the directories. .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))); const artifactsDir = 'build/contracts'; let n = 0; for (const artifact of fs.readdirSync(artifactsDir)) { const fullArtifactPath = path.join(artifactsDir, artifact); const { sourcePath: fullSourcePath } = readJSON(fullArtifactPath); const sourcePath = path.relative('.', fullSourcePath); const ignore = match.any(sourcePath, ignorePatternsSubtrees); if (ignore) { fs.unlinkSync(fullArtifactPath); n += 1; } } console.error(`Removed ${n} mock artifacts`);
#!/usr/bin/env node // This script removes the build artifacts of ignored contracts. const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const match = require('micromatch'); function readJSON (path) { return JSON.parse(fs.readFileSync(path)); } cp.spawnSync('npm', ['run', 'compile'], { stdio: 'inherit' }); const pkgFiles = readJSON('package.json').files; // Get only negated patterns. const ignorePatterns = pkgFiles .filter(pat => pat.startsWith('!')) // Remove the negation part and initial slash. Makes micromatch usage more intuitive. .map(pat => pat.slice(1).replace(/^\//, '')); const ignorePatternsSubtrees = ignorePatterns // Add **/* to ignore all files contained in the directories. .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))); const artifactsDir = 'build/contracts'; let n = 0; for (const artifact of fs.readdirSync(artifactsDir)) { const fullArtifactPath = path.join(artifactsDir, artifact); const { sourcePath: fullSourcePath } = readJSON(fullArtifactPath); const sourcePath = path.relative('.', fullSourcePath); const ignore = match.any(sourcePath, ignorePatternsSubtrees); if (ignore) { fs.unlinkSync(fullArtifactPath); n += 1; } } console.error(`Removed ${n} mock artifacts`);
Adjust component to be used in an add-on `layout: layout` needs to be defined where layout is imported from the component's template
import Ember from 'ember'; import layout from '../templates/components/star-rating'; export default Ember.Component.extend({ tagName: 'div', classNames: ['rating-panel'], layout: layout, rating: 0, maxRating: 5, item: null, setAction: '', stars: Ember.computed('rating', 'maxRating', function() { var fullStars = this.starRange(1, this.get('rating'), 'full'); var emptyStars = this.starRange(this.get('rating') + 1, this.get('maxRating'), 'empty'); return fullStars.concat(emptyStars); }), starRange: function(start, end, type) { var starsData = []; for (var i = start; i <= end; i++) { starsData.push({ rating: i, full: type === 'full' }); } return starsData; }, actions: { set: function(newRating) { this.sendAction('setAction', { item: this.get('item'), rating: newRating }); } } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'div', classNames: ['rating-panel'], rating: 0, maxRating: 5, item: null, setAction: '', stars: Ember.computed('rating', 'maxRating', function() { var fullStars = this.starRange(1, this.get('rating'), 'full'); var emptyStars = this.starRange(this.get('rating') + 1, this.get('maxRating'), 'empty'); return fullStars.concat(emptyStars); }), starRange: function(start, end, type) { var starsData = []; for (var i = start; i <= end; i++) { starsData.push({ rating: i, full: type === 'full' }); } return starsData; }, actions: { set: function(newRating) { this.sendAction('setAction', { item: this.get('item'), rating: newRating }); } } });
Add functionality to get latest tviits
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View from django.utils.decorators import method_decorator from django.template import RequestContext, loader from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, render from tviit.models import Tviit, TviitForm from django.contrib.auth.models import User from user_profile.models import UserProfile class IndexView(View): @method_decorator(login_required(login_url='/login/')) def get(self, request, *args, **kwargs): template = loader.get_template('tviit/index.html') profile = UserProfile.objects.get(user=request.user) tviits = get_latest_tviits(profile) print(tviits) context = { 'profile': profile, 'tviit_form': TviitForm, 'tviits': tviits, } return HttpResponse(template.render(context, request)) # Get all the tviits, which aren't replies def get_latest_tviits(profile): follows = User.objects.filter(pk__in=profile.follows.all()) tviits = Tviit.objects.filter(sender__in=follows) return tviits
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View from django.utils.decorators import method_decorator from django.template import RequestContext, loader from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render_to_response, render from tviit.models import Tviit, TviitForm class IndexView(View): @method_decorator(login_required(login_url='/login/')) def get(self, request, *args, **kwargs): template = loader.get_template('tviit/index.html') context = { 'tviit_form': TviitForm, } return HttpResponse(template.render(context, request))
Cut down on the loading of families in the normal GenerateReactionsTest Change generateReactions input reactant to propyl
# Data sources for kinetics database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['R_Recombination'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='Propyl', reactive=True, structure=SMILES("CC[CH3]"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "Propyl": 1, }, terminationConversion={ 'Propyl': .99, }, terminationTime=(40,'s'), )
# Data sources for kinetics database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = 'default', #this section lists possible reaction families to find reactioons with kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List all species you want reactions between species( label='ethane', reactive=True, structure=SMILES("CC"), ) species( label='H', reactive=True, structure=SMILES("[H]"), ) species( label='butane', reactive=True, structure=SMILES("CCCC"), ) # you must list reactor conditions (though this may not effect the output) simpleReactor( temperature=(650,'K'), pressure=(10.0,'bar'), initialMoleFractions={ "ethane": 1, }, terminationConversion={ 'butane': .99, }, terminationTime=(40,'s'), )
Fix mistake in table name
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMentionsPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mentions_posts', function (Blueprint $table) { $table->integer('post_id')->unsigned(); $table->integer('mentions_id')->unsigned(); $table->primary(['post_id', 'mentions_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('mentions_posts'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMentionsPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mentionsPosts', function (Blueprint $table) { $table->integer('post_id')->unsigned(); $table->integer('mentions_id')->unsigned(); $table->primary(['post_id', 'mentions_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('mentionsPosts'); } }
Use "effects" or "effect" parameter for PlayEffects action
package com.elmakers.mine.bukkit.action.builtin; import com.elmakers.mine.bukkit.action.BaseSpellAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.SpellResult; import org.bukkit.configuration.ConfigurationSection; public class PlayEffectsAction extends BaseSpellAction { private String effectKey; @Override public SpellResult perform(CastContext context) { if (effectKey == null || effectKey.isEmpty()) { return SpellResult.FAIL; } context.playEffects(effectKey); return SpellResult.CAST; } @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); effectKey = parameters.getString("effect"); effectKey = parameters.getString("effects", effectKey); } }
package com.elmakers.mine.bukkit.action.builtin; import com.elmakers.mine.bukkit.action.BaseSpellAction; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.SpellResult; import org.bukkit.configuration.ConfigurationSection; public class PlayEffectsAction extends BaseSpellAction { private String effectKey; @Override public SpellResult perform(CastContext context) { if (effectKey == null || effectKey.isEmpty()) { return SpellResult.FAIL; } context.playEffects(effectKey); return SpellResult.CAST; } @Override public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); effectKey = parameters.getString("effect"); } }
Add T0 to the symbols available through the API
"""Top-level objects and functions offered by the Skyfield library. Importing this ``skyfield.api`` module causes Skyfield to load up the default JPL planetary ephemeris ``de421`` and create planet objects like ``earth`` and ``mars`` that are ready for your use. """ import de421 from datetime import datetime from .starlib import Star from .timelib import JulianDate, T0, now, utc from .units import Angle def build_ephemeris(): from .data.horizons import festoon_ephemeris from .jpllib import Ephemeris ephemeris = Ephemeris(de421) festoon_ephemeris(ephemeris) return ephemeris ephemeris = build_ephemeris() del build_ephemeris sun = ephemeris.sun mercury = ephemeris.mercury venus = ephemeris.venus earth = ephemeris.earth moon = ephemeris.moon mars = ephemeris.mars jupiter = ephemeris.jupiter saturn = ephemeris.saturn uranus = ephemeris.uranus neptune = ephemeris.neptune pluto = ephemeris.pluto eight_planets = (mercury, venus, earth, mars, jupiter, saturn, uranus, neptune) nine_planets = eight_planets + (pluto,)
"""Top-level objects and functions offered by the Skyfield library. Importing this ``skyfield.api`` module causes Skyfield to load up the default JPL planetary ephemeris ``de421`` and create planet objects like ``earth`` and ``mars`` that are ready for your use. """ import de421 from datetime import datetime from .starlib import Star from .timelib import JulianDate, now, utc from .units import Angle def build_ephemeris(): from .data.horizons import festoon_ephemeris from .jpllib import Ephemeris ephemeris = Ephemeris(de421) festoon_ephemeris(ephemeris) return ephemeris ephemeris = build_ephemeris() del build_ephemeris sun = ephemeris.sun mercury = ephemeris.mercury venus = ephemeris.venus earth = ephemeris.earth moon = ephemeris.moon mars = ephemeris.mars jupiter = ephemeris.jupiter saturn = ephemeris.saturn uranus = ephemeris.uranus neptune = ephemeris.neptune pluto = ephemeris.pluto eight_planets = (mercury, venus, earth, mars, jupiter, saturn, uranus, neptune) nine_planets = eight_planets + (pluto,)
Set the timeout back to 300 instead of 3000 which was used for debugging
// This alert was to test to see if the JavaScript was loaded :) // alert("Hello World") $(document).ready(function() { function myFunction() { let userinput = $("#searchbarid").val(); $.post('/searchajax',{data: userinput},(data, status) =>{ // This is working, the data is being console.log // console.log(data) console.log(typeof data) console.log ("I work") // document.write(data); $('.autocomplete').empty() $( ".autocomplete" ).append("<p>" + data + "</p>") }) } let AjaxCanRun = true $('#searchbarid').keyup(function(){ if (AjaxCanRun) { // console.log('Key was pressed') This Works fine :) // if (300 second have passed) { myFunction() // start counter /// If false, the fuction will not run, if true it will runn AjaxCanRun = false } // This set time out will make sure to see if the fuction can run setTimeout(function() { AjaxCanRun = true }, 300) }) })
// This alert was to test to see if the JavaScript was loaded :) // alert("Hello World") $(document).ready(function() { function myFunction() { let userinput = $("#searchbarid").val(); $.post('/searchajax',{data: userinput},(data, status) =>{ // This is working, the data is being console.log // console.log(data) console.log(typeof data) console.log ("I work") // document.write(data); $('.autocomplete').empty() $( ".autocomplete" ).append("<p>" + data + "</p>") }) } let AjaxCanRun = true $('#searchbarid').keyup(function(){ if (AjaxCanRun) { // console.log('Key was pressed') This Works fine :) // if (300 second have passed) { myFunction() // start counter /// If false, the fuction will not run, if true it will runn AjaxCanRun = false } // This set time out will make sure to see if the fuction can run setTimeout(function() { AjaxCanRun = true }, 3000) }) })
Improve the docs for ToolchainInfo and link to the main toolchains do? ?c page. Closes #8821. PiperOrigin-RevId: 257044964
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.platform; import com.google.devtools.build.lib.skylarkbuildapi.StructApi; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; /** Info object representing data about a specific toolchain. */ @SkylarkModule( name = "ToolchainInfo", doc = "Provider which allows rule-specific toolchains to communicate data back to the actual" + " rule implementation. Read more about <a" + " href='../../toolchains.$DOC_EXT'>toolchains</a> for more information.", category = SkylarkModuleCategory.PROVIDER) public interface ToolchainInfoApi extends StructApi {}
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.platform; import com.google.devtools.build.lib.skylarkbuildapi.StructApi; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; /** * Info object representing data about a specific toolchain. */ @SkylarkModule( name = "ToolchainInfo", doc = "Provides access to data about a specific toolchain.", category = SkylarkModuleCategory.PROVIDER ) public interface ToolchainInfoApi extends StructApi { }
Send http status 403 when stats is hidden
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403) }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.status(404) res.end() }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets
Fix jQuery for selecting active tab
$(document).ready(function(){ $.urlParam = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(decodeURIComponent(window.location.href)); if (results==null){ return null; } else{ return results[1] || 0; } } function getPageName(url) { var index = url.lastIndexOf("/") + 1; var filenameWithExtension = url.substr(index); var filename = filenameWithExtension.split(".")[0]; return filename; } /* * Defaults to Active Page * Can be Manually Called if Page is a Subset of the current page (e.g. view.php) */ function setActiveOption(e){ var page; var currentURL = $(location).attr("href"); if(typeof(e) === "undefined"){ page = getPageName(currentURL); pageInfo = currentURL.split('/'); folder = (pageInfo.pop() == '') ? pageInfo[pageInfo.length - 1] : pageInfo.pop(); page = folder + "-" + page; }else page = e; $("#sidenav_" + page).addClass("active"); } setActiveOption(); });
$(document).ready(function(){ $.urlParam = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(decodeURIComponent(window.location.href)); if (results==null){ return null; } else{ return results[1] || 0; } } /* * Defaults to Active Page * Can be Manually Called if Page is a Subset of the current page (e.g. view.php) */ function setActiveOption(e){ var page; if(typeof(e) === "undefined"){ pageInfo = $(location).attr("href").split('/'); page = pageInfo.slice(-1)[0]; folder = (pageInfo.pop() == '') ? pageInfo[pageInfo.length - 1] : pageInfo.pop(); page = folder + "-" + page.replace(".php", ""); }else page = e; $("#sidenav_" + page).addClass("active"); } setActiveOption(); });
Add usage of nbins_cats to RF pyunit.
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
Use null instead of [] as default property value
import Service from '@ember/service'; export default Service.extend({ showWindow: false, shownComponents: null, data: null, addComponent(path){ if (this.get('shownComponents') == null){ this.set('shownComponents', []); } if (!this.get('shownComponents').includes(path)){ this.get('shownComponents').push(path); } }, removeComponent(path){ if (this.get('shownComponents') == null){ return; } let index = this.get('shownComponents').indexOf(path); if (index !== -1) this.get('shownComponents').splice(index, 1); // close everything when no components are left if (this.get('shownComponents.length') == 0) this.emptyAdditionalData() }, emptyAdditionalData(){ this.set('showWindow', false); this.set('shownComponents', []); this.set('data', null); } });
import Service from '@ember/service'; export default Service.extend({ showWindow: false, shownComponents: [], data: null, addComponent(path){ if (!this.get('shownComponents').includes(path)){ this.get('shownComponents').push(path); } }, removeComponent(path){ var index = this.get('shownComponents').indexOf(path); if (index !== -1) this.get('shownComponents').splice(index, 1); // close everything when no components are left if (this.get('shownComponents.length') == 0) this.emptyAdditionalData() }, emptyAdditionalData(){ this.set('showWindow', false); this.set('shownComponents', []); this.set('data', null); } });
Fix: Set chokidar option ignoreIntial: true by default
'use strict'; var util = require('util'); var Undertaker = require('undertaker'); var vfs = require('vinyl-fs'); var chokidar = require('chokidar'); function Gulp() { Undertaker.call(this); } util.inherits(Gulp, Undertaker); Gulp.prototype.src = vfs.src; Gulp.prototype.dest = vfs.dest; Gulp.prototype.symlink = vfs.symlink; Gulp.prototype.watch = function(glob, opt, task) { if (typeof opt === 'string' || typeof task === 'string' || Array.isArray(opt) || Array.isArray(task)) { throw new Error('watching ' + glob + ': watch task has to be ' + 'a function (optionally generated by using gulp.parallel ' + 'or gulp.series)'); } if (typeof opt === 'function') { task = opt; opt = {}; } var fn; if (typeof task === 'function') { fn = this.parallel(task); } if (opt.ignoreInitial == null) { opt.ignoreInitial = true; } var watcher = chokidar.watch(glob, opt); if (fn) { watcher .on('change', fn) .on('unlink', fn) .on('add', fn); } return watcher; }; // Let people use this class from our instance Gulp.prototype.Gulp = Gulp; var inst = new Gulp(); module.exports = inst;
'use strict'; var util = require('util'); var Undertaker = require('undertaker'); var vfs = require('vinyl-fs'); var chokidar = require('chokidar'); function Gulp() { Undertaker.call(this); } util.inherits(Gulp, Undertaker); Gulp.prototype.src = vfs.src; Gulp.prototype.dest = vfs.dest; Gulp.prototype.symlink = vfs.symlink; Gulp.prototype.watch = function(glob, opt, task) { if (typeof opt === 'string' || typeof task === 'string' || Array.isArray(opt) || Array.isArray(task)) { throw new Error('watching ' + glob + ': watch task has to be ' + 'a function (optionally generated by using gulp.parallel ' + 'or gulp.series)'); } if (typeof opt === 'function') { task = opt; opt = null; } var fn; if (typeof task === 'function') { fn = this.parallel(task); } var watcher = chokidar.watch(glob, opt); if (fn) { watcher .on('change', fn) .on('unlink', fn) .on('add', fn); } return watcher; }; // Let people use this class from our instance Gulp.prototype.Gulp = Gulp; var inst = new Gulp(); module.exports = inst;
Change to new event handling code
const express = require('express') const cors = require('cors') module.exports = function(config){ const router = new express.Router(); config.cors = { router: router, whitelist: null, allowedHeaders: [ 'Authorization', 'Content-Type', 'X-Token', 'X-Username', 'X-Server-Password', ], exposedHeaders: [ 'X-Token', 'X-Username', 'X-Server-Password', ], corsOptionsDelegate: function(req,cb){ cb(null,{ origin: config.cors.whitelist || true, methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', allowedHeaders: config.cors.allowedHeaders, exposedHeaders: config.cors.exposedHeaders, preflightContinue: false }) } } config.backend.on('expressPreConfig', function(app) { app.use(config.cors.router) }) router.use(cors(config.corsOptionsDelegate)) }
const express = require('express') const cors = require('cors') module.exports = function(config){ const router = new express.Router(); config.cors = { router: router, whitelist: null, allowedHeaders: [ 'Authorization', 'Content-Type', 'X-Token', 'X-Username', 'X-Server-Password', ], exposedHeaders: [ 'X-Token', 'X-Username', 'X-Server-Password', ], corsOptionsDelegate: function(req,cb){ cb(null,{ origin: config.cors.whitelist || true, methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', allowedHeaders: config.cors.allowedHeaders, exposedHeaders: config.cors.exposedHeaders, preflightContinue: false }) } } let onExpressPreConfig = config.backend.onExpressPreConfig config.backend.onExpressPreConfig = function(app) { app.use(config.cors.router) return onExpressPreConfig(app) } router.use(cors(config.corsOptionsDelegate)) }
Add helper method on JsArray for easing conversion from/to java array. PiperOrigin-RevId: 263680508
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javaemul.internal; import jsinterop.annotations.JsMethod; /** A utility to provide array stamping. Provided as a separate class to simplify super-source. */ public class ArrayStamper { public static <T> T[] stampJavaTypeInfo(Object array, T[] referenceType) { T[] asArray = JsUtils.uncheckedCast(array); $copyType(asArray, referenceType); return asArray; } @JsMethod(namespace = "vmbootstrap.Arrays") public static native <T> void $copyType(T[] array, T[] referenceType); }
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javaemul.internal; import jsinterop.annotations.JsMethod; class ArrayStamper { public static <T> T[] stampJavaTypeInfo(Object array, T[] referenceType) { T[] asArray = JsUtils.uncheckedCast(array); $copyType(asArray, referenceType); return asArray; } @JsMethod(namespace = "vmbootstrap.Arrays") public static native <T> void $copyType(T[] array, T[] referenceType); }
[Telemetry] Make profile generator wait for pages to load completely. The bug that causes this not to work is fixed. It is possible that this non-determinism in the profile could lead to flakiness in the session_restore benchmark. BUG=375979 Review URL: https://codereview.chromium.org/318733002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@274971 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.core import util from telemetry.page import page_set from telemetry.page import profile_creator class SmallProfileCreator(profile_creator.ProfileCreator): """ Runs a browser through a series of operations to fill in a small test profile. """ def __init__(self): super(SmallProfileCreator, self).__init__() typical_25 = os.path.join(util.GetBaseDir(), 'page_sets', 'typical_25.py') self._page_set = page_set.PageSet.FromFile(typical_25) # Open all links in the same tab save for the last _NUM_TABS links which # are each opened in a new tab. self._NUM_TABS = 5 def TabForPage(self, page, browser): idx = page.page_set.pages.index(page) # The last _NUM_TABS pages open a new tab. if idx <= (len(page.page_set.pages) - self._NUM_TABS): return browser.tabs[0] else: return browser.tabs.New() def MeasurePage(self, _, tab, results): tab.WaitForDocumentReadyStateToBeComplete()
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.core import util from telemetry.page import page_set from telemetry.page import profile_creator class SmallProfileCreator(profile_creator.ProfileCreator): """ Runs a browser through a series of operations to fill in a small test profile. """ def __init__(self): super(SmallProfileCreator, self).__init__() typical_25 = os.path.join(util.GetBaseDir(), 'page_sets', 'typical_25.py') self._page_set = page_set.PageSet.FromFile(typical_25) # Open all links in the same tab save for the last _NUM_TABS links which # are each opened in a new tab. self._NUM_TABS = 5 def TabForPage(self, page, browser): idx = page.page_set.pages.index(page) # The last _NUM_TABS pages open a new tab. if idx <= (len(page.page_set.pages) - self._NUM_TABS): return browser.tabs[0] else: return browser.tabs.New() def MeasurePage(self, _, tab, results): # Can't use WaitForDocumentReadyStateToBeComplete() here due to # crbug.com/280750 . tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
CORE-504: Update Java progress events to use floats
/* * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18. * Copyright (c) 2018 Breadwinner AG. All right reserved. * * See the LICENSE file at the project root for license information. * See the CONTRIBUTORS file at the project root for a list of contributors. */ package com.breadwallet.crypto.events.walletmanager; import android.support.annotation.Nullable; import com.google.common.base.Optional; import java.util.Date; public final class WalletManagerSyncProgressEvent implements WalletManagerEvent { private final float percentComplete; @Nullable private final Date timestamp; public WalletManagerSyncProgressEvent(float percentComplete, @Nullable Date timestamp) { this.percentComplete = percentComplete; this.timestamp = timestamp; } public float getPercentComplete() { return percentComplete; } public Optional<Date> getTimestamp() { return Optional.fromNullable(timestamp); } @Override public <T> T accept(WalletManagerEventVisitor<T> visitor) { return visitor.visit(this); } }
/* * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18. * Copyright (c) 2018 Breadwinner AG. All right reserved. * * See the LICENSE file at the project root for license information. * See the CONTRIBUTORS file at the project root for a list of contributors. */ package com.breadwallet.crypto.events.walletmanager; import android.support.annotation.Nullable; import com.google.common.base.Optional; import java.util.Date; public final class WalletManagerSyncProgressEvent implements WalletManagerEvent { private final double percentComplete; @Nullable private final Date timestamp; public WalletManagerSyncProgressEvent(double percentComplete, @Nullable Date timestamp) { this.percentComplete = percentComplete; this.timestamp = timestamp; } public double getPercentComplete() { return percentComplete; } public Optional<Date> getTimestamp() { return Optional.fromNullable(timestamp); } @Override public <T> T accept(WalletManagerEventVisitor<T> visitor) { return visitor.visit(this); } }
Add flag for insert UTF-8 BOM symbol in start CSV-file
<?php namespace EasyCSV; abstract class AbstractBase { protected $handle; protected $delimiter = ','; protected $enclosure = '"'; public function __construct($path, $mode = 'r+', $isNeedBOM = false) { if (! file_exists($path)) { touch($path); } $this->handle = new \SplFileObject($path, $mode); $this->handle->setFlags(\SplFileObject::DROP_NEW_LINE); if ($isNeedBOM) { $this->handle->fwrite("\xEF\xBB\xBF"); } } public function __destruct() { $this->handle = null; } public function setDelimiter($delimiter) { $this->delimiter = $delimiter; } public function setEnclosure($enclosure) { $this->enclosure = $enclosure; } }
<?php namespace EasyCSV; abstract class AbstractBase { protected $handle; protected $delimiter = ','; protected $enclosure = '"'; public function __construct($path, $mode = 'r+') { if (! file_exists($path)) { touch($path); } $this->handle = new \SplFileObject($path, $mode); $this->handle->setFlags(\SplFileObject::DROP_NEW_LINE); } public function __destruct() { $this->handle = null; } public function setDelimiter($delimiter) { $this->delimiter = $delimiter; } public function setEnclosure($enclosure) { $this->enclosure = $enclosure; } }
Update callback to support two parameters
import argparse import asyncio import logging from .protocol import create_anthemav_reader def console(): parser = argparse.ArgumentParser(description=console.__doc__) parser.add_argument('--host', default='127.0.0.1', help='IP or FQDN of AVR') parser.add_argument('--port', default='14999', help='Port of AVR') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.ERROR logging.basicConfig(level=level) loop = asyncio.get_event_loop() def print_callback(callerobj,message): print(message) conn = create_anthemav_reader(args.host,args.port,print_callback,loop=loop) loop.create_task(conn) loop.run_forever()
import argparse import asyncio import logging from .protocol import create_anthemav_reader def console(): parser = argparse.ArgumentParser(description=console.__doc__) parser.add_argument('--host', default='127.0.0.1', help='IP or FQDN of AVR') parser.add_argument('--port', default='14999', help='Port of AVR') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.ERROR logging.basicConfig(level=level) loop = asyncio.get_event_loop() def print_callback(telegram): """Callback that prints telegram values.""" for obiref, obj in telegram.items(): if obj: print(obj.value, obj.unit) print() conn = create_anthemav_reader(args.host,args.port,print_callback,loop=loop) loop.create_task(conn) loop.run_forever()
Fix Python packaging to use correct git log for package time/version stamps (2nd try)
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): gitinfo = subprocess.check_output( ['git', 'log', '--first-parent', '--max-count=1', '--format=format:%ct']).strip() return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo))) def tags(self): if self.tag_build is None: self.tag_build = self.git_timestamp_tag() return egg_info.tags(self)
from setuptools.command.egg_info import egg_info import subprocess import time class EggInfoFromGit(egg_info): """Tag the build with git commit timestamp. If a build tag has already been set (e.g., "egg_info -b", building from source package), leave it alone. """ def git_timestamp_tag(self): gitinfo = subprocess.check_output( ['git', 'log', '--first-parent', '--max-count=1', '--format=format:%ct', '..']).strip() return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo))) def tags(self): if self.tag_build is None: self.tag_build = self.git_timestamp_tag() return egg_info.tags(self)
FIX: Fix really stupid bug that meant images were not saved
<?php /** * Defines the SupportingProjectPage page type - initial code created by ss generator */ class PageWithImage extends Page implements RenderableAsPortlet { static $has_one = array( 'MainImage' => 'Image' ); // for rendering thumbnail when linked in facebook function getOGImage() { return $this->MainImage(); } function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage')); $dirname = strtolower($this->ClassName).'s'; $uf->setFolderName($dirname); return $fields; } public function getPortletTitle() { return $this->Title; } // FIXME - make this more efficient public function getPortletImage() { $result = null; if ($this->MainImageID) { $result = DataObject::get_by_id('Image', $this->MainImageID); } return $result; } public function getPortletCaption() { return ''; } } class PageWithImage_Controller extends Page_Controller { }
<?php /** * Defines the SupportingProjectPage page type - initial code created by ss generator */ class PageWithImage extends Page implements RenderableAsPortlet { static $has_one = array( 'MainImage' => 'Image' ); // for rendering thumbnail when linked in facebook function getOGImage() { return $this->MainImage(); } function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'.$this->MainImageID)); $dirname = strtolower($this->ClassName).'s'; $uf->setFolderName($dirname); return $fields; } public function getPortletTitle() { return $this->Title; } // FIXME - make this more efficient public function getPortletImage() { $result = null; if ($this->MainImageID) { $result = DataObject::get_by_id('Image', $this->MainImageID); } return $result; } public function getPortletCaption() { return ''; } } class PageWithImage_Controller extends Page_Controller { }
Convert yaml to json config
<?php function handleGitHubPushEvent($payload) { $config = getUserConfig($payload['repository']['full_name'].'/'.$payload['commits'][0]['id']); } function getUserConfig($commitpath) { $defaultconfig = Config::get('userconfig'); $file = file_get_contents("https://raw.githubusercontent.com/".$commitpath."/.redports.json"); if($file === false) return $defaultconfig; $config = json_decode($file, true); foreach($config as $key => $value) { if(isset($defaultconfig[$key])) { if(gettype($defaultconfig[$key]) == gettype($value)) $defaultconfig[$key] = $value; else { if(settype($value, gettype($defaultconfig[$key]))) $defaultconfig[$key] = $value; } } } return $defaultconfig; }
<?php function handleGitHubPushEvent($payload) { $config = getUserConfig($payload['repository']['full_name'].'/'.$payload['commits'][0]['id']); } function getUserConfig($commitpath) { $defaultconfig = Config::get('userconfig'); $config = yaml_parse_url("https://raw.githubusercontent.com/".$commitpath."/.redports.yml"); if($config === false) return $defaultconfig; foreach($config as $key => $value) { if(isset($defaultconfig[$key])) { if(gettype($defaultconfig[$key]) == gettype($value)) $defaultconfig[$key] = $value; else { if(settype($value, gettype($defaultconfig[$key]))) $defaultconfig[$key] = $value; } } } return $defaultconfig; }
Fix test for python 3
# -*- coding: utf-8 -*- import pytest import odin class MultiPartResource(odin.Resource): id = odin.IntegerField() code = odin.StringField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') class TestFields(object): def test_multipartfield__get_value(self): target = MultiPartResource(id=42, code='29A') assert '42:29A' == target.two_parts def test_multipartfield__unknown_fields(self): with pytest.raises(AttributeError) as result: class BadMultiPartResource(odin.Resource): id = odin.IntegerField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') assert str(result.value).startswith("Attribute 'code' not found")
# -*- coding: utf-8 -*- import pytest import odin class MultiPartResource(odin.Resource): id = odin.IntegerField() code = odin.StringField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') class TestFields(object): def test_multipartfield__get_value(self): target = MultiPartResource(id=42, code='29A') assert '42:29A' == target.two_parts def test_multipartfield__unknown_fields(self): with pytest.raises(AttributeError) as result: class BadMultiPartResource(odin.Resource): id = odin.IntegerField() two_parts = odin.MultiPartField(('id', 'code'), separator=':') assert result.value.message.startswith("Attribute 'code' not found")
Remove explicit path from load_dotenv call
#! /usr/bin/env python3.6 # coding: utf-8 import os import datetime as dt from pathlib import Path import pytz from dotenv import load_dotenv load_dotenv() slack_verification_token = os.environ["slack_verification_token"] slack_bot_user_token = os.environ["slack_bot_user_token"] bot_id = os.environ["bot_id"] bot_name = os.environ["bot_name"] home = Path(os.getenv("home_folder", os.getcwd())) print(home) db_host = os.environ["db_host"] db_user = os.environ["db_user"] db_passwd = os.environ["db_passwd"] db_name = os.environ["db_name"] dropbox_token = os.environ["dropbox_token"] tz = pytz.timezone(os.environ["tz"]) app_id = os.environ["app_id"] test_channel = os.environ["test_channel"] main_channel = os.environ["main_channel"] countdown_message = os.environ["countdown_message"] ongoing_message = os.environ["ongoing_message"] finished_message = os.environ["finished_message"] countdown_date = dt.datetime.fromtimestamp(int(os.environ["countdown_date"]), tz=tz) countdown_args = os.environ["countdown_args"].split(", ")
#! /usr/bin/env python3.6 # coding: utf-8 import os import datetime as dt from pathlib import Path import pytz from dotenv import load_dotenv env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) slack_verification_token = os.environ["slack_verification_token"] slack_bot_user_token = os.environ["slack_bot_user_token"] bot_id = os.environ["bot_id"] bot_name = os.environ["bot_name"] home = Path(os.getenv("home_folder", os.getcwd())) db_host = os.environ["db_host"] db_user = os.environ["db_user"] db_passwd = os.environ["db_passwd"] db_name = os.environ["db_name"] dropbox_token = os.environ["dropbox_token"] tz = pytz.timezone(os.environ["tz"]) app_id = os.environ["app_id"] test_channel = os.environ["test_channel"] main_channel = os.environ["main_channel"] countdown_message = os.environ["countdown_message"] ongoing_message = os.environ["ongoing_message"] finished_message = os.environ["finished_message"] countdown_date = dt.datetime.fromtimestamp(int(os.environ["countdown_date"]), tz=tz) countdown_args = os.environ["countdown_args"].split(", ")
fix(backend): Fix for observing game by guest.
<?php /** * Created by PhpStorm. * User: stas * Date: 12.02.16 * Time: 21:13 */ namespace CoreBundle\Model\Request\Game; use CoreBundle\Model\Request\SecurityRequestAwareTrait; use CoreBundle\Model\Request\SecurityRequestInterface; use JMS\Serializer\Annotation as JMS; use Symfony\Component\Validator\Constraints as Assert; /** * Class GameGetRequest * @package CoreBundle\Model\Request\Game */ class GameGetRequest extends GameRequest implements SecurityRequestInterface { use SecurityRequestAwareTrait; /** * @var int * * @JMS\Type("integer") */ private $id; /** * @var string * * @JMS\Expose * @JMS\Type("string") */ protected $login; /** * @var string * * @JMS\Expose * @JMS\Type("string") */ protected $token; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return GameGetRequest */ public function setId($id) { $this->id = $id; return $this; } }
<?php /** * Created by PhpStorm. * User: stas * Date: 12.02.16 * Time: 21:13 */ namespace CoreBundle\Model\Request\Game; use CoreBundle\Model\Request\SecurityRequestAwareTrait; use CoreBundle\Model\Request\SecurityRequestInterface; use JMS\Serializer\Annotation as JMS; use Symfony\Component\Validator\Constraints as Assert; /** * Class GameGetRequest * @package CoreBundle\Model\Request\Game */ class GameGetRequest extends GameRequest implements SecurityRequestInterface { use SecurityRequestAwareTrait; /** * @var int * * @JMS\Type("integer") */ private $id; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return GameGetRequest */ public function setId($id) { $this->id = $id; return $this; } }
Switch two instances of string[n] to string.charAt(n) for IE 7 compatibility.
/* * To Title Case 2.0 – http://individed.com/code/to-title-case/ * Copyright © 2008–2012 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function () { var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i; return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) { if (index > 0 && index + p1.length !== title.length && p1.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && title.charAt(index - 1).search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (p1.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
/* * To Title Case 2.0 – http://individed.com/code/to-title-case/ * Copyright © 2008–2012 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function () { var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i; return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) { if (index > 0 && index + p1.length !== title.length && p1.search(smallWords) > -1 && title[index - 2] !== ":" && title[index - 1].search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (p1.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
Fix config sync handling not using client task scheduler
package info.tehnut.xtones.network; import info.tehnut.xtones.client.XtonesClient; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import org.checkerframework.checker.nullness.qual.Nullable; final class ConfigSyncHandler implements IMessageHandler<ConfigSyncMessage, IMessage> { static final ConfigSyncHandler INSTANCE = new ConfigSyncHandler(); private ConfigSyncHandler() { } private static void readConfig(final ConfigSyncMessage config) { XtonesClient.setServerXtoneCycling(config.hasXtoneCycling()); } @Override @Nullable public IMessage onMessage(final ConfigSyncMessage config, final MessageContext context) { Minecraft.getMinecraft().addScheduledTask(() -> readConfig(config)); return null; } }
package info.tehnut.xtones.network; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import org.checkerframework.checker.nullness.qual.Nullable; import info.tehnut.xtones.client.XtonesClient; final class ConfigSyncHandler implements IMessageHandler<ConfigSyncMessage, IMessage> { static final ConfigSyncHandler INSTANCE = new ConfigSyncHandler(); private ConfigSyncHandler() { } private static void readConfig(final ConfigSyncMessage config) { XtonesClient.setServerXtoneCycling(config.hasXtoneCycling()); } @Override @Nullable public IMessage onMessage(final ConfigSyncMessage config, final MessageContext context) { FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> readConfig(config)); return null; } }
Enable babel plugin in eslint
// Licensed under the Apache License, Version 2.0 (the “License”); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an “AS IS” BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import {CONFIGS_DIR} from '../../paths' import {join} from 'path' const ESLINT_CONFIG_DIR = join(CONFIGS_DIR, 'eslint') module.exports = { parser: 'Babel-ESLint', plugins: [ 'eslint-plugin-babel', ], extends: [ join(ESLINT_CONFIG_DIR, 'core', 'best-practices.js'), join(ESLINT_CONFIG_DIR, 'core', 'stylistic-issues.js'), ], }
// Licensed under the Apache License, Version 2.0 (the “License”); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an “AS IS” BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import {CONFIGS_DIR} from '../../paths' import {join} from 'path' const ESLINT_CONFIG_DIR = join(CONFIGS_DIR, 'eslint') module.exports = { parser: 'Babel-ESLint', extends: [ join(ESLINT_CONFIG_DIR, 'core', 'best-practices.js'), join(ESLINT_CONFIG_DIR, 'core', 'stylistic-issues.js'), ], }
Change publicPath from /dist/ to /
const path = require('path') const webpack = require('webpack') const WebpackMd5Hash = require('webpack-md5-hash') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { output: { path: path.resolve(__dirname, '../dist'), filename: '[name].[chunkhash:6].js', publicPath: '/', }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader', options: { extractCSS: true } }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { importLoaders: 1, minimize: true } }, 'postcss-loader' ] }), }], }, plugins: [ new WebpackMd5Hash(), new ExtractTextPlugin('[name].[contenthash:6].css'), new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}), ], devtool: 'source-map' }
const path = require('path') const webpack = require('webpack') const WebpackMd5Hash = require('webpack-md5-hash') const ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { output: { path: path.resolve(__dirname, '../dist'), filename: '[name].[chunkhash:6].js', publicPath: '/dist/' }, module: { rules: [{ test: /\.vue$/, loader: 'vue-loader', options: { extractCSS: true } }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { importLoaders: 1, minimize: true } }, 'postcss-loader' ] }), }], }, plugins: [ new WebpackMd5Hash(), new ExtractTextPlugin('[name].[contenthash:6].css'), new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}), ], devtool: 'source-map' }
Fix editor mock when text is really long
pw.component.register('content-editor-plaintext', function (view, config) { var self = this; var mock = document.createElement('DIV'); mock.classList.add('console-content-plaintext-mock') mock.style.position = 'absolute'; mock.style.right = '-100px'; mock.style.opacity = '0'; mock.style.width = view.node.clientWidth + 'px'; pw.node.after(view.node, mock); view.node.addEventListener('keypress', function (evt) { var value = this.value + String.fromCharCode(evt.keyCode); if (evt.keyCode == 13) { value += '<br>'; } self.update(value); }); view.node.addEventListener('keyup', function (evt) { self.update(this.value); }); view.node.addEventListener('blur', function () { pw.component.broadcast('content-editor:changed'); }); this.listen('content-editor:booted', function () { self.update(view.node.value); }); this.update = function (value) { value = value.replace(/\n/g, '<br>'); if (value.trim() == '') { value = '&nbsp;'; } // add an extra line break to push the content down if (value.substring(value.length - 4, value.length) == '<br>') { value += '<br>'; } mock.innerHTML = value; view.node.style.height = mock.offsetHeight + 'px'; }; });
pw.component.register('content-editor-plaintext', function (view, config) { var self = this; var mock = document.createElement('DIV'); mock.classList.add('console-content-plaintext-mock') mock.style.position = 'absolute'; mock.style.top = '-100px'; mock.style.opacity = '0'; mock.style.width = view.node.clientWidth + 'px'; pw.node.after(view.node, mock); view.node.addEventListener('keypress', function (evt) { var value = this.value + String.fromCharCode(evt.keyCode); if (evt.keyCode == 13) { value += '<br>'; } self.update(value); }); view.node.addEventListener('keyup', function (evt) { self.update(this.value); }); view.node.addEventListener('blur', function () { pw.component.broadcast('content-editor:changed'); }); this.listen('content-editor:booted', function () { self.update(view.node.value); }); this.update = function (value) { value = value.replace(/\n/g, '<br>'); if (value.trim() == '') { value = '&nbsp;'; } // add an extra line break to push the content down if (value.substring(value.length - 4, value.length) == '<br>') { value += '<br>'; } mock.innerHTML = value; view.node.style.height = mock.offsetHeight + 'px'; }; });
Add a main function with command line arguments Now able to generate wave files from command line
############# # ECE 612 Spring 2017 # Joe Parrish # # Use the same logic from SpectrumTester.py to generate multiple sine waves # but write that output to a .wav file for file based testing of the project code ############# import wave import argparse import numpy as np def generate_sample_file(test_freqs, test_amps, chunk=4096, samplerate=44100): filename = 'Sample' x = np.arange(chunk) y = np.zeros(chunk) for test_freq,test_amp in zip(test_freqs,test_amps): filename += '_' + str(test_freq) + 'Hz@' + str(test_amp) y = np.add(y, np.sin(2 * np.pi * test_freq * x / samplerate) * test_amp) filename += '.wav' y = y.astype('i2') wave_writer = wave.open(filename, mode='wb') wave_writer.setnchannels(1) wave_writer.setsampwidth(2) wave_writer.setframerate(samplerate) for x in range(0,8): wave_writer.writeframes(y) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Write a wave file containing Numpy generated sine waves') parser.add_argument('--freqs', nargs='+', type=int) parser.add_argument('--amps', nargs='+', type=int) args = parser.parse_args() generate_sample_file(args.freqs, args.amps)
############# # ECE 612 Spring 2017 # Joe Parrish # # Use the same logic from SpectrumTester.py to generate multiple sine waves # but write that output to a .wav file for file based testing of the project code ############# import wave import numpy as np def generate_sample_file(test_freqs, test_amps, chunk=4096, samplerate=44100): filename = 'Sample_' x = np.arange(chunk) y = np.zeros(chunk) for test_freq,test_amp in zip(test_freqs,test_amps): filename += str(test_freq) + 'Hz@' + str(test_amp) y = np.add(y, np.sin(2 * np.pi * test_freq * x / samplerate) * test_amp) filename += '.wav' y = y.astype('i2') wave_writer = wave.open(filename, mode='wb') wave_writer.setnchannels(1) wave_writer.setsampwidth(2) wave_writer.setframerate(samplerate) for x in range(0,8): wave_writer.writeframes(y)
Switch extra-views to lower version for now
#!/usr/bin/env python import os from setuptools import setup, find_packages setup( name='django-oscar-stores', version=":versiontools:stores:", url='https://github.com/tangentlabs/django-oscar-stores', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="An extension for Oscar to include store locations", long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), keywords="django, oscar, e-commerce", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'Django>=1.4.2', 'versiontools>=1.1.9', 'django-oscar>=0.4', 'django-extra-views>=0.2.2', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
#!/usr/bin/env python import os from setuptools import setup, find_packages setup( name='django-oscar-stores', version=":versiontools:stores:", url='https://github.com/tangentlabs/django-oscar-stores', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="An extension for Oscar to include store locations", long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), keywords="django, oscar, e-commerce", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'Django>=1.4.2', 'versiontools>=1.1.9', 'django-oscar>=0.4', 'django-extra-views>=0.5.2', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python' ] )
Update app min width and min height
const fs = require('fs'); const electron = require('electron'); const { app } = electron; const { BrowserWindow } = electron; const dbExists = () => { const dbPath = '.config/db'; if (fs.existsSync(dbPath)) { return true; } return false; }; const createDatabase = () => { fs.mkdirSync('./.config'); const prefill = JSON.stringify({ tasks: [], ideas: [], appProperties: { showNotYetTasks: true, fullscreen: false, calendarSystem: 'en-US', firstDayOfWeek: 1, }, }); fs.writeFileSync('.config/db', prefill); }; const isFullscreen = () => { const data = fs.readFileSync('.config/db', 'utf-8'); return JSON.parse(data).appProperties.fullscreen; }; let win; function createWindow() { if (dbExists() === false) { createDatabase(); } let width = 1024; let height = 768; if (isFullscreen()) { ({ width, height } = electron.screen.getPrimaryDisplay().size); } win = new BrowserWindow({ minWidth: 1024, minHeight: 768, width, height, icon: `${__dirname}/wanna.png`, }); win.loadURL('http://localhost:3000'); } app.on('ready', () => { createWindow(); });
const fs = require('fs'); const electron = require('electron'); const { app } = electron; const { BrowserWindow } = electron; const dbExists = () => { const dbPath = '.config/db'; if (fs.existsSync(dbPath)) { return true; } return false; }; const createDatabase = () => { fs.mkdirSync('./.config'); const prefill = JSON.stringify({ tasks: [], ideas: [], appProperties: { showNotYetTasks: true, fullscreen: false, calendarSystem: 'en-US', firstDayOfWeek: 1, }, }); fs.writeFileSync('.config/db', prefill); }; const isFullscreen = () => { const data = fs.readFileSync('.config/db', 'utf-8'); return JSON.parse(data).appProperties.fullscreen; }; let win; function createWindow() { if (dbExists() === false) { createDatabase(); } let width = 800; let height = 600; if (isFullscreen()) { ({ width, height } = electron.screen.getPrimaryDisplay().size); } win = new BrowserWindow({ minWidth: 800, minHeight: 600, width, height, icon: `${__dirname}/wanna.png`, }); win.loadURL('http://localhost:3000'); } app.on('ready', () => { createWindow(); });
Fix nginx forwarding issue with remote address.
var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { var ip = ''; if (req.headers['x-nginx-proxy'] == 'true') { ip = req.headers['x-real-ip']; } else { ip = req.connection.remoteAddress; } rdb.sismember( 'stats:ip', ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { rdb.sadd('stats:ip', ip, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; }
var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { rdb.sismember( 'stats:ip', req.connection.remoteAddress, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { rdb.sadd('stats:ip', req.connection.remoteAddress, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; }
Correct for None appearing in requirements list
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Add automatic template render on Controller :D
<?php /* * (c) Smalte - 2012 ~ Until the end of the world... * * Julien Breux <julien@smalte.org> * Fabien Serny <fabien@smalte.org> * Grégoire Poulain <gregoire@smalte.org> * Alain Folletete <alain@smalte.org> * Raphaël Malié <raphael@smalte.org> * * Thanks a lot to our community! * * Read LICENCE file for more information. */ namespace Controllers\FrontOffice; use \Smalte\Controller\Controller; class Home extends Controller { public function displayAction() { // Set template vars like this $this->templateVars = array( 'test' => 'mycontent', 'date' => date('H:i:s'), ); // Controller resolver will automatically render the template corresponding to this method (home/display) // You can change template with this method // $this->setTemplate('home/index'); // In case of json answer (for example) // You can avoid template rendering with this method // $this->noRender(); // You will be able to set the Json content with this method // $this->setResponseContent(json_encode(array('Smalte', 'is', 'good'))); } }
<?php /* * (c) Smalte - 2012 ~ Until the end of the world... * * Julien Breux <julien@smalte.org> * Fabien Serny <fabien@smalte.org> * Grégoire Poulain <gregoire@smalte.org> * Alain Folletete <alain@smalte.org> * Raphaël Malié <raphael@smalte.org> * * Thanks a lot to our community! * * Read LICENCE file for more information. */ namespace Controllers\FrontOffice; use \Smalte\Controller\Controller; class Home extends Controller { public function displayAction() { $vars = array( 'test' => 'mycontent', 'date' => date('H:i:s'), ); $content = $this->renderView('home/index', $vars); return $this->getResponse($content); } }
Update to current Braintree Node library version
Package.describe({ name: 'patrickml:braintree', version: '1.0.4', // Brief, one-line summary of the package. summary: 'Complete Sync wrapper for Braintree Payments.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/patrickml/braintree', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); api.use( [ 'underscore' ], ['client', 'server']); api.addFiles('braintree.js', "server"); api.export([ 'Braintree', 'BrainTreeConnect' ], 'server'); }); Npm.depends({ braintree: '1.29.0' }); Package.onTest(function(api) { api.use('tinytest'); api.use('patrickml:braintree'); api.addFiles('braintree-tests.js'); });
Package.describe({ name: 'patrickml:braintree', version: '1.0.4', // Brief, one-line summary of the package. summary: 'Complete Sync wrapper for Braintree Payments.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/patrickml/braintree', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); api.use( [ 'underscore' ], ['client', 'server']); api.addFiles('braintree.js', "server"); api.export([ 'Braintree', 'BrainTreeConnect' ], 'server'); }); Npm.depends({ braintree: '1.27.0' }); Package.onTest(function(api) { api.use('tinytest'); api.use('patrickml:braintree'); api.addFiles('braintree-tests.js'); });
Handle empty response in help texts
package main import ( "text/template" ) var ( BANNER_TEMPLATE = template.Must(template.New("banner").Parse( `===================== goslow ==================== `)) CREATE_SITE_TEMPLATE = template.Must(template.New("create site").Parse( `Your personal goslow domain is {{ .Domain }} You can configure your domain with POST requests to admin-{{ .Domain }} Example: Let's say you want to add an endpoint /christmas and you want it to respond to GET requests with "hohoho" and 2.5 seconds delay. Just make a POST request to your admin domain ... curl -d "hohoho" "admin-{{ .Domain }}/christmas?delay=2.5&method=GET" ... and you're done! If you have any questions, don't hesitate to ask: codumentary.com@gmail.com`)) ADD_RULE_TEMPLATE = template.Must(template.New("add rule").Parse( `Hooray! Endpoint http://{{ .Domain }}{{ .Path }} responds to {{if .Method }}{{ .Method }}{{else}}any HTTP method{{ end }} {{ if .Delay }}with {{ .Delay }} delay{{ else }}without any delay{{end}}. Response is: {{ if .StringBody }}{{ .StringBody }}{{ else }}<EMPTY>{{ end }} `)) )
package main import ( "text/template" ) var ( BANNER_TEMPLATE = template.Must(template.New("banner").Parse( `===================== goslow ==================== `)) CREATE_SITE_TEMPLATE = template.Must(template.New("create site").Parse( `Your personal goslow domain is {{ .Domain }} You can configure your domain with POST requests to admin-{{ .Domain }} Example: Let's say you want to add an endpoint /christmas and you want it to respond to GET requests with "hohoho" and 2.5 seconds delay. Just make a POST request to your admin domain ... curl -d "hohoho" "admin-{{ .Domain }}/christmas?delay=2.5&method=GET" ... and you're done! If you have any questions, don't hesitate to ask: codumentary.com@gmail.com`)) ADD_RULE_TEMPLATE = template.Must(template.New("add rule").Parse( `Hooray! Endpoint http://{{ .Domain }}{{ .Path }} responds to {{if .Method }}{{ .Method }}{{else}}any HTTP method{{ end }} {{ if .Delay }}with {{ .Delay }} delay{{ else }}without any delay{{end}}. Response is: {{ .StringBody }} `)) )
Change pixelated platform repo name
var repos = {}; var labels = {}; var configurable = require('../lib/configurable'); function addRepo(name, key, label) { configurable.get(key) && (repos[name] = configurable.get(key)); configurable.get(key) && (labels[name] = (label || repos[name])); } configurable.setSilentMode(true); addRepo('user-agent', 'PX_USER_AGENT', 'User Agent'); addRepo('dispatcher', 'PX_DISPATCHER', 'Dispatcher'); addRepo('puppet-pixelated', 'PX_PUPPET_PIXELATED', 'Puppet Pixelated'); addRepo('project-issues', 'PX_PROJECT_ISSUES', 'Project Issues'); addRepo('website', 'PX_PAGES', 'Website'); var maxDynaReposQuantity = 5; for (i = 0; i < maxDynaReposQuantity; i++) { addRepo(configurable.get('REPO_' + i + '_NAME') || i + 'th', 'REPO_' + i + '_URL'); } configurable.get('REPOS', function (value) { var chunks = value.split(';'); chunks.forEach(function (chunk) { var val = chunk, nameRegex = /(https:\/\/api\.github\.com\/repos\/)?(.*)/; name = nameRegex.exec(val)[2], key = name.toLowerCase().replace('/', '_'); var gitHubApiPrefix = 'https://api.github.com/repos/'; repos[key] = gitHubApiPrefix + name; labels[key] = name; }); }); module.exports = { repos: repos, labels: labels };
var repos = {}; var labels = {}; var configurable = require('../lib/configurable'); function addRepo(name, key, label) { configurable.get(key) && (repos[name] = configurable.get(key)); configurable.get(key) && (labels[name] = (label || repos[name])); } configurable.setSilentMode(true); addRepo('user-agent', 'PX_USER_AGENT', 'User Agent'); addRepo('dispatcher', 'PX_DISPATCHER', 'Dispatcher'); addRepo('platform', 'PX_PLATFORM', 'Platform'); addRepo('project-issues', 'PX_PROJECT_ISSUES', 'Project Issues'); addRepo('website', 'PX_PAGES', 'Website'); var maxDynaReposQuantity = 5; for (i = 0; i < maxDynaReposQuantity; i++) { addRepo(configurable.get('REPO_' + i + '_NAME') || i + 'th', 'REPO_' + i + '_URL'); } configurable.get('REPOS', function (value) { var chunks = value.split(';'); chunks.forEach(function (chunk) { var val = chunk, nameRegex = /(https:\/\/api\.github\.com\/repos\/)?(.*)/; name = nameRegex.exec(val)[2], key = name.toLowerCase().replace('/', '_'); var gitHubApiPrefix = 'https://api.github.com/repos/'; repos[key] = gitHubApiPrefix + name; labels[key] = name; }); }); module.exports = { repos: repos, labels: labels };
Add plug-in name for welcome RBAC
package org.ligoj.app.resource.welcome; import java.util.Arrays; import java.util.List; import org.ligoj.app.api.FeaturePlugin; import org.ligoj.app.iam.model.DelegateOrg; import org.ligoj.app.model.DelegateNode; import org.ligoj.bootstrap.model.system.SystemAuthorization; import org.ligoj.bootstrap.model.system.SystemRole; import org.ligoj.bootstrap.model.system.SystemRoleAssignment; import org.ligoj.bootstrap.model.system.SystemUser; import org.springframework.stereotype.Component; /** * Initialize during the RBAC data on installation. */ @Component public class InitializeRbacDataResource implements FeaturePlugin { @Override public String getKey() { return "feature:welcome:data-rbac"; } @Override public List<Class<?>> getInstalledEntities() { return Arrays.asList(SystemUser.class, SystemRole.class, SystemAuthorization.class, SystemRoleAssignment.class, DelegateOrg.class, DelegateNode.class); } @Override public String getName() { return "Welcome Data RBAC"; } }
package org.ligoj.app.resource.welcome; import java.util.Arrays; import java.util.List; import org.ligoj.app.api.FeaturePlugin; import org.ligoj.app.iam.model.DelegateOrg; import org.ligoj.app.model.DelegateNode; import org.ligoj.bootstrap.model.system.SystemAuthorization; import org.ligoj.bootstrap.model.system.SystemRole; import org.ligoj.bootstrap.model.system.SystemRoleAssignment; import org.ligoj.bootstrap.model.system.SystemUser; import org.springframework.stereotype.Component; /** * Initialize during the RBAC data on installation. */ @Component public class InitializeRbacDataResource implements FeaturePlugin { @Override public String getKey() { return "feature:welcome:data-rbac"; } @Override public List<Class<?>> getInstalledEntities() { return Arrays.asList(SystemUser.class, SystemRole.class, SystemAuthorization.class, SystemRoleAssignment.class, DelegateOrg.class, DelegateNode.class); } }
Put loginwrapper inside main router
import React from 'react' import DefaultLayout from './DefaultLayout' import {Router, Route, NotFound, Redirect} from 'router:@sanity/base/router' import locationStore from 'datastore:@sanity/base/location' import SanityIntlProvider from 'component:@sanity/base/sanity-intl-provider' import LoginWrapper from 'component:@sanity/base/login-wrapper' class DefaultLayoutRouter extends React.Component { constructor() { super() this.state = {} this.handleNavigate = this.handleNavigate.bind(this) } componentWillMount() { this.pathSubscription = locationStore .state .subscribe({next: event => this.setState({location: event.location})}) } componentWillUnmount() { this.pathSubscription.unsubscribe() } handleNavigate(newUrl, options) { locationStore.actions.navigate(newUrl) } render() { const {location} = this.state if (!location) { return null } return ( <SanityIntlProvider> <LoginWrapper> <Router location={location} navigate={this.handleNavigate}> <Route path="/:site/*" component={DefaultLayout} /> <Redirect path="/" to="/some-site" /> <NotFound component={() => <div>Not found</div>} /> </Router> </LoginWrapper> </SanityIntlProvider> ) } } export default DefaultLayoutRouter
import React from 'react' import DefaultLayout from './DefaultLayout' import {Router, Route, NotFound, Redirect} from 'router:@sanity/base/router' import locationStore from 'datastore:@sanity/base/location' import SanityIntlProvider from 'component:@sanity/base/sanity-intl-provider' class DefaultLayoutRouter extends React.Component { constructor() { super() this.state = {} this.handleNavigate = this.handleNavigate.bind(this) } componentWillMount() { this.pathSubscription = locationStore .state .subscribe({next: event => this.setState({location: event.location})}) } componentWillUnmount() { this.pathSubscription.unsubscribe() } handleNavigate(newUrl, options) { locationStore.actions.navigate(newUrl) } render() { const {location} = this.state if (!location) { return null } return ( <SanityIntlProvider> <Router location={location} navigate={this.handleNavigate}> <Route path="/:site/*" component={DefaultLayout} /> <Redirect path="/" to="/some-site" /> <NotFound component={() => <div>Not found</div>} /> </Router> </SanityIntlProvider> ) } } export default DefaultLayoutRouter
Add conditional to set 'module.exports'
(function() { var Color; chromato = function(x, y, z, m) { return new Color(x, y, z, m); }; if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) { module.exports = chroma; } chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.rgb = function(r, g, b, a) { return new Color(r, g, b, a, 'rgb'); }; chromato.hex = function(x) { return new Color(x); }; chromato.interpolate = function(a, b, f, m) { if ((a == null) || (b == null)) { return '#000'; } if (type(a) === 'string') { a = new Color(a); } if (type(b) === 'string') { b = new Color(b); } return a.interpolate(f, b, m); }; chromato.mix = chromato.interpolate; }).call(this);
(function() { var Color; chromato = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.rgb = function(r, g, b, a) { return new Color(r, g, b, a, 'rgb'); }; chromato.hex = function(x) { return new Color(x); }; chromato.interpolate = function(a, b, f, m) { if ((a == null) || (b == null)) { return '#000'; } if (type(a) === 'string') { a = new Color(a); } if (type(b) === 'string') { b = new Color(b); } return a.interpolate(f, b, m); }; chromato.mix = chromato.interpolate; }).call(this);
Fix issue where errors aren't being propagated.
function DeferredChain() { var self = this; this.chain = new Promise(function(accept, reject) { self._accept = accept; self._reject = reject; }); this.await = new Promise(function() { self._done = arguments[0]; self._error = arguments[1]; }); this.started = false; }; DeferredChain.prototype.then = function(fn) { var self = this; this.chain = this.chain.then(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); this.chain = this.chain.catch(function(e) { self._error(e); }); return this; }; DeferredChain.prototype.catch = function(fn) { var self = this; this.chain = this.chain.catch(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.start = function() { this.started = true; this.chain = this.chain.then(this._done); this._accept(); return this.await; }; module.exports = DeferredChain;
function DeferredChain() { var self = this; this.chain = new Promise(function(accept, reject) { self._accept = accept; self._reject = reject; }); this.await = new Promise(function() { self._done = arguments[0]; }); this.started = false; }; DeferredChain.prototype.then = function(fn) { var self = this; this.chain = this.chain.then(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.catch = function(fn) { var self = this; this.chain = this.chain.catch(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.start = function() { this.started = true; this.chain = this.chain.then(this._done); this._accept(); return this.await; }; module.exports = DeferredChain;
[IMP] Remove unneeded dependency on Inventory
# Copyright (C) 2019 - TODAY, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Product ISP', 'version': '12.0.1.0.0', 'license': 'AGPL-3', 'summary': 'Assign ISPs to Products', 'author': 'Open Source Integrators, Odoo Community Association (OCA)', "website": 'https://github.com/OCA/vertical-isp', 'depends': [ 'product', 'base_phone_rate' ], 'data': [ 'views/product_product.xml', ], 'installable': True, 'development_status': 'Beta', 'maintainers': [ 'wolfhall', 'max3903', 'osi-scampbell', ], }
# Copyright (C) 2019 - TODAY, Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Product ISP', 'version': '12.0.1.0.0', 'license': 'AGPL-3', 'summary': 'Assign ISPs to Products', 'author': 'Open Source Integrators, Odoo Community Association (OCA)', "website": 'https://github.com/OCA/vertical-isp', 'depends': [ 'stock', 'base_phone_rate' ], 'data': [ 'views/product_product.xml', ], 'installable': True, 'development_status': 'Beta', 'maintainers': [ 'wolfhall', 'max3903', 'osi-scampbell', ], }
Fix hunters name (my fault)
import React, { Component } from 'react' import styled from 'styled-components' const FooterWrapper = styled.div` display: flex; justify-content: center; align-items: center; height: 10vh; font-size: 0.85em; background: ${props => props.theme.colors.background}; color: ${props => props.theme.colors.barText}; padding: 0.25em 0.5em; text-align: center; cursor: default; ` const Content = styled.div` ` const Link = styled.a` color: white; ` export default class Footer extends Component { render (){ return ( <FooterWrapper> <Content> Not FDIC Insured <br/> <Link href="https://github.com/csrf-demo/csrf-demo" target="_blank"> Fork on Github </Link> <br/> Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Heavener </Content> </FooterWrapper> ) } }
import React, { Component } from 'react' import styled from 'styled-components' const FooterWrapper = styled.div` display: flex; justify-content: center; align-items: center; height: 10vh; font-size: 0.85em; background: ${props => props.theme.colors.background}; color: ${props => props.theme.colors.barText}; padding: 0.25em 0.5em; text-align: center; cursor: default; ` const Content = styled.div` ` const Link = styled.a` color: white; ` export default class Footer extends Component { render (){ return ( <FooterWrapper> <Content> Not FDIC Insured <br/> <Link href="https://github.com/csrf-demo/csrf-demo" target="_blank"> Fork on Github </Link> <br/> Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Aeraer </Content> </FooterWrapper> ) } }
Add more logging data in Send.
// // Copyright © 2011 Guy M. Allard // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package stomp import ( "os" ) // Send func (c *Connection) Send(h Headers, b string) (e os.Error) { c.log(SEND, "start", h) if !c.connected { return ECONBAD } if _, ok := h.Contains("destination"); !ok { return EREQDSTSND } e = nil ch := h.Clone() f := Frame{SEND, ch, []uint8(b)} r := make(chan os.Error) c.output <- wiredata{f, r} e = <-r c.log(SEND, "end", ch) return e // nil or not }
// // Copyright © 2011 Guy M. Allard // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package stomp import ( "os" ) // Send func (c *Connection) Send(h Headers, b string) (e os.Error) { c.log(SEND, "start") if !c.connected { return ECONBAD } if _, ok := h.Contains("destination"); !ok { return EREQDSTSND } e = nil ch := h.Clone() f := Frame{SEND, ch, []uint8(b)} r := make(chan os.Error) c.output <- wiredata{f, r} e = <-r c.log(SEND, "end") return e // nil or not }
Exclude preprints from queryset from account/register in the admin app.
from __future__ import absolute_import from django import forms from django.db.models import Q from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(Q(name__startswith='collections_') | Q(name__startswith='preprint_')), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
from __future__ import absolute_import from django import forms from django.contrib.auth.models import Group from osf.models import AdminProfile class LoginForm(forms.Form): email = forms.CharField(label=u'Email', required=True) password = forms.CharField( label=u'Password', widget=forms.PasswordInput(render_value=False), required=True ) class UserRegistrationForm(forms.Form): """ A form that finds an existing OSF User, and grants permissions to that user so that they can use the admin app""" osf_id = forms.CharField(required=True, max_length=5, min_length=5) # TODO: Moving to guardian, find a better way to distinguish "admin-like" groups from object permission groups group_perms = forms.ModelMultipleChoiceField( queryset=Group.objects.exclude(name__startswith='collections_'), required=False, widget=forms.CheckboxSelectMultiple ) class DeskUserForm(forms.ModelForm): class Meta: model = AdminProfile fields = ['desk_token', 'desk_token_secret']
Fix test. AS_PATH_LIST should return empty list not null.
package com.jayway.jsonpath; import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; public class TestSuppressExceptions { @Test public void testSuppressExceptionsIsRespected() { ParseContext parseContext = JsonPath.using( new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS) .build()); String json = "{}"; assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing"))); } @Test public void testSuppressExceptionsIsRespectedPath() { ParseContext parseContext = JsonPath.using( new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST) .build()); String json = "{}"; List<String> result = parseContext.parse(json).read(JsonPath.compile("$.missing")); assertThat(result).isEmpty(); } }
package com.jayway.jsonpath; import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import org.junit.Test; import static org.junit.Assert.assertNull; public class TestSuppressExceptions { @Test public void testSuppressExceptionsIsRespected() { ParseContext parseContext = JsonPath.using( new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS) .build()); String json = "{}"; assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing"))); } @Test public void testSuppressExceptionsIsRespectedPath() { ParseContext parseContext = JsonPath.using( new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider()).options(Option.SUPPRESS_EXCEPTIONS, Option.AS_PATH_LIST) .build()); String json = "{}"; assertNull(parseContext.parse(json).read(JsonPath.compile("$.missing"))); } }
Drop configured annotator store uri
from django.conf import settings __version_info__ = (1, 2, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__, # Alternate names for social-auth backends, # to be used for display and font-awesome icon (lowercased) # If not entered here, backend name will be used as-is for # icon and title-cased for display (i.e., twitter / Twitter). 'backend_names': { 'github': 'GitHub', 'google-oauth2': 'Google', }, }
from django.conf import settings __version_info__ = (1, 2, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__, # Alternate names for social-auth backends, # to be used for display and font-awesome icon (lowercased) # If not entered here, backend name will be used as-is for # icon and title-cased for display (i.e., twitter / Twitter). 'backend_names': { 'github': 'GitHub', 'google-oauth2': 'Google', }, 'ANNOTATOR_STORE_URI': settings.ANNOTATOR_STORE_URI }
Increase maxBuffer to 10MB when compiling using native compiler
const { execSync } = require("child_process"); const LoadingStrategy = require("./LoadingStrategy"); const VersionRange = require("./VersionRange"); class Native extends LoadingStrategy { load() { const versionString = this.validateAndGetSolcVersion(); const command = "solc --standard-json"; const maxBuffer = 1024 * 1024 * 10; try { return { compile: options => String(execSync(command, { input: options, maxBuffer })), version: () => versionString }; } catch (error) { if (error.message === "No matching version found") { throw this.errors("noVersion", versionString); } throw new Error(error); } } validateAndGetSolcVersion() { let version; try { version = execSync("solc --version"); } catch (error) { throw this.errors("noNative", null, error); } return new VersionRange(this.config).normalizeSolcVersion(version); } } module.exports = Native;
const { execSync } = require("child_process"); const LoadingStrategy = require("./LoadingStrategy"); const VersionRange = require("./VersionRange"); class Native extends LoadingStrategy { load() { const versionString = this.validateAndGetSolcVersion(); const command = "solc --standard-json"; try { return { compile: options => String(execSync(command, { input: options })), version: () => versionString }; } catch (error) { if (error.message === "No matching version found") { throw this.errors("noVersion", versionString); } throw new Error(error); } } validateAndGetSolcVersion() { let version; try { version = execSync("solc --version"); } catch (error) { throw this.errors("noNative", null, error); } return new VersionRange(this.config).normalizeSolcVersion(version); } } module.exports = Native;
Add abstract getObserverClass() and use it for dynamic updateMethods() invocation OPEN - task 33: Problem with EntityModelObserver architecture http://github.com/DevOpsDistilled/OpERP/issues/issue/33 updateMethods() are methods in EntityObservers like "updateItems(List)"
package devopsdistilled.operp.client.abstracts; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import devopsdistilled.operp.server.data.entity.Entiti; import devopsdistilled.operp.server.data.service.EntityService; public abstract class AbstractEntityModel<E extends Entiti, ES extends EntityService<E, ID>, EO extends EntityObserver, ID extends Serializable> extends AbstractModel<EO> implements EntityModel<E, ES, EO, ID> { protected List<E> entities; public AbstractEntityModel() { entities = new LinkedList<>(); } @Override public List<E> getEntities() { return entities; } @Override public void setEntities(List<E> entities) { this.entities = entities; notifyObservers(); } @Override public void update() { setEntities(getService().findAll()); } @Override public void notifyObservers() { for (EO observer : observers) { Method updateMethod = getUpdateMethod(); try { updateMethod.invoke(observer, getEntities()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } @Override public void registerObserver(EO observer) { super.registerObserver(observer); update(); } protected abstract Class<EO> getObserverClass(); private Method getUpdateMethod() { Method[] methods = getObserverClass().getMethods(); return methods[0]; } }
package devopsdistilled.operp.client.abstracts; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import devopsdistilled.operp.server.data.entity.Entiti; import devopsdistilled.operp.server.data.service.EntityService; public abstract class AbstractEntityModel<E extends Entiti, ES extends EntityService<E, ID>, EO extends EntityObserver<E>, ID extends Serializable> extends AbstractModel<EO> implements EntityModel<E, ES, EO, ID> { protected List<E> entities; public AbstractEntityModel() { entities = new LinkedList<>(); } @Override public List<E> getEntities() { return entities; } @Override public void setEntities(List<E> entities) { this.entities = entities; notifyObservers(); } @Override public void update() { setEntities(getService().findAll()); } @Override public void notifyObservers() { for (EO observer : observers) { observer.update(getEntities()); } } @Override public void registerObserver(EO observer) { super.registerObserver(observer); update(); observer.update(getEntities()); } }
Revert "Nix helpful admin login requirement" This reverts commit 684dc38622d6cbe70879fb900ce5d73146a0cb40. We can put it back in because we're going to stick with LDAP basic auth.
from django.conf import settings from django.conf.urls.defaults import patterns, include from django.contrib.auth.decorators import login_required from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from funfactory.monkeypatches import patch patch() from django.contrib import admin from adminplus import AdminSitePlus admin.site = AdminSitePlus() admin.autodiscover() admin.site.login = login_required(admin.site.login) urlpatterns = patterns('', (r'', include('fjord.analytics.urls')), (r'', include('fjord.base.urls')), (r'', include('fjord.feedback.urls')), # Generate a robots.txt (r'^robots\.txt$', lambda r: HttpResponse( ("User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow'), mimetype="text/plain" ) ), (r'^browserid/', include('django_browserid.urls')), (r'^admin/', include(admin.site.urls)), ) # In DEBUG mode, serve media files through Django. if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
from django.conf import settings from django.conf.urls.defaults import patterns, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from funfactory.monkeypatches import patch patch() from django.contrib import admin from adminplus import AdminSitePlus admin.site = AdminSitePlus() admin.autodiscover() urlpatterns = patterns('', (r'', include('fjord.analytics.urls')), (r'', include('fjord.base.urls')), (r'', include('fjord.feedback.urls')), # Generate a robots.txt (r'^robots\.txt$', lambda r: HttpResponse( ("User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow'), mimetype="text/plain" ) ), (r'^browserid/', include('django_browserid.urls')), (r'^admin/', include(admin.site.urls)), ) # In DEBUG mode, serve media files through Django. if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
Fix missing call to display.setup()
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.display.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
Move logic for creating RunProcessError to ExecutionResult.to_error
def result(return_code, output, stderr_output, allow_error=False): result = ExecutionResult(return_code, output, stderr_output) if allow_error or return_code == 0: return result else: raise result.to_error() class RunProcessError(RuntimeError): def __init__(self, return_code, output, stderr_output): message = "return code: {0}\noutput: {1}\nstderr output: {2}".format( return_code, output, stderr_output) super(type(self), self).__init__(message) self.return_code = return_code self.output = output self.stderr_output = stderr_output class ExecutionResult(object): def __init__(self, return_code, output, stderr_output): self.return_code = return_code self.output = output self.stderr_output = stderr_output def to_error(self): return RunProcessError( self.return_code, self.output, self.stderr_output )
def result(return_code, output, stderr_output, allow_error=False): if allow_error or return_code == 0: return ExecutionResult(return_code, output, stderr_output) else: raise RunProcessError(return_code, output, stderr_output) class RunProcessError(RuntimeError): def __init__(self, return_code, output, stderr_output): message = "return code: {0}\noutput: {1}\nstderr output: {2}".format( return_code, output, stderr_output) super(type(self), self).__init__(message) self.return_code = return_code self.output = output self.stderr_output = stderr_output class ExecutionResult(object): def __init__(self, return_code, output, stderr_output): self.return_code = return_code self.output = output self.stderr_output = stderr_output
Fix hover state strapi link Signed-off-by: soupette <0a59f0508aa203bc732745954131d022d9f538a9@gmail.com>
/** * * LeftMenuFooter * */ import React from 'react'; import { PropTypes } from 'prop-types'; import Wrapper, { A } from './Wrapper'; function LeftMenuFooter({ version }) { // PROJECT_TYPE is an env variable defined in the webpack config // eslint-disable-next-line no-undef const projectType = PROJECT_TYPE; return ( <Wrapper> <div className="poweredBy"> <A key="website" href="https://strapi.io" target="_blank" rel="noopener noreferrer"> Strapi </A> &nbsp; <A href={`https://github.com/strapi/strapi/releases/tag/v${version}`} key="github" target="_blank" rel="noopener noreferrer" > v{version} </A> &nbsp; <A href="https://strapi.io" target="_blank" rel="noopener noreferrer"> — {projectType} Edition </A> </div> </Wrapper> ); } LeftMenuFooter.propTypes = { version: PropTypes.string.isRequired, }; export default LeftMenuFooter;
/** * * LeftMenuFooter * */ import React from 'react'; import { PropTypes } from 'prop-types'; import Wrapper, { A } from './Wrapper'; function LeftMenuFooter({ version }) { // PROJECT_TYPE is an env variable defined in the webpack config // eslint-disable-next-line no-undef const projectType = PROJECT_TYPE; return ( <Wrapper> <div className="poweredBy"> <a key="website" href="https://strapi.io" target="_blank" rel="noopener noreferrer"> Strapi </a> &nbsp; <A href={`https://github.com/strapi/strapi/releases/tag/v${version}`} key="github" target="_blank" rel="noopener noreferrer" > v{version} </A> &nbsp; <A href="https://strapi.io" target="_blank" rel="noopener noreferrer"> — {projectType} Edition </A> </div> </Wrapper> ); } LeftMenuFooter.propTypes = { version: PropTypes.string.isRequired, }; export default LeftMenuFooter;
Delete test file after creation
package org.sejda.core.support.prefix.processor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; import org.sejda.core.support.prefix.model.NameGenerationRequest; public class TextPrefixProcessorTest { @Test public void producesFilenameFriendlyResults() throws IOException { String text = "This is an example\nof\t\f\r\n text;\\// that` is \" '' not filename friendly"; NameGenerationRequest req = NameGenerationRequest.nameRequest().text(text); String actual = new TextPrefixProcessor().process("prefix-[TEXT]-suffix", req); assertEquals("prefix-This is an exampleof text that is not filename friendly-suffix", actual); File file = File.createTempFile(actual, ".pdf"); assertTrue(file.exists()); file.delete(); } }
package org.sejda.core.support.prefix.processor; import org.junit.Test; import org.sejda.core.support.prefix.model.NameGenerationRequest; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TextPrefixProcessorTest { @Test public void producesFilenameFriendlyResults() throws IOException { String text = "This is an example\nof\t\f\r\n text;\\// that` is \" '' not filename friendly"; NameGenerationRequest req = NameGenerationRequest.nameRequest().text(text); String actual = new TextPrefixProcessor().process("prefix-[TEXT]-suffix", req); assertEquals("prefix-This is an exampleof text that is not filename friendly-suffix", actual); File file = File.createTempFile(actual, ".pdf"); assertTrue(file.exists()); } }
Fix missing blog post images
// Highlight active navigation menu item (function() { var fullPath = window.location.pathname.substring(1); var parentPath = fullPath.split('/')[0]; var path = fullPath.replace(/\//g, ''); if (path) { if (/404/.test(path) || /success/.test(path)) { return; } // For blog post pages. if (/blog/.test(path)) { parentPath = parentPath +'/'; } document.querySelector("[data-fx='main-nav'] a[href='/"+parentPath+"']").classList.add('active'); } else { return; } })(); // Helper function to set bloglist classes to be used for backgrounds (function() { var pathname = window.location.pathname; var bloglist = document.querySelector("[data-fx='blog-list']"); if (/blog/.test(pathname)) { var pageNum = parseInt(pathname.split('/')[3], 10); if (!pageNum) { pageNum = 1; } if (pageNum <= 4) { pageNum = pageNum; } if (pageNum > 4) { if (pageNum % 4 === 0) { pageNum = 4; } else { pageNum = pageNum % 4; } } if (bloglist) { bloglist.classList.add('page' + pageNum); } } })();
// Highlight active navigation menu item (function() { var fullPath = window.location.pathname.substring(1); var parentPath = fullPath.split('/')[0]; var path = fullPath.replace(/\//g, ''); if (path) { if (/404/.test(path) || /success/.test(path)) { return; } // For blog post pages. if (/blog/.test(path)) { parentPath = parentPath +'/'; } document.querySelector("[data-fx='main-nav'] a[href='/"+parentPath+"']").classList.add('active'); } else { return; } })(); // Helper function to set bloglist classes to be used for backgrounds (function() { var pathname = window.location.pathname; if (pathname === '/blog/') { var pageNum = parseInt(pathname.split('/')[3], 10); if (!pageNum) { pageNum = 1; } if (pageNum <= 4) { pageNum = pageNum; } if (pageNum > 4) { if (pageNum % 4 === 0) { pageNum = 4; } else { pageNum = pageNum % 4; } } document.querySelector("[data-fx='blog-list']").classList.add('page' + pageNum); } })();
examples: Allow to specify role name on commandline
#!/usr/bin/env python import sys, os, json, logging sys.path.append(os.path.abspath(".")) import gevent import msgflo class Repeat(msgflo.Participant): def __init__(self, role): d = { 'component': 'PythonRepeat', 'label': 'Repeat input data without change', } msgflo.Participant.__init__(self, d, role) def process(self, inport, msg): self.send('out', msg.data) self.ack(msg) def main(): waiter = gevent.event.AsyncResult() role = sys.argv[1] if len(sys.argv) > 1 else 'repeat' repeater = Repeat(role) engine = msgflo.run(repeater, done_cb=waiter.set) print "Repeat running on %s" % (engine.broker_url) sys.stdout.flush() waiter.wait() print "Shutdown" sys.stdout.flush() if __name__ == '__main__': logging.basicConfig() main()
#!/usr/bin/env python import sys, os, json, logging sys.path.append(os.path.abspath(".")) import gevent import msgflo class Repeat(msgflo.Participant): def __init__(self, role): d = { 'component': 'PythonRepeat', 'label': 'Repeat input data without change', } msgflo.Participant.__init__(self, d, role) def process(self, inport, msg): self.send('out', msg.data) self.ack(msg) def main(): waiter = gevent.event.AsyncResult() repeater = Repeat('repeat') engine = msgflo.run(repeater, done_cb=waiter.set) print "Repeat running on %s" % (engine.broker_url) sys.stdout.flush() waiter.wait() print "Shutdown" sys.stdout.flush() if __name__ == '__main__': logging.basicConfig() main()
Fix Race Condition in TestXfrmMonitorExpire
// +build linux package netlink import ( "testing" "github.com/vishvananda/netlink/nl" ) func TestXfrmMonitorExpire(t *testing.T) { defer setUpNetlinkTest(t)() ch := make(chan XfrmMsg) done := make(chan struct{}) defer close(done) errChan := make(chan error) if err := XfrmMonitor(ch, nil, errChan, nl.XFRM_MSG_EXPIRE); err != nil { t.Fatal(err) } // Program state with limits state := getBaseState() state.Limits.TimeHard = 2 state.Limits.TimeSoft = 1 if err := XfrmStateAdd(state); err != nil { t.Fatal(err) } hardFound := false softFound := false msg := (<-ch).(*XfrmMsgExpire) if msg.XfrmState.Spi != state.Spi { t.Fatal("Received unexpected msg, spi does not match") } hardFound = msg.Hard || hardFound softFound = !msg.Hard || softFound msg = (<-ch).(*XfrmMsgExpire) if msg.XfrmState.Spi != state.Spi { t.Fatal("Received unexpected msg, spi does not match") } hardFound = msg.Hard || hardFound softFound = !msg.Hard || softFound if !hardFound || !softFound { t.Fatal("Missing expire msg: hard found:", hardFound, "soft found:", softFound) } }
// +build linux package netlink import ( "testing" "github.com/vishvananda/netlink/nl" ) func TestXfrmMonitorExpire(t *testing.T) { defer setUpNetlinkTest(t)() ch := make(chan XfrmMsg) done := make(chan struct{}) defer close(done) errChan := make(chan error) if err := XfrmMonitor(ch, nil, errChan, nl.XFRM_MSG_EXPIRE); err != nil { t.Fatal(err) } // Program state with limits state := getBaseState() state.Limits.TimeHard = 2 state.Limits.TimeSoft = 1 if err := XfrmStateAdd(state); err != nil { t.Fatal(err) } msg := (<-ch).(*XfrmMsgExpire) if msg.XfrmState.Spi != state.Spi || msg.Hard { t.Fatal("Received unexpected msg") } msg = (<-ch).(*XfrmMsgExpire) if msg.XfrmState.Spi != state.Spi || !msg.Hard { t.Fatal("Received unexpected msg") } }
Fix gold hoe charge level.
package joshie.harvest.api.core; import net.minecraft.item.ItemStack; /** Items that implement this interface are associated with a certain * ToolTier, this can affect various things **/ public interface ITiered { /** Returns the rating of this item. Values returned should * between 1-100% * * @param stack the item * @return the percentage complete **/ double getLevel(ItemStack stack); /** Increases the tools level * @param stack the item **/ void levelTool(ItemStack stack); /** Returns the tier of this item * * @param stack the item * @return the tier **/ ToolTier getTier(ItemStack stack); enum ToolTier { BASIC(0), COPPER(1), SILVER(2), GOLD(3), MYSTRIL(4), CURSED(5), BLESSED(5), MYTHIC(6); private final int level; ToolTier(int level) { this.level = level; } public int getToolLevel() { return level; } public boolean isGreaterThanOrEqualTo(ToolTier tier) { return this.ordinal() >= tier.ordinal() || ((tier == CURSED || tier == BLESSED) && (this == CURSED || this == BLESSED)); } } }
package joshie.harvest.api.core; import net.minecraft.item.ItemStack; /** Items that implement this interface are associated with a certain * ToolTier, this can affect various things **/ public interface ITiered { /** Returns the rating of this item. Values returned should * between 1-100% * * @param stack the item * @return the percentage complete **/ double getLevel(ItemStack stack); /** Increases the tools level * @param stack the item **/ void levelTool(ItemStack stack); /** Returns the tier of this item * * @param stack the item * @return the tier **/ ToolTier getTier(ItemStack stack); enum ToolTier { BASIC(0), COPPER(1), SILVER(2), GOLD(2), MYSTRIL(4), CURSED(5), BLESSED(5), MYTHIC(6); private final int level; ToolTier(int level) { this.level = level; } public int getToolLevel() { return level; } public boolean isGreaterThanOrEqualTo(ToolTier tier) { return this.ordinal() >= tier.ordinal() || ((tier == CURSED || tier == BLESSED) && (this == CURSED || this == BLESSED)); } } }
Fix latex build: make some unicode characters found in help work
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] source_suffix = '.rst' master_doc = 'index' project = 'Powerline' version = 'beta' release = 'beta' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_static_path = ['_static'] html_show_copyright = False latex_show_urls = 'footnote' latex_elements = { 'preamble': ''' \\DeclareUnicodeCharacter{22EF}{$\\cdots$} % Dots \\DeclareUnicodeCharacter{2665}{\\ding{170}} % Heart \\DeclareUnicodeCharacter{2746}{\\ding{105}} % Snow \\usepackage{pifont} ''', } on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we’re building docs locally try: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] source_suffix = '.rst' master_doc = 'index' project = 'Powerline' version = 'beta' release = 'beta' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' html_static_path = ['_static'] html_show_copyright = False on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we’re building docs locally try: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass
Fix compile error in example
package com.emc.example.client; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; import com.emc.example.client.dummy.SensorData; import com.emc.example.client.dummy.SensorEvent; import com.emc.nautilus.streaming.Producer; import com.emc.nautilus.streaming.ProducerConfig; import com.emc.nautilus.streaming.Serializer; import com.emc.nautilus.streaming.Stream; import com.emc.nautilus.streaming.StreamManager; public class StreamProducerSink { public StreamProducerSink(StreamManager streamManager, Socket clientSocket, Serializer<SensorEvent> serializer) { this.streamManager = streamManager; this.clientSocket = clientSocket; this.serializer = serializer; } StreamManager streamManager; private Socket clientSocket; private Serializer<SensorEvent> serializer; private boolean isRunning = true; //... public void run() throws IOException { DataInputStream rawTCP = new DataInputStream(clientSocket.getInputStream()); Stream stream = streamManager.getStream("rawSensorStream"); Producer<SensorEvent> producer = stream.createProducer(serializer, new ProducerConfig(null)); while (isRunning ) { SensorData sd = SensorData.fromTCP(rawTCP); String routingKey = sd.sensor_id; SensorEvent e = new SensorEvent(sd); producer.publish(routingKey, e); } } //... }
package com.emc.example.client; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; import com.emc.example.client.dummy.SensorData; import com.emc.example.client.dummy.SensorEvent; import com.emc.nautilus.streaming.Producer; import com.emc.nautilus.streaming.ProducerConfig; import com.emc.nautilus.streaming.Serializer; import com.emc.nautilus.streaming.Stream; import com.emc.nautilus.streaming.StreamManager; public class StreamProducerSink { public StreamProducerSink(StreamManager streamManager, Socket clientSocket, Serializer<SensorEvent> serializer) { this.streamManager = streamManager; this.clientSocket = clientSocket; this.serializer = serializer; } StreamManager streamManager; private Socket clientSocket; private Serializer<SensorEvent> serializer; private boolean isRunning = true; //... public void run() throws IOException { DataInputStream rawTCP = new DataInputStream(clientSocket.getInputStream()); Stream stream = streamManager.getStream("rawSensorStream"); Producer<SensorEvent> producer = stream.createProducer(serializer, new ProducerConfig()); while (isRunning ) { SensorData sd = SensorData.fromTCP(rawTCP); String routingKey = sd.sensor_id; SensorEvent e = new SensorEvent(sd); producer.publish(routingKey, e); } } //... }
Replace LDAP enum with DB
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.model; import java.util.HashMap; import java.util.Map; import org.gluu.persist.annotation.AttributeEnum; /** * Specify type of script location * * @author Yuriy Movchan Date: 10/07/2015 */ public enum ScriptLocationType implements AttributeEnum { DB("db", "Database"), FILE("file", "File"); private String value; private String displayName; private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>(); static { for (ScriptLocationType enumType : values()) { MAP_BY_VALUES.put(enumType.getValue(), enumType); } } ScriptLocationType(String value, String displayName) { this.value = value; this.displayName = displayName; } public String getValue() { return value; } public String getDisplayName() { return displayName; } public static ScriptLocationType getByValue(String value) { return MAP_BY_VALUES.get(value); } public Enum<? extends AttributeEnum> resolveByValue(String value) { return getByValue(value); } @Override public String toString() { return value; } }
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.model; import java.util.HashMap; import java.util.Map; import org.gluu.persist.annotation.AttributeEnum; /** * Specify type of script location * * @author Yuriy Movchan Date: 10/07/2015 */ public enum ScriptLocationType implements AttributeEnum { LDAP("ldap", "Ldap"), FILE("file", "File"); private String value; private String displayName; private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>(); static { for (ScriptLocationType enumType : values()) { MAP_BY_VALUES.put(enumType.getValue(), enumType); } } ScriptLocationType(String value, String displayName) { this.value = value; this.displayName = displayName; } public String getValue() { return value; } public String getDisplayName() { return displayName; } public static ScriptLocationType getByValue(String value) { return MAP_BY_VALUES.get(value); } public Enum<? extends AttributeEnum> resolveByValue(String value) { return getByValue(value); } @Override public String toString() { return value; } }
Add json to from vdf scripts Signed-off-by: Stany MARCEL <3e139d47b96f775f4bc13af807cbc2ea7c67e72b@gmail.com>
#!/usr/bin/env python from distutils.core import setup, Extension uinput = Extension('libuinput', sources = ['src/uinput.c']) setup(name='python-steamcontroller', version='1.0', description='Steam Controller userland driver', author='Stany MARCEL', author_email='stanypub@gmail.com', url='https://github.com/ynsta/steamcontroller', package_dir={'steamcontroller': 'src'}, packages=['steamcontroller'], scripts=['scripts/sc-dump.py', 'scripts/sc-xbox.py', 'scripts/vdf2json.py', 'scripts/json2vdf.py'], license='MIT', platforms=['Linux'], ext_modules=[uinput, ])
#!/usr/bin/env python from distutils.core import setup, Extension uinput = Extension('libuinput', sources = ['src/uinput.c']) setup(name='python-steamcontroller', version='1.0', description='Steam Controller userland driver', author='Stany MARCEL', author_email='stanypub@gmail.com', url='https://github.com/ynsta/steamcontroller', package_dir={'steamcontroller': 'src'}, packages=['steamcontroller'], scripts=['scripts/sc-dump.py', 'scripts/sc-xbox.py'], license='MIT', platforms=['Linux'], ext_modules=[uinput, ])
Use the Spring Cloud Context version from jhipster-dependencies
/** * Copyright 2013-2018 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see http://www.jhipster.tech/ * for more information. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const AWS_SSM_VERSION = '1.11.247'; const configuration = { aws: 'aws' }; const constants = { conf: configuration, AWS_SSM_VERSION }; module.exports = constants;
/** * Copyright 2013-2018 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see http://www.jhipster.tech/ * for more information. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const AWS_SSM_VERSION = '1.11.247'; const SPRING_CLOUD_CTX_VERSION = '1.3.0.RELEASE'; const configuration = { aws: 'aws' }; const constants = { conf: configuration, AWS_SSM_VERSION, SPRING_CLOUD_CTX_VERSION }; module.exports = constants;
Fix type in DataType test
<?php class DataTypeTest extends PHPUnit_Framework_TestCase { public function testAutoload() { $this->assertInstanceOf('DataType', new DataType); } public function testImportDataType() { $xml = new SimpleXMLElement(' <DataType dtName="Test" dtHandle="test"/> '); $DataType = new DataType; $dataType = $DataType->import($xml); $this->assertNotEmpty('dtID', $dataType); $this->assertEquals('Test', $dataType->dtName); $this->assertEquals('test', $dataType->dtHandle); } public function testImportDataTypeIncorrectElementName() { $xml = new SimpleXMLElement(' <Data dtName="Test" dtHandle="test"/> '); $DataType = new DataType; $this->setExpectedException('DataTypeException'); $DataType->import($xml); } }
<?php class DataTypeTest extends PHPUnit_Framework_TestCase { public function testAutoload() { $this->assertInstanceOf('DataType', new DataType); } public function testImportDataType() { $xml = new SimpleXMLElement(' <DataType dtName="Test" dtHandle="test"/> '); $DataType = new DataType; $dataType = $DataType->import($xml); $this->assertNotEmpty('dtID', $dataType); $this->assertEquals('Test', $dataType->dtName); $this->assertEquals('test', $dataType->dtHandle); } public function testImportDataTypeIncorrectElementName() { $xml = new SimpleXMLElement(' <Data dtName="Test" dtHandle="test"/> '); $DataType = new DataType; $dataType = new $DataType; $this->setExpectedException('DataTypeException'); $dataType->import($xml); } }
Allow <br /> and <p> in descriptions
import bleach DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p'] USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6', 'br', 'p'] def clean_for_user_description(html): """ Removes dangerous tags, including h1. """ return bleach.clean(html, tags=USER_DESCR_ALLOWED_TAGS, strip=True) def clean_for_description(html): """ Removes dangerous tags. """ return bleach.clean(html, tags=DESCR_ALLOWED_TAGS, strip=True) def clean_all(html): """ Removes *all* html tags. """ return bleach.clean(html, tags=[], styles=[], attributes=[], strip=True)
import bleach DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] USER_DESCR_ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h2', 'h3', 'h4', 'h5', 'h6'] def clean_for_user_description(html): """ Removes dangerous tags, including h1. """ return bleach.clean(html, tags=USER_DESCR_ALLOWED_TAGS, strip=True) def clean_for_description(html): """ Removes dangerous tags. """ return bleach.clean(html, tags=DESCR_ALLOWED_TAGS, strip=True) def clean_all(html): """ Removes *all* html tags. """ return bleach.clean(html, tags=[], styles=[], attributes=[], strip=True)
Use protractor sauceBuild parameter to mass the build number to Sauce
var fs = require('fs'); var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json')); var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES); browser_capabilities['name'] = 'GlobaLeaks-E2E'; browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER; browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH]; exports.config = { framework: 'jasmine', baseUrl: 'http://localhost:9000/', troubleshoot: false, directConnect: false, sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, sauceBuild: process.env.TRAVIS_BUILD_NUMBER, capabilities: browser_capabilities, params: { 'testFileDownload': false, 'verifyFileDownload': false, 'tmpDir': '/tmp/globaleaks-download', }, specs: specs, jasmineNodeOpts: { isVerbose: true, includeStackTrace: true, defaultTimeoutInterval: 360000 } };
var fs = require('fs'); var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json')); var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES); browser_capabilities['name'] = 'GlobaLeaks-E2E'; browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER; browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH]; exports.config = { framework: 'jasmine', baseUrl: 'http://localhost:9000/', troubleshoot: false, directConnect: false, sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, capabilities: browser_capabilities, params: { 'testFileDownload': false, 'verifyFileDownload': false, 'tmpDir': '/tmp/globaleaks-download', }, specs: specs, jasmineNodeOpts: { isVerbose: true, includeStackTrace: true, defaultTimeoutInterval: 360000 } };
Raise a more useful error for circular deps.
from spyc.graph import Vertex, find_cycle, topological_sort class CircularDependency(Exception): pass class Scheduler(object): def __init__(self): self.specs = {} def ensure(self, spec): """Require that ``spec`` is satisfied.""" if spec.key() in self.specs: self.specs[spec.key()].data.merge(spec) else: self.specs[spec.key()] = Vertex(spec) def depend(self, first, next): """Specify that ``first`` depends on ``next``. This also has the effect of invoking ``ensure`` on both resources. """ first.schedule(self) next.schedule(self) self.specs[first.key()].edges.add(self.specs[next.key()]) def apply(self): verticies = set(self.specs.values()) cycle = find_cycle(verticies) if cycle is not None: raise CircularDependency(cycle) for v in topological_sort(verticies): v.data.apply()
from spyc.graph import Vertex, find_cycle, topological_sort class Scheduler(object): def __init__(self): self.specs = {} def ensure(self, spec): """Require that ``spec`` is satisfied.""" if spec.key() in self.specs: self.specs[spec.key()].data.merge(spec) else: self.specs[spec.key()] = Vertex(spec) def depend(self, first, next): """Specify that ``first`` depends on ``next``. This also has the effect of invoking ``ensure`` on both resources. """ first.schedule(self) next.schedule(self) self.specs[first.key()].edges.add(self.specs[next.key()]) def apply(self): verticies = set(self.specs.values()) cycle = find_cycle(verticies) if cycle is not None: assert False # TODO proper checking for v in topological_sort(verticies): v.data.apply()