text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Normalize trailing spaces as well This doesn't remove spaces at the end, it just converts the last one to make it visible. I think the strategy of not having spaces at all in the end should go in a config option and shouldn't be a task of normalizeSpaces. Conflicts: src/content.js
var content = (function() { return { normalizeTags: function(element) { var i, j, node, sibling; var fragment = document.createDocumentFragment(); for (i = 0; i < element.childNodes.length; i++) { node = element.childNodes[i]; if(!node) continue; // skip empty tags, so they'll get removed if(node.nodeName !== 'BR' && !node.textContent) continue; if(node.nodeType === 1 && node.nodeName !== 'BR') { sibling = node; while((sibling = sibling.nextSibling) !== null) { if(!parser.isSameNode(sibling, node)) break; for(j = 0; j < sibling.childNodes.length; j++) { node.appendChild(sibling.childNodes[j].cloneNode(true)); } sibling.parentNode.removeChild(sibling); } this.normalizeTags(node); } fragment.appendChild(node.cloneNode(true)); } while (element.firstChild) { element.removeChild(element.firstChild); } element.appendChild(fragment); }, cleanInternals: function(element) { element.innerHTML = element.innerHTML.replace(/\u200B/g, '<br />'); }, normalizeSpaces: function(element) { if(!element) return; if(element.nodeType === 3) { element.nodeValue = element.nodeValue.replace(/^(\s)/, '\u00A0').replace(/(\s)$/, '\u00A0'); } else { this.normalizeSpaces(element.firstChild); this.normalizeSpaces(element.lastChild); } } }; })();
var content = (function() { return { normalizeTags: function(element) { var i, j, node, sibling; var fragment = document.createDocumentFragment(); for (i = 0; i < element.childNodes.length; i++) { node = element.childNodes[i]; if(!node) continue; // skip empty tags, so they'll get removed if(node.nodeName !== 'BR' && !node.textContent) continue; if(node.nodeType === 1 && node.nodeName !== 'BR') { sibling = node; while((sibling = sibling.nextSibling) !== null) { if(!parser.isSameNode(sibling, node)) break; for(j = 0; j < sibling.childNodes.length; j++) { node.appendChild(sibling.childNodes[j].cloneNode(true)); } sibling.parentNode.removeChild(sibling); } this.normalizeTags(node); } fragment.appendChild(node.cloneNode(true)); } while (element.firstChild) { element.removeChild(element.firstChild); } element.appendChild(fragment); }, cleanInternals: function(element) { element.innerHTML = element.innerHTML.replace(/\u200B/g, '<br />'); }, normalizeSpaces: function(element) { var firstChild = element.firstChild; if(!firstChild) return; if(firstChild.nodeType === 3) { firstChild.nodeValue = firstChild.nodeValue.replace(/^(\s)/, '\u00A0'); } else { this.normalizeSpaces(firstChild); } } }; })();
Remove migration dependency from Django 1.8
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='GenericLink', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ('url', models.URLField()), ('title', models.CharField(max_length=200)), ('description', models.TextField(max_length=1000, null=True, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('is_external', models.BooleanField(default=True, db_index=True)), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)), ], options={ 'ordering': ('-created_at',), 'verbose_name': 'Generic Link', 'verbose_name_plural': 'Generic Links', }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='GenericLink', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_id', models.PositiveIntegerField(db_index=True)), ('url', models.URLField()), ('title', models.CharField(max_length=200)), ('description', models.TextField(max_length=1000, null=True, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), ('is_external', models.BooleanField(default=True, db_index=True)), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)), ], options={ 'ordering': ('-created_at',), 'verbose_name': 'Generic Link', 'verbose_name_plural': 'Generic Links', }, ), ]
Use object destructuring for resident attributes
import newResidentAndResidencySchema from '/both/schemas/newResidentAndResidencySchema'; Meteor.methods({ addNewResidentAndResidency (document) { // set up validation context based on new resident and residency schama const validationContext = newResidentAndResidencySchema.newContext(); // Check if submitted document is valid const documentIsValid = validationContext.validate(document); if (documentIsValid) { // Get fields from object const { firstName, lastInitial, homeId, moveIn } = document; // Create new resident // TODO: migrate homeId out of resident schema const residentId = Residents.insert({ firstName, lastInitial, homeId }); if (residentId) { // Insert residency document const residencyId = Residencies.insert({ residentId, homeId, moveIn }); if (residencyId) { // Submission was successful return true; } else { // Could not create residency throw new Meteor.Error( 'could-not-create-residency', 'Could not create residency.' ) } } else { // Could not create resident throw new Meteor.Error( 'could-not-create-resident', 'Could not create resident.' ) } } else { // Document is not valid throw new Meteor.Error( 'resident-and-residency-invalid', 'Resident and residency document is not valid.' ) } } });
import newResidentAndResidencySchema from '/both/schemas/newResidentAndResidencySchema'; Meteor.methods({ addNewResidentAndResidency (document) { // set up validation context based on new resident and residency schama const validationContext = newResidentAndResidencySchema.newContext(); // Check if submitted document is valid const documentIsValid = validationContext.validate(document); if (documentIsValid) { // Get fields from object firstName = document.firstName; lastInitial = document.lastInitial; homeId = document.homeId; moveIn = document.moveIn; // Create new resident // TODO: migrate homeId out of resident schema const residentId = Residents.insert({ firstName, lastInitial, homeId }); if (residentId) { // Insert residency document const residencyId = Residencies.insert({ residentId, homeId, moveIn }); if (residencyId) { // Submission was successful return true; } else { // Could not create residency throw new Meteor.Error( 'could-not-create-residency', 'Could not create residency.' ) } } else { // Could not create resident throw new Meteor.Error( 'could-not-create-resident', 'Could not create resident.' ) } } else { // Document is not valid throw new Meteor.Error( 'resident-and-residency-invalid', 'Resident and residency document is not valid.' ) } } });
Set default time out for publish with confirm to 0
<?php namespace Fsalehpour\RabbitMQ\Facades; use Illuminate\Support\Facades\Facade; use PhpAmqpLib\Message\AMQPMessage; class AMQPFacade extends Facade { public static function basic_publish_with_response($channel, $exchange, $routing_key, $body, $headers = []) { $response = null; $corr_id = uniqid(); list ($callback_queue, ,) = $channel->queue_declare('', false, false, true, false); $callback = function ($msg) use ($corr_id, &$response) { if ($msg->get('correlation_id') == $corr_id) { $response = $msg->body; } }; $channel->basic_consume($callback_queue, '', false, false, false, false, $callback); $msg = new AMQPMessage($body, array_merge($headers, [ 'correlation_id' => $corr_id, 'reply_to' => $callback_queue ])); $channel->basic_publish($msg, $exchange, $routing_key); while (!$response) { $channel->wait(null, false, env('RABBITMQ_TIMEOUT', 0)); } return $response; } protected static function getFacadeAccessor() { return 'AMQP'; } }
<?php namespace Fsalehpour\RabbitMQ\Facades; use Illuminate\Support\Facades\Facade; use PhpAmqpLib\Message\AMQPMessage; class AMQPFacade extends Facade { public static function basic_publish_with_response($channel, $exchange, $routing_key, $body, $headers = []) { $response = null; $corr_id = uniqid(); list ($callback_queue, ,) = $channel->queue_declare('', false, false, true, false); $callback = function ($msg) use ($corr_id, &$response) { if ($msg->get('correlation_id') == $corr_id) { $response = $msg->body; } }; $channel->basic_consume($callback_queue, '', false, false, false, false, $callback); $msg = new AMQPMessage($body, array_merge($headers, [ 'correlation_id' => $corr_id, 'reply_to' => $callback_queue ])); $channel->basic_publish($msg, $exchange, $routing_key); while (!$response) { $channel->wait(null, false, env('RABBITMQ_TIMEOUT', 10)); } return $response; } protected static function getFacadeAccessor() { return 'AMQP'; } }
Remove unused ObjectDoesNotExist exception import
from django.core.management.base import BaseCommand, CommandError from subscriptions.models import Subscription class Command(BaseCommand): help = ("Active subscription holders need to be informed via audio file " "about the new missed call service.") def add_arguments(self, parser): parser.add_argument( '--audio', type=str, help='Audio file containing the notification of the new missed' ' call service.') def handle(self, *args, **options): audio_file = options['audio'] if not audio_file: raise CommandError('--audio_file is a required parameter') self.stdout.write("Processing active subscriptions ...") count = 0 active_subscriptions = Subscription.objects.filter( active=True, messageset__content_type="audio") for active_subscription in active_subscriptions.iterator(): # Add audio file to subscription meta_data. Not sure how we'll # handle translations here. if (not active_subscription.metadata["prepend_next_delivery"] or active_subscription.metadata["prepend_next_delivery"] is None): active_subscription.metadata["prepend_next_delivery"] = \ audio_file count += 1 if count > 0: self.stdout.write("Updated {} subscriptions with audio " "notifications".format(count)) else: self.stdout.write( "No subscriptions updated with audio file notes")
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand, CommandError from subscriptions.models import Subscription class Command(BaseCommand): help = ("Active subscription holders need to be informed via audio file " "about the new missed call service.") def add_arguments(self, parser): parser.add_argument( '--audio', type=str, help='Audio file containing the notification of the new missed' ' call service.') def handle(self, *args, **options): audio_file = options['audio'] if not audio_file: raise CommandError('--audio_file is a required parameter') self.stdout.write("Processing active subscriptions ...") count = 0 active_subscriptions = Subscription.objects.filter( active=True, messageset__content_type="audio") for active_subscription in active_subscriptions.iterator(): # Add audio file to subscription meta_data. Not sure how we'll # handle translations here. if (not active_subscription.metadata["prepend_next_delivery"] or active_subscription.metadata["prepend_next_delivery"] is None): active_subscription.metadata["prepend_next_delivery"] = \ audio_file count += 1 if count > 0: self.stdout.write("Updated {} subscriptions with audio " "notifications".format(count)) else: self.stdout.write( "No subscriptions updated with audio file notes")
Join channels where the bot isn't already on
#!/usr/bin/env python import asyncio import asyncio_redis import asyncio_redis.encoders import json import irc3 import traceback __version__ = '3.0alpha' class Redis2Irc(irc3.IrcBot): def __init__(self, conf, **kwargs): """ :type conf: dict """ super(Redis2Irc, self).__init__(**kwargs) self._conf = conf self.joined_channels = set() @property def conf(self): return self._conf @asyncio.coroutine def start(self): while True: try: yield from self.process_message() except Exception: self.log.critical(traceback.format_exc()) self.log.info("...restarting Redis listener in a few seconds.") yield from asyncio.sleep(5) @asyncio.coroutine def process_message(self): # Create connection connection = yield from asyncio_redis.Connection.create( host=self.conf.get('REDIS_HOST', 'localhost'), port=6379, ) while True: try: future = yield from connection.blpop([self.conf.get('REDIS_QUEUE_NAME', 'ircnotifier')]) message = json.loads(future.value) channels = set(message['channels']) message = message['message'] to_join = channels.difference(self.joined_channels) for chan in to_join: self.join(chan) for chan in channels: self.privmsg(chan, message) except: self.log.critical(traceback.format_exc()) yield from asyncio.sleep(1)
#!/usr/bin/env python import asyncio import asyncio_redis import asyncio_redis.encoders import json import irc3 import traceback __version__ = '3.0alpha' class Redis2Irc(irc3.IrcBot): def __init__(self, conf, **kwargs): """ :type conf: dict """ super(Redis2Irc, self).__init__(**kwargs) self._conf = conf @property def conf(self): return self._conf @asyncio.coroutine def start(self): while True: try: yield from self.process_message() except Exception: self.log.critical(traceback.format_exc()) self.log.info("...restarting Redis listener in a few seconds.") yield from asyncio.sleep(5) @asyncio.coroutine def process_message(self): # Create connection connection = yield from asyncio_redis.Connection.create( host=self.conf.get('REDIS_HOST', 'localhost'), port=6379, ) while True: try: future = yield from connection.blpop([self.conf.get('REDIS_QUEUE_NAME')]) message = json.loads(future.value) channels = message['channels'] message = message['message'] # FIXME: Actually join channel if they aren't joined already # FIXME: Actually send message, yo! except: self.log.critical(traceback.format_exc()) yield from asyncio.sleep(1) if __name__ == '__main__': main()
Add JSON convenience to InvalidRegistrationRequest.
import json from oic.oauth2.message import ErrorResponse from .util import should_fragment_encode class BearerTokenError(ValueError): pass class InvalidAuthorizationCode(ValueError): pass class InvalidAccessToken(ValueError): pass class InvalidRefreshToken(ValueError): pass class InvalidSubjectIdentifier(ValueError): pass class InvalidScope(ValueError): pass class InvalidClientAuthentication(ValueError): pass class InvalidAuthenticationRequest(ValueError): def __init__(self, message, parsed_request, oauth_error=None): super().__init__(message) self.request = parsed_request self.oauth_error = oauth_error def to_error_url(self): redirect_uri = self.request.get('redirect_uri') if redirect_uri and self.oauth_error: error_resp = ErrorResponse(error=self.oauth_error, error_message=str(self)) return error_resp.request(redirect_uri, should_fragment_encode(self.request)) return None class AuthorizationError(Exception): pass class InvalidTokenRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error class InvalidUserinfoRequest(ValueError): pass class InvalidClientRegistrationRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error def to_json(self): error = {'error': self.oauth_error, 'error_description': str(self)} return json.dumps(error)
from oic.oauth2.message import ErrorResponse from .util import should_fragment_encode class BearerTokenError(ValueError): pass class InvalidAuthorizationCode(ValueError): pass class InvalidAccessToken(ValueError): pass class InvalidRefreshToken(ValueError): pass class InvalidSubjectIdentifier(ValueError): pass class InvalidScope(ValueError): pass class InvalidClientAuthentication(ValueError): pass class InvalidAuthenticationRequest(ValueError): def __init__(self, message, parsed_request, oauth_error=None): super().__init__(message) self.request = parsed_request self.oauth_error = oauth_error def to_error_url(self): redirect_uri = self.request.get('redirect_uri') if redirect_uri and self.oauth_error: error_resp = ErrorResponse(error=self.oauth_error, error_message=str(self)) return error_resp.request(redirect_uri, should_fragment_encode(self.request)) return None class AuthorizationError(Exception): pass class InvalidTokenRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error class InvalidUserinfoRequest(ValueError): pass class InvalidClientRegistrationRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error
Fix bug due to wrong arguments order.
"""This module contains the main wrapper class.""" class BaseWrapper: """Define base template for function wrapper classes. """ def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args, **kwargs): raise NotImplementedError class NumpyWrapper(BaseWrapper): """Function wrapper for numpy's random functions. Allows easy usage avoiding the creation anonymous lambda functions. In addition, the `size` attribute is adjusted automatically. For instance, instead of writing 'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])' you may simply write 'ts.random.randint(low=1, high=10)'. """ def __init__(self, func, size="arg"): super(NumpyWrapper, self).__init__(func) self.size = size def __call__(self, *args, **kwargs): if self.size == "arg": def wrapped(x): return self.func(x.shape[0], *args, **kwargs) elif self.size == "kwarg": def wrapped(x): return self.func(*args, size=x.shape[0], **kwargs) else: raise ValueError("Size argument must be 'arg' or 'kwarg'.") wrapped.__doc__ = self.func.__doc__ return wrapped
"""This module contains the main wrapper class.""" class BaseWrapper: """Define base template for function wrapper classes. """ def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args, **kwargs): raise NotImplementedError class NumpyWrapper(BaseWrapper): """Function wrapper for numpy's random functions. Allows easy usage avoiding the creation anonymous lambda functions. In addition, the `size` attribute is adjusted automatically. For instance, instead of writing 'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])' you may simply write 'ts.random.randint(low=1, high=10)'. """ def __init__(self, func, size="arg"): super(NumpyWrapper, self).__init__(func) self.size = size def __call__(self, *args, **kwargs): if self.size == "arg": def wrapped(x): return self.func(*args, x.shape[0], **kwargs) elif self.size == "kwarg": def wrapped(x): return self.func(*args, size=x.shape[0], **kwargs) else: raise ValueError("Size argument must be 'arg' or 'kwarg'.") wrapped.__doc__ = self.func.__doc__ return wrapped
Add balance checking test round
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='https://di.uoa.gr/?breach=%s', prefix='test', alphabet='0123456789' ) self.victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=self.victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] # Balance checking self.balance_victim = Victim.objects.create( target=target, sourceip='192.168.10.141', snifferendpoint='http://localhost/' ) balance_round = Round.objects.create( victim=self.balance_victim, amount=1, knownsecret='testsecret', knownalphabet='0123', roundcardinality=3 )
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='https://di.uoa.gr/?breach=%s', prefix='test', alphabet='0123456789' ) self.victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=self.victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] # Balance checking self.balance_victim = Victim.objects.create( target=target, sourceip='192.168.10.141', snifferendpoint='http://localhost/' )
Change name of test to avoid collision This was spotted by coveralls.
import sys if sys.hexversion < 0x02070000: import unittest2 as unittest else: import unittest from hypothesis import given, example from hypothesis.extra.datetime import datetimes from calexicon.calendars import ProlepticGregorianCalendar, JulianCalendar from calexicon.dates import DateWithCalendar, InvalidDate class CalendarTest(unittest.TestCase): calendar = None def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) self.assertEqual(d.calendar, self.calendar.__class__) def check_invalid_date(self, year, month, day): self.assertRaises(InvalidDate, lambda : self.calendar.date(year, month, day)) @given(datetimes(timezones=[])) def test_date_strings(self, dt): if self.calendar is None: return d = dt.date() dc = self.calendar.from_date(d) self.assertIsNotNone(dc.__str__()) @given(datetimes(timezones=[])) def test_native_representation(self, dt): if self.calendar is None: return d = dt.date() dc = self.calendar.from_date(d) self.assertIsNotNone(dc.native_representation()) def display_string_comparison(self, year, month, day, expected): d = self.calendar.date(year, month, day) self.assertEqual(d.__str__(), expected)
import sys if sys.hexversion < 0x02070000: import unittest2 as unittest else: import unittest from hypothesis import given, example from hypothesis.extra.datetime import datetimes from calexicon.calendars import ProlepticGregorianCalendar, JulianCalendar from calexicon.dates import DateWithCalendar, InvalidDate class CalendarTest(unittest.TestCase): calendar = None def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) self.assertEqual(d.calendar, self.calendar.__class__) def check_invalid_date(self, year, month, day): self.assertRaises(InvalidDate, lambda : self.calendar.date(year, month, day)) @given(datetimes(timezones=[])) def test_date_strings(self, dt): if self.calendar is None: return d = dt.date() dc = self.calendar.from_date(d) self.assertIsNotNone(dc.__str__()) @given(datetimes(timezones=[])) def test_date_strings(self, dt): if self.calendar is None: return d = dt.date() dc = self.calendar.from_date(d) self.assertIsNotNone(dc.native_representation()) def display_string_comparison(self, year, month, day, expected): d = self.calendar.date(year, month, day) self.assertEqual(d.__str__(), expected)
Read all records from the file
import argparse, csv, datetime, time def run_main(): fails = list() succeeds = list() not_yet = list() path = file_path() # read file with open(path) as f: reader = csv.reader(f) for row in reader: status = row[0] if status == 'F': fails.append(row) elif status == 'S': succeeds.append(row) else: not_yet.append(row) # evaluate measurements now = datetime.datetime.now() for row in list(not_yet): evaluate_time = datetime.datetime(*(time.strptime(row[1], '%Y-%m-%d %H:%M:%S')[:6])) if evaluate_time < now: print "Time to evaluate:", row[2], "\n Is it true?" user_input = raw_input() if user_input.capitalize().startswith('Y'): succeeds.append(row) else: fails .append(row) not_yet.remove(row) # print total statistics total_done = len(fails) + len(succeeds) if total_done > 0: percentage = '%d%%' % (float(100 * len(succeeds)) / float(total_done)) else: percentage = 'N/A' print "Succesful predictions:", percentage, ", not done yet:", len(not_yet) def file_path(): parser = argparse.ArgumentParser() parser.add_argument("path") args = parser.parse_args() return args.path
import argparse, csv, datetime, time def run_main(): fails = 0 succeeds = 0 not_yet = list() path = file_path() # read file with open(path) as f: reader = csv.reader(f) for row in reader: status = row[0] if status == 'F': fails = fails + 1 elif status == 'S': succeeds = succeeds + 1 else: not_yet.append(row) # evaluate measurements now = datetime.datetime.now() for row in list(not_yet): evaluate_time = datetime.datetime(*(time.strptime(row[1], '%Y-%m-%d %H:%M:%S')[:6])) if evaluate_time < now: print "Time to evaluate:", row[2], "\n Is it true?" user_input = raw_input() if user_input.capitalize().startswith('Y'): succeeds = succeeds + 1 else: fails = fails + 1 not_yet.remove(row) # print total statistics total_done = fails + succeeds if total_done > 0: percentage = '%d%%' % (float(100 * succeeds) / float(total_done)) else: percentage = 'N/A' print "Succesful predictions:", percentage, ", not done yet:", len(not_yet) def file_path(): parser = argparse.ArgumentParser() parser.add_argument("path") args = parser.parse_args() return args.path
Increase only minor in version number
from os.path import dirname, join from setuptools import setup, find_packages version = '0.2.1' def read(fname): return open(join(dirname(__file__), fname)).read() setup(name='django-apptemplates', version=version, description='Django template loader that allows you to load and' 'override a template from a specific Django application.', long_description=read('README.rst'), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Software Development :: Libraries :: Application Frameworks', # noqa 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='django templates', author='Konrad Wojas', author_email='[email protected]', maintainer='Tomas Zulberti', url='http://bitbucket.org/tzulberti/django-apptemplates/', license='MIT License', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, )
from os.path import dirname, join from setuptools import setup, find_packages version = '0.3' def read(fname): return open(join(dirname(__file__), fname)).read() setup(name='django-apptemplates', version=version, description='Django template loader that allows you to load and' 'override a template from a specific Django application.', long_description=read('README.rst'), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Software Development :: Libraries :: Application Frameworks', # noqa 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='django templates', author='Konrad Wojas', author_email='[email protected]', maintainer='Tomas Zulberti', url='http://bitbucket.org/tzulberti/django-apptemplates/', license='MIT License', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, )
Delete any files that get moved.
# -*- coding: utf-8 -*- """ test_collectr ------------- Some functions to test the collectr library. :copyright: (c) 2013 Cory Benfield :license: MIT License, for details see LICENSE. """ import unittest import collectr class CollectrTest(unittest.TestCase): """ Tests for the collectr library. """ def setUp(self): self.dir = collectr.StaticDir('test/fixtures/dirB') def tearDown(self): self.dir = None try: # Delete the files if they exist, otherwise mask failure. self.old_call('rm -rf test/fixtures/dirB/css') self.old_call('rm -rf test/fixtures/dirB/js') except OSError: pass def test_enumerate_files(self): result = ['test/fixtures/dirA/css/css1.css', 'test/fixtures/dirA/css/css2.css', 'test/fixtures/dirA/js/script1.js', 'test/fixtures/dirA/js/script2.js'] files = self.dir.enumerate_files('test/fixtures/dirA') self.assertEqual(files, result) def test_enumerate_files_with_filter(self): result = ['test/fixtures/dirB/img/img1.jpg', 'test/fixtures/dirB/img/img3.tiff'] self.dir.ignore = ['.*\.png'] files = self.dir.enumerate_files('test/fixtures/dirB') self.assertEqual(files, result) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """ test_collectr ------------- Some functions to test the collectr library. :copyright: (c) 2013 Cory Benfield :license: MIT License, for details see LICENSE. """ import unittest import collectr class CollectrTest(unittest.TestCase): """ Tests for the collectr library. """ def setUp(self): self.dir = collectr.StaticDir('test/fixtures/dirB') def tearDown(self): self.dir = None def test_enumerate_files(self): result = ['test/fixtures/dirA/css/css1.css', 'test/fixtures/dirA/css/css2.css', 'test/fixtures/dirA/js/script1.js', 'test/fixtures/dirA/js/script2.js'] files = self.dir.enumerate_files('test/fixtures/dirA') self.assertEqual(files, result) def test_enumerate_files_with_filter(self): result = ['test/fixtures/dirB/img/img1.jpg', 'test/fixtures/dirB/img/img3.tiff'] self.dir.ignore = ['.*\.png'] files = self.dir.enumerate_files('test/fixtures/dirB') self.assertEqual(files, result) if __name__ == '__main__': unittest.main()
Comment out some useless code in challenges
from django.http import HttpResponse from django.shortcuts import render from .models import Challenge def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) ''' def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Challenge # from .forms import DocumentForm def download(req): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response def index(request): challenges = Challenge.objects.all() return render(request, 'challenges/index.html', {'challenges': challenges}) ''' path=settings.MEDIA_ROOT file_list =os.listdir(path) return render(request,'challenges/index.html', {'files': file_list}) ''' def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'challenges/upload.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'challenges/upload.html') def upload2(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/jeopardy') else: form = DocumentForm() return render(request, 'challenges/upload2.html', { 'form': form }) def textBased(request): challenges = Challenge.objects.all() return render(request, 'challenges/textBased.html', {'challenges': challenges})
Check that query params are actually strings Previously `toLowerCase` could fail because it tried to perform the operation on something else than a string.
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = is.string(o[p[0]])? o[p[0]].toLowerCase(): ''; var b = is.string(p[1])? p[1].toLowerCase(): ''; return minimatch(a, b, { matchBase: true }); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b, { matchBase: true }); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
Fix api controller lookup dir
<?php namespace App\Http\Controllers\API; use function OpenApi\scan; /** * @OA\OpenApi( * openapi="3.0.0", * @OA\Info( * title="OParl Developer Platform API", * description="Meta information concerning the OParl ecosystem", * version="0", * @OA\License( * name="CC-4.0-BY", * url="https://creativecommons.org/licenses/by/4.0/" * ) * ) * ) */ class ApiController { /** * Return the dynamically updated swagger.json for the meta endpoints. * * @return \Symfony\Component\HttpFoundation\Response */ public function openApiJson() { $openApi = scan([base_path('app/Http/Controllers/API'), app_path('Model')]); return response( $openApi, 200, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*', ] ); } /** * Index page for the api. * * @return \Symfony\Component\HttpFoundation\Response */ public function index() { return view('api.index'); } }
<?php namespace App\Http\Controllers\API; use function OpenApi\scan; /** * @OA\OpenApi( * openapi="3.0.0", * @OA\Info( * title="OParl Developer Platform API", * description="Meta information concerning the OParl ecosystem", * version="0", * @OA\License( * name="CC-4.0-BY", * url="https://creativecommons.org/licenses/by/4.0/" * ) * ) * ) */ class ApiController { /** * Return the dynamically updated swagger.json for the meta endpoints. * * @return \Symfony\Component\HttpFoundation\Response */ public function openApiJson() { $openApi = scan([base_path('lib/Api/Controllers'), app_path('Model')]); return response( $openApi, 200, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*', ] ); } /** * Index page for the api. * * @return \Symfony\Component\HttpFoundation\Response */ public function index() { return view('api.index'); } }
Fix problem with english system
document.addEventListener("DOMContentLoaded", function(event) { safari.self.addEventListener("message", messageHandler); safari.self.addEventListener("refreshVideoState",messageHandler); }); safari.self.addEventListener("activate", tabChanged); function messageHandler(event) { if (event.name === "enablePiP") { document.querySelectorAll('video')[0].webkitSetPresentationMode('picture-in-picture'); } else if (event.name == "checkForVideo"){ lookForVideo(); } } function lookForVideo(){ if (window == window.top){ if (isAVideoOnPage()){ console.log("Found a video on top"); safari.extension.dispatchMessage("videoFound"); } else{ console.log("Found no video on top"); safari.extension.dispatchMessage("noVideoFound"); } } else { if (isAVideoOnPage()){ console.log("Found video somewhere else"); safari.extension.dispatchMessage("videoFound"); } } } function tabChanged(event) { console.log("Changed a tab"); safari.extension.dispatchMessage("tabChange"); } //checks if there is a video on the page and returns true if there is one function isAVideoOnPage(){ if (document.querySelectorAll("video").length > 0){ return true; } else{ return false; } }
document.addEventListener("DOMContentLoaded", function(event) { safari.self.addEventListener("message", messageHandler); safari.self.addEventListener("refreshVideoState",messageHandler); }); safari.self.addEventListener("activate", tabChanged); function messageHandler(event) { if (event.name === "enablePiP") { document.querySelectorAll("video")[0].webkitSetPresentationMode("picture-in-picture"); } else if (event.name == "checkForVideo"){ lookForVideo(); } } function lookForVideo(){ if (window == window.top){ if (isAVideoOnPage()){ console.log("Found a video on top"); safari.extension.dispatchMessage("videoFound"); } else{ console.log("Found no video on top"); safari.extension.dispatchMessage("noVideoFound"); } } else { if (isAVideoOnPage()){ console.log("Found video somewhere else"); safari.extension.dispatchMessage("videoFound"); } } } function tabChanged(event) { console.log("Changed a tab"); safari.extension.dispatchMessage("tabChange"); } //checks if there is a video on the page and returns true if there is one function isAVideoOnPage(){ if (document.querySelectorAll("video").length > 0){ return true; } else{ return false; } }
Fix missing service in lecturerFactory
(function() { 'use strict'; angular .module('lecturer') .factory('lecturerFactory', lecturerFactory); /* @ngInject */ function lecturerFactory(lecturerService, $location) { var username = ''; var observerCallbacks = []; var Login = false; var service = { login: login, checkUserToken: checkUserToken, logout: logout, registerObserverCallback: registerObserverCallback }; return service; function login(credentials) { if (!Login) { Login = lecturerService.login; } var SHA256 = new Hashes.SHA256(); SHA256.setUTF8(true); // Prevent binding the hashed password into the input. var form = { email: credentials.email, passsword: SHA256.hex(credentials.password) }; Login.save(form, loginSuccess, logoutSuccess); } function checkUserToken(onError) { if (!Login) { Login = lectureService.login; } Login.get(loginSuccess, function() { logoutSuccess(); onError(); }); } function logout() { lectureService.logout .save(success); function success() { logoutSuccess(); $location.path('/'); } } function registerObserverCallback(callback) { observerCallbacks.push(callback); } function loginSuccess(response) { angular .forEach(observerCallbacks, function(callback) { callback(true, response.username); }); } function logoutSuccess() { angular .forEach(observerCallbacks, function(callback) { callback(false); }); } } })();
(function() { 'use strict'; angular .module('lecturer') .factory('lecturerFactory', lecturerFactory); /* @ngInject */ function lecturerFactory(lecturerService) { var username = ''; var observerCallbacks = []; var Login = false; var service = { login: login, checkUserToken: checkUserToken, logout: logout, registerObserverCallback: registerObserverCallback }; return service; function login(credentials) { if (!Login) { Login = lecturerService.login; } var SHA256 = new Hashes.SHA256(); SHA256.setUTF8(true); // Prevent binding the hashed password into the input. var form = { email: credentials.email, passsword: SHA256.hex(credentials.password) }; Login.save(form, loginSuccess, logoutSuccess); } function checkUserToken(onError) { if (!Login) { Login = lectureService.login; } Login.get(loginSuccess, function() { logoutSuccess(); onError(); }); } function logout() { lectureService.logout .save(success); function success() { logoutSuccess(); $location.path('/'); } } function registerObserverCallback(callback) { observerCallbacks.push(callback); } function loginSuccess(response) { angular .forEach(observerCallbacks, function(callback) { callback(true, response.username); }); } function logoutSuccess() { angular .forEach(observerCallbacks, function(callback) { callback(false); }); } } })();
Add missing article to DummyConfigResource docstring
var _ = require('lodash'); var resources = require('../dummy/resources'); var DummyResource = resources.DummyResource; var DummyConfigResource = DummyResource.extend(function(self, name, store) { /**class:DummyConfigResource(name) Handles api requests to the config resource from :class:`DummyApi`. :param string name: The name of the resource. Should match the name given in api requests. */ DummyResource.call(self, name); /**attribute:DummyConfigResource.store An object containing the sandbox's config data. Properties do not need to be JSON-stringified, this is done when the config is retrieved using a ``'config.get'`` api request. */ self.store = store || {config: {}}; /**attribute:DummyConfigResource.app A shortcut to DummyConfigResource.store.config (the app's config). */ Object.defineProperty(self, 'app', { get: function() { return self.store.config; }, set: function(v) { self.store.config = v; return v; } }); self.handlers.get = function(cmd) { var value = self.store[cmd.key]; if (_.isUndefined(value)) { value = null; } return { success: true, value: JSON.stringify(value) }; }; }); this.DummyConfigResource = DummyConfigResource;
var _ = require('lodash'); var resources = require('../dummy/resources'); var DummyResource = resources.DummyResource; var DummyConfigResource = DummyResource.extend(function(self, name, store) { /**class:DummyConfigResource(name) Handles api requests to the config resource from :class:`DummyApi`. :param string name: The name of the resource. Should match the name given in api requests. */ DummyResource.call(self, name); /**attribute:DummyConfigResource.store An object containing sandbox's config data. Properties do not need to be JSON-stringified, this is done when the config is retrieved using a ``'config.get'`` api request. */ self.store = store || {config: {}}; /**attribute:DummyConfigResource.app A shortcut to DummyConfigResource.store.config (the app's config). */ Object.defineProperty(self, 'app', { get: function() { return self.store.config; }, set: function(v) { self.store.config = v; return v; } }); self.handlers.get = function(cmd) { var value = self.store[cmd.key]; if (_.isUndefined(value)) { value = null; } return { success: true, value: JSON.stringify(value) }; }; }); this.DummyConfigResource = DummyConfigResource;
Fix bug where reseting jobs would cause vue iso_date filter to break.
const utilitiesMixin = { methods: { getStatus: function(job) { if (!job.pid && !job.start && !job.end && !job.message) return "pending"; else if (job.pid && job.start && !job.end && !job.message) return "running"; else if (job.pid && job.start && job.end && !job.message) return "completed"; else if (job.message) return "failed"; }, }, filters: { date: function(value) { var options = { year: "numeric", month: "2-digit", day: "numeric" }; return value ? new Date(value).toLocaleString('en-US', options) : ''; }, iso_date: function(value) { let iso_date = ''; if(value) { iso_date = new Date(new Date(value).toString().split('GMT')[0]+' UTC') .toISOString().split('.')[0]+'Z'; } return iso_date; } }, } export default utilitiesMixin;
const utilitiesMixin = { methods: { getStatus: function(job) { if (!job.pid && !job.start && !job.end && !job.message) return "pending"; else if (job.pid && job.start && !job.end && !job.message) return "running"; else if (job.pid && job.start && job.end && !job.message) return "completed"; else if (job.message) return "failed"; }, }, filters: { date: function(value) { var options = { year: "numeric", month: "2-digit", day: "numeric" }; return value ? new Date(value).toLocaleString('en-US', options) : ''; }, iso_date: function(value) { let iso_date = new Date(new Date(value).toString().split('GMT')[0]+' UTC') .toISOString().split('.')[0]+'Z'; return value ? iso_date : ''; } }, } export default utilitiesMixin;
Remove creating multiple instances of target for execution
var CronJob = require('cron').CronJob, logger = require('./logger'), TargetNodes = require('./targets/nodes').TargetNodes, job, state, target = new TargetNodes({}), STATE = { IDLE: 0, ACTIVE: 1 }; function setIdle() { state = STATE.IDLE; } function setActive() { state = STATE.ACTIVE; } function isActive() { return state === STATE.ACTIVE; } function execute () { logger.info('=== CRON CHECK FOR DATA START ===', module); if (isActive()) { logger.warn('Previous synchronization process was not completed yet', module); return; } setActive(); return target.execute() .then(function () { setIdle(); logger.info('=== CRON CHECK FOR DATA END ===', module); }) .fail(function () { setIdle(); logger.error('=== CRON CHECK FOR DATA ERROR ===', module); }); } module.exports = { /** * Initialize cron job for commit and push tasks perform */ init: function () { state = STATE.IDLE; job = new CronJob({ cronTime: '0 */1 * * * *', onTick: execute, start: true }); } };
var CronJob = require('cron').CronJob, logger = require('./logger'), TargetNodes = require('./targets/nodes').TargetNodes, job, state, STATE = { IDLE: 0, ACTIVE: 1 }; function setIdle() { state = STATE.IDLE; } function setActive() { state = STATE.ACTIVE; } function isActive() { return state === STATE.ACTIVE; } function execute () { logger.info('=== CRON CHECK FOR DATA START ===', module); if (isActive()) { logger.warn('Previous synchronization process was not completed yet', module); return; } setActive(); return (new TargetNodes({})).execute() .then(function () { setIdle(); logger.info('=== CRON CHECK FOR DATA END ===', module); }) .fail(function () { setIdle(); logger.error('=== CRON CHECK FOR DATA ERROR ===', module); }); } module.exports = { /** * Initialize cron job for commit and push tasks perform */ init: function () { state = STATE.IDLE; job = new CronJob({ cronTime: '0 */1 * * * *', onTick: execute, start: true }); } };
Fix possible ClassCastException in closeables composer
package com.annimon.stream.internal; import java.io.Closeable; public final class Compose { private Compose() { } public static Runnable runnables(final Runnable a, final Runnable b) { return new Runnable() { @Override public void run() { try { a.run(); } catch (Throwable e1) { try { b.run(); } catch (Throwable ignore) { } handleException(e1); return; } b.run(); } }; } public static Runnable closeables(final Closeable a, final Closeable b) { return new Runnable() { @Override public void run() { try { a.close(); } catch (Throwable e1) { try { b.close(); } catch (Throwable ignore) { } handleException(e1); return; } try { b.close(); } catch (Throwable e2) { handleException(e2); } } }; } private static void handleException(Throwable e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new RuntimeException(e); } } }
package com.annimon.stream.internal; import java.io.Closeable; public final class Compose { private Compose() { } public static Runnable runnables(final Runnable a, final Runnable b) { return new Runnable() { @Override public void run() { try { a.run(); } catch (Throwable e1) { try { b.run(); } catch (Throwable ignore) { } if (e1 instanceof RuntimeException) { throw (RuntimeException) e1; } throw (Error) e1; } b.run(); } }; } public static Runnable closeables(final Closeable a, final Closeable b) { return new Runnable() { @Override public void run() { try { a.close(); } catch (Throwable e1) { try { b.close(); } catch (Throwable ignore) { } if (e1 instanceof RuntimeException) { throw (RuntimeException) e1; } throw (Error) e1; } try { b.close(); } catch (Throwable e2) { if (e2 instanceof RuntimeException) { throw (RuntimeException) e2; } else if (e2 instanceof Error) { throw (Error) e2; } else { throw new RuntimeException(e2); } } } }; } }
Fix es6 error on node 5
/* eslint-disable */ var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); module.exports = { // debug: true, // webpack_assets_file_path: 'webpack-assets.json', // webpack_stats_file_path: 'webpack-stats.json', assets: { images: { extensions: ['png', 'jpg', 'jpeg', 'gif'], parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, fonts: { extensions: ['eot', 'ttf', 'woff', 'woff2'], parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, svg: { extension: 'svg', parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, style_modules: { extensions: ['css', 'scss'], filter: function (module, regex, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log); } return regex.test(module.name); }, path: function (module, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log); } return module.name; }, parser: function (module, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log); } return module.source; }, }, }, };
/* eslint object-shorthand:0 func-names:0 */ const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); module.exports = { // debug: true, // webpack_assets_file_path: 'webpack-assets.json', // webpack_stats_file_path: 'webpack-stats.json', assets: { images: { extensions: ['png', 'jpg', 'jpeg', 'gif'], parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, fonts: { extensions: ['eot', 'ttf', 'woff', 'woff2'], parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, svg: { extension: 'svg', parser: WebpackIsomorphicToolsPlugin.url_loader_parser, }, style_modules: { extensions: ['css', 'scss'], filter: function (module, regex, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log); } return regex.test(module.name); }, path: function (module, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log); } return module.name; }, parser: function (module, options, log) { if (options.development) { return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log); } return module.source; }, }, }, };
Make the '--add-home-links' option work for any value that evaluates to a bool
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't already have one. " "If main menus for any site do not have menu items, identify the " "'home' and 'section root' pages for the site, and menu items linking " "to those to the menu. Assumes 'site.root_page' is the 'home page' " "and its children are the 'section root' pages") def add_arguments(self, parser): parser.add_argument( '--add-home-links', action='store_true', dest='add-home-links', default=False, help="Add menu items for 'home' pages", ) def handle(self, *args, **options): for site in Site.objects.all(): menu = app_settings.MAIN_MENU_MODEL_CLASS.get_for_site(site) if not menu.get_menu_items_manager().exists(): menu.add_menu_items_for_pages( site.root_page.get_descendants( inclusive=bool(options['add-home-links']) ).filter(depth__lte=site.root_page.depth + 1) )
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Site from wagtailmenus import app_settings logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Create a 'main menu' for any 'Site' that doesn't already have one. " "If main menus for any site do not have menu items, identify the " "'home' and 'section root' pages for the site, and menu items linking " "to those to the menu. Assumes 'site.root_page' is the 'home page' " "and its children are the 'section root' pages") def add_arguments(self, parser): parser.add_argument( '--add-home-links', action='store_true', dest='add-home-links', default=False, help="Add menu items for 'home' pages", ) def handle(self, *args, **options): for site in Site.objects.all(): menu = app_settings.MAIN_MENU_MODEL_CLASS.get_for_site(site) if not menu.get_menu_items_manager().exists(): menu.add_menu_items_for_pages( site.root_page.get_descendants( inclusive=options['add-home-links'] ).filter(depth__lte=site.root_page.depth + 1) )
Set minimum numpy version to 1.11, due to backwards compatibility issues for numpy.datetime64 (localtime used by default)
from setuptools import setup from tools.generate_pyi import generate_pyi def main(): # Generate .pyi files import pyxtf.xtf_ctypes generate_pyi(pyxtf.xtf_ctypes) import pyxtf.vendors.kongsberg generate_pyi(pyxtf.vendors.kongsberg) # Run setup script setup(name='pyxtf', version='0.1', description='eXtended Triton Format (XTF) file interface', author='Oystein Sture', author_email='[email protected]', url='https://github.com/oysstu/pyxtf', license='MIT', setup_requires=['numpy>=1.11'], install_requires=['numpy>=1.11'], packages=['pyxtf', 'pyxtf.vendors'], package_data={'':['*.pyi']}, use_2to3=False, classifiers=[ 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Other Audience', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Programming Language:: Python:: 3:: Only' ]) if __name__ == '__main__': main()
from setuptools import setup from tools.generate_pyi import generate_pyi def main(): # Generate .pyi files import pyxtf.xtf_ctypes generate_pyi(pyxtf.xtf_ctypes) import pyxtf.vendors.kongsberg generate_pyi(pyxtf.vendors.kongsberg) # Run setup script setup(name='pyxtf', version='0.1', description='eXtended Triton Format (XTF) file interface', author='Oystein Sture', author_email='[email protected]', url='https://github.com/oysstu/pyxtf', license='MIT', setup_requires=['numpy'], install_requires=['numpy'], packages=['pyxtf', 'pyxtf.vendors'], package_data={'':['*.pyi']}, use_2to3=False, classifiers=[ 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Other Audience', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Topic :: Scientific/Engineering', 'Programming Language:: Python:: 3:: Only' ]) if __name__ == '__main__': main()
Allow auditor to create relationship in context This allows the auditor to map objects to the audit but not to unmap them while not giving him edit permissions on the audit.
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: [email protected] # Maintained By: [email protected] scope = "Audit" description = """ The permissions required by an auditor to access relevant resources for the program being audited. """ permissions = { "read": [ "Audit", "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", "Meeting", "ObjectDocument", "ObjectPerson", "Relationship", "Document", "Meeting", "UserRole", "Context", ], "create": [ "Request", "ControlAssessment", "Issue", "Relationship", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", ], "view_object_page": [ "__GGRC_ALL__" ], "update": [ "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse" ], "delete": [ "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", ], }
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: [email protected] # Maintained By: [email protected] scope = "Audit" description = """ The permissions required by an auditor to access relevant resources for the program being audited. """ permissions = { "read": [ "Audit", "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", "Meeting", "ObjectDocument", "ObjectPerson", "Relationship", "Document", "Meeting", "UserRole", "Context", ], "create": [ "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", ], "view_object_page": [ "__GGRC_ALL__" ], "update": [ "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse" ], "delete": [ "Request", "ControlAssessment", "Issue", "DocumentationResponse", "InterviewResponse", "PopulationSampleResponse", ], }
Add assertions to ensure only valid s3content ids can be created
package org.springframework.content.s3; import org.springframework.util.Assert; import java.io.Serializable; public final class S3ContentId implements Serializable { private String bucket; private String objectId; public S3ContentId(String bucket, String objectId) { Assert.hasText(bucket, "bucket must be specified"); Assert.hasText(objectId, "objectId must be specified"); this.bucket = bucket; this.objectId = objectId; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } @Override public String toString() { return "S3ContentId{" + "bucket='" + bucket + '\'' + ", objectId='" + objectId + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; S3ContentId that = (S3ContentId) o; if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false; return objectId != null ? objectId.equals(that.objectId) : that.objectId == null; } @Override public int hashCode() { int result = bucket != null ? bucket.hashCode() : 0; result = 31 * result + (objectId != null ? objectId.hashCode() : 0); return result; } }
package org.springframework.content.s3; import java.io.Serializable; public final class S3ContentId implements Serializable { private String bucket; private String objectId; public S3ContentId(String bucket, String objectId) { this.bucket = bucket; this.objectId = objectId; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } @Override public String toString() { return "S3ContentId{" + "bucket='" + bucket + '\'' + ", objectId='" + objectId + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; S3ContentId that = (S3ContentId) o; if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false; return objectId != null ? objectId.equals(that.objectId) : that.objectId == null; } @Override public int hashCode() { int result = bucket != null ? bucket.hashCode() : 0; result = 31 * result + (objectId != null ? objectId.hashCode() : 0); return result; } }
Add test for removing item
import jsonsempai import os import shutil import sys import tempfile TEST_FILE = '''{ "three": 3, "one": { "two": { "three": 3 } } }''' class TestSempai(object): def setup(self): self.direc = tempfile.mkdtemp(prefix='jsonsempai') sys.path.append(self.direc) with open(os.path.join(self.direc, 'sempai.json'), 'w') as f: f.write(TEST_FILE) def teardown(self): sys.path.remove(self.direc) shutil.rmtree(self.direc) def test_import(self): import sempai assert sempai def test_access(self): import sempai assert sempai.three == 3 def test_access_nested(self): import sempai assert sempai.one.two.three == 3 def test_acts_like_dict(self): import sempai assert sempai.one.two == {"three": 3} def test_set(self): import sempai sempai.one.two.three = 4 assert sempai.one.two.three == 4 def test_del(self): import sempai del sempai.one.two.three assert sempai.one.two.get('three', 'not at home') == 'not at home' def test_location(self): import sempai assert sempai.__file__ == os.path.join(self.direc, 'sempai.json')
import jsonsempai import os import shutil import sys import tempfile TEST_FILE = '''{ "three": 3, "one": { "two": { "three": 3 } } }''' class TestSempai(object): def setup(self): self.direc = tempfile.mkdtemp(prefix='jsonsempai') sys.path.append(self.direc) with open(os.path.join(self.direc, 'sempai.json'), 'w') as f: f.write(TEST_FILE) def teardown(self): sys.path.remove(self.direc) shutil.rmtree(self.direc) def test_import(self): import sempai assert sempai def test_access(self): import sempai assert sempai.three == 3 def test_access_nested(self): import sempai assert sempai.one.two.three == 3 def test_acts_like_dict(self): import sempai assert sempai.one.two == {"three": 3} def test_set(self): import sempai sempai.one.two.three = 4 assert sempai.one.two.three == 4 def test_location(self): import sempai assert sempai.__file__ == os.path.join(self.direc, 'sempai.json')
Add missing canvas context methods
module.exports = function() { global.expect = global.chai.expect; global.THREE = require('three'); // Mock 'document.createElement()' to return a fake canvas. // This is a bit more convenient rather than requiring both the canvas // and jsdom node modules to be installed as well. const context = { clearRect: function() {}, save: function() {}, restore: function() {}, beginPath: function() {}, rect: function() {}, clip: function() {}, measureText: function( text ) { return { width: text.length } }, translate: function() {}, strokeRect: function() {}, scale: function() {}, fillText: function() {}, strokeText: function() {}, }; global.document = { 'createElement': function( name ) { if ( name === 'div' ) { return; } else if ( name === 'canvas' ) { return { name: 'canvas', width: null, height: null, getContext: function() { return context; }, }; } throw new Error(`This simple mock doesn't know element type ${ name }`); } }; beforeEach( function() { this.sandbox = global.sinon.sandbox.create(); global.stub = this.sandbox.stub.bind(this.sandbox); global.spy = this.sandbox.spy.bind(this.sandbox); global.mock = this.sandbox.mock.bind(this.sandbox); }); afterEach( function() { delete global.stub; delete global.spy; delete global.mock; this.sandbox.restore(); }); };
module.exports = function() { global.expect = global.chai.expect; global.THREE = require('three'); // Mock 'document.createElement()' to return a fake canvas. // This is a bit more convenient rather than requiring both the canvas // and jsdom node modules to be installed as well. const context = { clearRect: function() {}, save: function() {}, restore: function() {}, beginPath: function() {}, rect: function() {}, clip: function() {}, measureText: function( text ) { return { width: text.length } }, translate: function() {}, strokeRect: function() {}, }; global.document = { 'createElement': function( name ) { if ( name === 'div' ) { return; } else if ( name === 'canvas' ) { return { name: 'canvas', width: null, height: null, getContext: function() { return context; }, }; } throw new Error(`This simple mock doesn't know element type ${ name }`); } }; beforeEach( function() { this.sandbox = global.sinon.sandbox.create(); global.stub = this.sandbox.stub.bind(this.sandbox); global.spy = this.sandbox.spy.bind(this.sandbox); global.mock = this.sandbox.mock.bind(this.sandbox); }); afterEach( function() { delete global.stub; delete global.spy; delete global.mock; this.sandbox.restore(); }); };
Fix update checks never returning anything.
var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var _ = require('lodash'); module.exports = { createIfNotExists: function(inPath) { return fs.statAsync(inPath).catch(function(e) { return fs.openAsync(inPath, 'w').then(fs.closeAsync); }); }, createDirIfNotExists: function (path) { try { fs.mkdirSync(path); } catch(e) { if(e.code != 'EEXIST') { throw e; } } }, capizalizeFirstLetter: function(word) { return word.charAt(0).toUpperCase() + word.slice(1); }, getOnlineDiff: function(oldEntries, newEntries) { var updates = []; newEntries.forEach(function(entry) { var oldEntry = _.find(oldEntries, { id: entry.id }); if(oldEntry) { if(entry.status && !oldEntry.status) { updates.push(entry); } } }); return updates; } };
var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var _ = require('lodash'); module.exports = { createIfNotExists: function(inPath) { return fs.statAsync(inPath).catch(function(e) { return fs.openAsync(inPath, 'w').then(fs.closeAsync); }); }, createDirIfNotExists: function (path) { try { fs.mkdirSync(path); } catch(e) { if(e.code != 'EEXIST') { throw e; } } }, capizalizeFirstLetter: function(word) { return word.charAt(0).toUpperCase() + word.slice(1); }, getOnlineDiff: function(oldEntries, newEntries) { var updates = []; newEntries.forEach(function(entry) { var oldEntry = _.find(oldEntries, { id: entry.id }); if(oldEntry) { if(entry.online && !oldEntry.online) { updates.push(entry); } } }); return updates; } };
Add dependency on Django 1.3.
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) # Dynamically calculate the version based on photologue.VERSION version_tuple = __import__('photologue').VERSION if len(version_tuple) == 3: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name="django-photologue", version=version, description="Powerful image management for the Django web framework.", author="Justin Driscoll, Marcos Daniel Petry, Richard Barran", author_email="[email protected], [email protected]", url="https://github.com/jdriscoll/django-photologue", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum. ], )
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) # Dynamically calculate the version based on photologue.VERSION version_tuple = __import__('photologue').VERSION if len(version_tuple) == 3: version = "%d.%d_%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name="django-photologue", version=version, description="Powerful image management for the Django web framework.", author="Justin Driscoll, Marcos Daniel Petry, Richard Barran", author_email="[email protected], [email protected]", url="https://github.com/jdriscoll/django-photologue", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
Change the back-off algo for failures
import time import multiprocessing try: from setproctitle import setproctitle except ImportError: def setproctitle(title): pass class StatsCollector(multiprocessing.Process): def __init__(self, queue): super(StatsCollector, self).__init__() self.queue = queue def close(self): pass def run(self): setproctitle("bucky: %s" % self.__class__.__name__) interval = self.interval while True: start_timestamp = time.time() interval = self.interval if self.collect() else interval+interval stop_timestamp = time.time() interval = min(interval, 300) interval = interval - (stop_timestamp - start_timestamp) if interval > 0.1: time.sleep(interval) def collect(self): raise NotImplementedError() def add_stat(self, name, value, timestamp, **metadata): if metadata: if self.metadata: metadata.update(self.metadata) else: metadata = self.metadata if metadata: self.queue.put((None, name, value, timestamp, metadata)) else: self.queue.put((None, name, value, timestamp)) def merge_dicts(self, *dicts): ret = {} for d in dicts: if d: ret.update(d) return ret
import time import multiprocessing try: from setproctitle import setproctitle except ImportError: def setproctitle(title): pass class StatsCollector(multiprocessing.Process): def __init__(self, queue): super(StatsCollector, self).__init__() self.queue = queue def close(self): pass def run(self): setproctitle("bucky: %s" % self.__class__.__name__) err = 0 while True: start_timestamp = time.time() if not self.collect(): err = min(err + 1, 2) else: err = 0 stop_timestamp = time.time() sleep_time = (err + 1) * self.interval - (stop_timestamp - start_timestamp) if sleep_time > 0.1: time.sleep(sleep_time) def collect(self): raise NotImplementedError() def add_stat(self, name, value, timestamp, **metadata): if metadata: if self.metadata: metadata.update(self.metadata) else: metadata = self.metadata if metadata: self.queue.put((None, name, value, timestamp, metadata)) else: self.queue.put((None, name, value, timestamp)) def merge_dicts(self, *dicts): ret = {} for d in dicts: if d: ret.update(d) return ret
IMPROVE (bugsnag): Stop bugsnag to send AJAX errors for user errors
(function () { 'use strict'; angular .module('gisto') .factory('bugsnagHttpInterceptor', bugsnagHttpInterceptor); bugsnagHttpInterceptor.$inject = ['$q', 'bugsnag']; /* @ngInject */ function bugsnagHttpInterceptor($q, bugsnag) { return { requestError: handleError, responseError: handleError }; function handleError(rejection) { if (!shouldNotSendError(rejection)) { bugsnag.notify("AjaxError", rejection.status + ' on ' + rejection.config.url, { request: { status: rejection.status, statusText: rejection.statusText, url: rejection.config.url, method: rejection.config.method }, headers: { headers: rejection.headers() }, data: { data: rejection.data } }, "error"); } return $q.reject(rejection); } function shouldNotSendError(rejection) { return isGitHubStarNotFound(rejection) && isConnectionTimeout(rejection) && isAuthorizationError(rejection) && isRateLimitReached(rejection); } function isGitHubStarNotFound(rejection) { return rejection.status === 404 && rejection.config.url.indexOf('/star') > -1 } function isConnectionTimeout(rejection) { return rejection.status === 0; } function isAuthorizationError(rejection) { return rejection.status === 401; } function isRateLimitReached(rejection) { return rejection.headers()['x-ratelimit-remaining'] === 0; } } })();
(function () { 'use strict'; angular .module('gisto') .factory('bugsnagHttpInterceptor', bugsnagHttpInterceptor); bugsnagHttpInterceptor.$inject = ['$q', 'bugsnag']; /* @ngInject */ function bugsnagHttpInterceptor($q, bugsnag) { return { requestError: handleError, responseError: handleError }; function handleError(rejection) { if (!isGitHubStarNotFound(rejection)) { bugsnag.notify("AjaxError", rejection.status + ' on ' + rejection.config.url, { request: { status: rejection.status, statusText: rejection.statusText, url: rejection.config.url, method: rejection.config.method }, headers: { headers: rejection.headers() }, data: { data: rejection.data } }, "error"); } return $q.reject(rejection); } function isGitHubStarNotFound(rejection) { return rejection.status === 404 && rejection.config.url.indexOf('/star') > -1 } } })();
Add support for intent slot's value as a object
'use strict'; const _ = require('underscore'); function buildSlots(slots) { const res = {}; _.each(slots, (value, key) => { if( _.isString(value)){ res[key] = { name: key, value: value } }else{ res[key] = { name: key, ...value } } }); return res; } function buildSession(e) { return e ? e.sessionAttributes : {}; } function init(options) { let isNew = true; // public API const api = { init, build }; function build(intentName, slots, prevEvent) { if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request'); const res = { // override more stuff later as we need session: { sessionId: options.sessionId, application: { applicationId: options.appId }, attributes: buildSession(prevEvent), user: { userId: options.userId, accessToken: options.accessToken }, new: isNew }, request: { type: 'IntentRequest', requestId: options.requestId, locale: options.locale, timestamp: (new Date()).toISOString(), intent: { name: intentName, slots: buildSlots(slots) } }, version: '1.0' }; isNew = false; return res; } return api; } module.exports = {init};
'use strict'; const _ = require('underscore'); function buildSlots(slots) { const res = {}; _.each(slots, (value, key) => { res[key] = { name: key, value: value }; if(! _.isString(value)){ res[key] = {...res[key],...value} } }); return res; } function buildSession(e) { return e ? e.sessionAttributes : {}; } function init(options) { let isNew = true; // public API const api = { init, build }; function build(intentName, slots, prevEvent) { if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request'); const res = { // override more stuff later as we need session: { sessionId: options.sessionId, application: { applicationId: options.appId }, attributes: buildSession(prevEvent), user: { userId: options.userId, accessToken: options.accessToken }, new: isNew }, request: { type: 'IntentRequest', requestId: options.requestId, locale: options.locale, timestamp: (new Date()).toISOString(), intent: { name: intentName, slots: buildSlots(slots) } }, version: '1.0' }; isNew = false; return res; } return api; } module.exports = {init};
Change CloudWatch metrics timer to 1 minute.
var async = require('async'); var context; var publishTimer; function publishToDashboard() { async.waterfall([ function(callback) { context.consuler.getKeyValue(context.keys.request, function(result) { callback(null, result); }); }, function(requests, callback) { context.consuler.getKeyValue(context.keys.allocation, function(result) { callback(null, requests, result); }); }, function(requests, allocations, callback) { var timestamp = new Date(); context.AwsHandler.publishMultiple([ { MetricName: context.strings.requestCount, Dimensions: [], Timestamp: timestamp, Unit: "Count", Value: requests }, { MetricName: context.strings.allocationCount, Dimensions: [], Timestamp: timestamp, Unit: "Count", Value: allocations } ]); } ], function (err, results) {}); } module.exports = function (c) { context = c; publishTimer = setInterval(publishToDashboard, 60000); }
var async = require('async'); var context; var publishTimer; function publishToDashboard() { async.waterfall([ function(callback) { context.consuler.getKeyValue(context.keys.request, function(result) { callback(null, result); }); }, function(requests, callback) { context.consuler.getKeyValue(context.keys.allocation, function(result) { callback(null, requests, result); }); }, function(requests, allocations, callback) { var timestamp = new Date(); context.AwsHandler.publishMultiple([ { MetricName: context.strings.requestCount, Dimensions: [], Timestamp: timestamp, Unit: "Count", Value: requests }, { MetricName: context.strings.allocationCount, Dimensions: [], Timestamp: timestamp, Unit: "Count", Value: allocations } ]); } ], function (err, results) {}); } module.exports = function (c) { context = c; publishTimer = setInterval(publishToDashboard, 500); }
Send vote count to interface
package ch.ethz.geco.bass.audio.gson; import ch.ethz.geco.bass.audio.util.AudioTrackMetaData; import com.google.gson.*; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import java.lang.reflect.Type; import java.util.Map; /** * Serializes an AudioTrack to json. */ public class AudioTrackSerializer implements JsonSerializer<AudioTrack> { @Override public JsonElement serialize(AudioTrack src, Type typeOfSrc, JsonSerializationContext context) { AudioTrackInfo info = src.getInfo(); // Get meta data AudioTrackMetaData metaData = (AudioTrackMetaData) src.getUserData(); // Parse votes to json array JsonArray votes = new JsonArray(); for (Map.Entry<String, Byte> entry : metaData.getVotes().entrySet()) { JsonObject vote = new JsonObject(); vote.addProperty(entry.getKey(), entry.getValue()); votes.add(vote); } JsonObject jsonTrack = new JsonObject(); jsonTrack.addProperty("id", metaData.getTrackID()); jsonTrack.addProperty("uri", info.uri); jsonTrack.addProperty("userID", metaData.getUserID()); jsonTrack.addProperty("title", info.title); jsonTrack.add("voters", votes); jsonTrack.addProperty("votes", metaData.getVoteCount()); jsonTrack.addProperty("length", info.length); jsonTrack.addProperty("position", src.getPosition()); return jsonTrack; } }
package ch.ethz.geco.bass.audio.gson; import ch.ethz.geco.bass.audio.util.AudioTrackMetaData; import com.google.gson.*; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import java.lang.reflect.Type; import java.util.Map; /** * Serializes an AudioTrack to json. */ public class AudioTrackSerializer implements JsonSerializer<AudioTrack> { @Override public JsonElement serialize(AudioTrack src, Type typeOfSrc, JsonSerializationContext context) { AudioTrackInfo info = src.getInfo(); // Get meta data AudioTrackMetaData metaData = (AudioTrackMetaData) src.getUserData(); // Parse votes to json array JsonArray votes = new JsonArray(); for (Map.Entry<String, Byte> entry : metaData.getVotes().entrySet()) { JsonObject vote = new JsonObject(); vote.addProperty(entry.getKey(), entry.getValue()); votes.add(vote); } JsonObject jsonTrack = new JsonObject(); jsonTrack.addProperty("id", metaData.getTrackID()); jsonTrack.addProperty("uri", info.uri); jsonTrack.addProperty("userID", metaData.getUserID()); jsonTrack.addProperty("title", info.title); jsonTrack.add("votes", votes); jsonTrack.addProperty("length", info.length); jsonTrack.addProperty("position", src.getPosition()); return jsonTrack; } }
Add case param in accept/reject urls.
<?php function modal ($id, $title, $body, $data) { $html = '<div id="'.$id.'" class="modal fade" style="display:none" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" class="close" data-dismiss="modal" type="button">&times;</button> <h4 class="modal-title">' . $title .'</h4> </div> <div class="modal-body">' . $body .'</div> <div class="modal-footer"> <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a> <a href="' . url('/') . ($_GET['case'] ? '?case=' . $_GET['case'] . '&' : '?') . 'action=' . $data['action'] . '" class="btn btn-primary" id="'.$id.'-confirm">Confirm</a> </div> </div> </div> </div>'; echo $html; };
<?php function modal ($id, $title, $body, $data) { $html = '<div id="'.$id.'" class="modal fade" style="display:none" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" class="close" data-dismiss="modal" type="button">&times;</button> <h4 class="modal-title">' . $title .'</h4> </div> <div class="modal-body">' . $body .'</div> <div class="modal-footer"> <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a> <a href="' . url('/') . '?action=' . $data['action'] . '" class="btn btn-primary" id="'.$id.'-confirm">Confirm</a> </div> </div> </div> </div>'; echo $html; };
Update from small pipeline changes
/*global define*/ define([], function() { 'use strict'; /** * Utility function for retrieving the number of components in a given type. * As per the spec: * 'SCALAR' : 1 * 'VEC2' : 2 * 'VEC3' : 3 * 'VEC4' : 4 * 'MAT2' : 4 * 'MAT3' : 9 * 'MAT4' : 16 * * @param {String} type glTF type * @returns {Number} The number of components in that type. */ function numberOfComponentsForType(type) { switch (type) { case 'SCALAR': return 1; case 'VEC2': return 2; case 'VEC3': return 3; case 'VEC4': case 'MAT2': return 4; case 'MAT3': return 9; case 'MAT4': return 16; } } return numberOfComponentsForType; });
/*global define*/ define([], function() { 'use strict'; /** * Utility function for retrieving the number of components in a given type. * As per the spec: * 'SCALAR' : 1 * 'VEC2' : 2 * 'VEC3' : 3 * 'VEC4' : 4 * 'MAT2' : 4 * 'MAT3' : 9 * 'MAT4' : 16 * * @param {String} type glTF type * @returns {Number} The number of components in that type. */ function numberOfComponentsForType(type) { switch (type) { case 'SCALAR': return 1; case 'VEC2': return 2; case 'VEC3': return 3; case 'VEC4': case 'MAT2': return 4; case 'MAT3': return 9; case 'MAT4': return 16; } } return numberOfComponentsForType; });
Change stride semantic in MaxPool
"""Pooling layer.""" from theano.tensor.signal import downsample from athenet.layers import Layer class MaxPool(Layer): """Max-pooling layer.""" def __init__(self, poolsize, stride=None): """Create max-pooling layer. :poolsize: Pooling factor in the format (height, width). :stride: Pair representing interval at which to apply the filters. """ super(MaxPool, self).__init__() self.poolsize = poolsize if stride is None: self.stride = poolsize else: self.stride = stride @property def output_shape(self): image_h, image_w, n_channels = self.input_shape pool_h, pool_w = self.poolsize if self.stride is not None: stride_h, stride_w = self.stride else: stride_h, stride_w = pool_h, pool_w output_h = (image_h - pool_h) / stride_h + 1 output_w = (image_w - pool_w) / stride_w + 1 return (output_h, output_w, n_channels) def _get_output(self, layer_input): """Return layer's output. layer_input: Input in the format (batch size, number of channels, image height, image width). :return: Layer output. """ if self.stride == self.poolsize: stride = None else: stride = self.stride return downsample.max_pool_2d( input=layer_input, ds=self.poolsize, ignore_border=True, st=stride )
"""Pooling layer.""" from theano.tensor.signal import downsample from athenet.layers import Layer class MaxPool(Layer): """Max-pooling layer.""" def __init__(self, poolsize, stride=None): """Create max-pooling layer. :poolsize: Pooling factor in the format (height, width). :stride: Pair representing interval at which to apply the filters. """ super(MaxPool, self).__init__() self.poolsize = poolsize self.stride = stride @property def output_shape(self): image_h, image_w, n_channels = self.input_shape pool_h, pool_w = self.poolsize if self.stride: stride_h, stride_w = self.stride else: stride_h, stride_w = pool_h, pool_w output_h = (image_h - pool_h) / stride_h + 1 output_w = (image_w - pool_w) / stride_w + 1 return (output_h, output_w, n_channels) def _get_output(self, layer_input): """Return layer's output. layer_input: Input in the format (batch size, number of channels, image height, image width). :return: Layer output. """ return downsample.max_pool_2d( input=layer_input, ds=self.poolsize, ignore_border=True, st=self.stride )
Set readme content type to markdown
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.md', 'r', 'utf-8') as f: README = f.read() with codecs_open('HISTORY.md', 'r', 'utf-8') as f: HISTORY = f.read() setup( author='Beau Barker', author_email='[email protected]', classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ], description='Process JSON-RPC requests', extras_require={ 'tox': ['tox'], 'examples': [ 'aiohttp', 'aiozmq', 'flask', 'flask-socketio', 'pyzmq', 'tornado', 'websockets', 'werkzeug', ] }, include_package_data=True, install_requires=['jsonschema', 'six', 'funcsigs'], license='MIT', long_description=README + '\n\n' + HISTORY, long_description_content_type='text/markdown', name='jsonrpcserver', package_data={'jsonrpcserver': ['request-schema.json']}, packages=['jsonrpcserver'], url='https://github.com/bcb/jsonrpcserver', version='3.5.3' )
"""setup.py""" from codecs import open as codecs_open from setuptools import setup with codecs_open('README.md', 'r', 'utf-8') as f: README = f.read() with codecs_open('HISTORY.md', 'r', 'utf-8') as f: HISTORY = f.read() setup( name='jsonrpcserver', version='3.5.3', description='Process JSON-RPC requests', long_description=README + '\n\n' + HISTORY, author='Beau Barker', author_email='[email protected]', url='https://github.com/bcb/jsonrpcserver', license='MIT', packages=['jsonrpcserver'], package_data={'jsonrpcserver': ['request-schema.json']}, include_package_data=True, install_requires=['jsonschema', 'six', 'funcsigs'], extras_require={ 'tox': ['tox'], 'examples': [ 'aiohttp', 'aiozmq', 'flask', 'flask-socketio', 'pyzmq', 'tornado', 'websockets', 'werkzeug', ] }, classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ], )
Hide Exscript.protocols.AbstractMethod from the API docs.
#!/usr/bin/env python # Generates the API documentation. import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.Interpreter', '--exclude Exscript.helpers', '--exclude Exscript.FunctionAction', '--exclude Exscript.FooLib', '--exclude Exscript.AccountManager', '--exclude Exscript.stdlib', '--exclude Exscript.protocols.AbstractMethod', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.protocols.otp', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
#!/usr/bin/env python # Generates the API documentation. import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Generate the API documentation. os.system('epydoc ' + ' '.join(['--name', project, '--exclude Exscript.Interpreter', '--exclude Exscript.helpers', '--exclude Exscript.FunctionAction', '--exclude Exscript.FooLib', '--exclude Exscript.AccountManager', '--exclude Exscript.stdlib', '--exclude Exscript.protocols.telnetlib', '--exclude Exscript.protocols.otp', '--html', '--no-private', '--no-source', '--no-frames', '--inheritance=included', '-v', '-o %s' % doc_dir, base_dir]))
Fix 404 page font issue
import React from 'react'; import { Link } from 'react-router'; import classNames from 'classnames'; import Title from 'react-title-component'; import main from '../../assets/css/main.scss'; const primaryBtnClassnames = classNames(main['primary-btn'], main.btn, main.a); import styles from '../../assets/css/pages/notfound.scss'; const NotFound = () => <div id={styles['error-page']}> <Title render={parentTitle => `Page Not Found | ${parentTitle}`}/> <div className="container-fluid" id={styles['error-page-container']}> <div className="row"> <center><span id={styles['error-404']}>404</span></center> </div> <div className="row"> <div className="col-xs-12 col-md-6 col-md-push-3"> <center><span id={styles['error-message']}> Whoops! This page has either relocated or no longer exists (maybe it's just on vacation). </span></center> </div> </div> <br/> <br/> <br/> <div className="row"> <center><Link to="/" className={primaryBtnClassnames}><span className="fa fa-arrow-left"/> Back to Safety</Link></center> </div> </div> </div>; export default NotFound;
import React from 'react'; import { Link } from 'react-router'; import classNames from 'classnames'; import Title from 'react-title-component'; import main from '../../assets/css/main.scss'; const primaryBtnClassnames = classNames(main['primary-btn'], main.btn, main.a); import styles from '../../assets/css/pages/notfound.scss'; const NotFound = () => <div id={styles['error-page']}> <Title render={parentTitle => `Page Not Found | ${parentTitle}`}/> <div className="container-fluid" id={styles['error-page-container']}> <div className="row"> <center><span id={styles['error-404']}>404</span></center> </div> <div className="row"> <div className="col-xs-12 col-md-6 col-md-push-3"> <center><span id={styles['error-message']}> Whoops! This page has either relocated or no longer exists (maybe it's just on vacation). </span></center> </div> </div> <br/> <br/> <br/> <div className="row"> <center><Link to="/" className={primaryBtnClassnames}><span className="fa fa-arrow-left"> Back to Safety</span></Link></center> </div> </div> </div>; export default NotFound;
Add simple back-end validation on signup
<?php namespace App\Http\Controllers\Auth; use App\User; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Auth; class AuthController extends \App\Http\Controllers\Controller { public function login() { if (Auth::check() === true) return redirect('/'); return view('login'); } public function logout() { // TODO: Validation Auth::logout(); return redirect('/login'); } public function signup() { return view('signup'); } public function authenticate() { // TODO: Validation $credentials = [ 'email' => Request::input('email'), 'password' => Request::input('password') ]; if( ! Auth::attempt($credentials, true)) return redirect('login'); Auth::login(Auth::user()); return redirect('/'); } public function register(\Illuminate\Http\Request $request) { // TODO: Validation // TODO: get username properly $this->validate($request, [ 'email' => 'required|email|unique:users,email', 'password' => 'same:repeat-password', 'repeat-password' => 'required', ]); $credentials = [ 'username' => str_random(10), 'email' => Request::input('email'), 'password' => Request::input('password') ]; try { $user = User::create($credentials); } catch (QueryException $e) { dd($e->errorInfo[2]); } Auth::login($user); return redirect('/'); } }
<?php namespace App\Http\Controllers\Auth; use App\User; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Auth; class AuthController extends \App\Http\Controllers\Controller { public function login() { if (Auth::check() === true) return redirect('/'); return view('login'); } public function logout() { // TODO: Validation Auth::logout(); return redirect('/login'); } public function signup() { return view('signup'); } public function authenticate() { // TODO: Validation $credentials = [ 'email' => Request::input('email'), 'password' => Request::input('password') ]; if( ! Auth::attempt($credentials, true)) return redirect('login'); Auth::login(Auth::user()); return redirect('/'); } public function register() { // TODO: Validation // TODO: get username properly $credentials = [ 'username' => str_random(10), 'email' => Request::input('email'), 'password' => Request::input('password') ]; try { $user = User::create($credentials); } catch (QueryException $e) { dd($e->errorInfo[2]); } Auth::login($user); return redirect('/'); } }
Fix a pydocstyle warning in .travis.yml
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Copyright (c) 2014 CorvisaCloud, LLC # # License: MIT # """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' tempfile_suffix = 'lua' defaults = { '--ignore:,': ['channel'], '--only:,': [], '--limit=': None, '--globals:,': [], } comment_re = r'\s*--' inline_settings = 'limit' inline_overrides = ('ignore', 'only', 'globals') cmd = 'luacheck @ *' regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$' def build_args(self, settings): """Return args, transforming --ignore, --only, and --globals args into a format luacheck understands.""" args = super().build_args(settings) for arg in ('--ignore', '--only', '--globals'): try: index = args.index(arg) values = args[index + 1].split(',') args[index + 1:index + 2] = values except ValueError: pass return args
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Copyright (c) 2014 CorvisaCloud, LLC # # License: MIT # """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' tempfile_suffix = 'lua' defaults = { '--ignore:,': ['channel'], '--only:,': [], '--limit=': None, '--globals:,': [], } comment_re = r'\s*--' inline_settings = 'limit' inline_overrides = ('ignore', 'only', 'globals') cmd = 'luacheck @ *' regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$' def build_args(self, settings): """Return args, transforming --ignore, --only, and --globals args into a format luacheck understands.""" args = super().build_args(settings) for arg in ('--ignore', '--only', '--globals'): try: index = args.index(arg) values = args[index + 1].split(',') args[index + 1:index + 2] = values except ValueError: pass return args
Add handler and logger for management commands
import os from .toggles import * if not DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('RCAMP_EMAIL_HOST') EMAIL_PORT = int(os.environ.get('RCAMP_EMAIL_PORT')) else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'WARN', 'class': 'logging.FileHandler', 'filename': '/opt/logs/rcamp.log', }, 'management_commands': { 'level': "INFO", 'class': 'logging.FileHandler', 'filename': '/opt/logs/management_commands.log' } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'rcamp': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'projects': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'management_commands': { 'handlers': ['management_commands'], 'level': 'DEBUG', 'propagate': True, }, 'accounts': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, }
import os from .toggles import * if not DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = os.environ.get('RCAMP_EMAIL_HOST') EMAIL_PORT = int(os.environ.get('RCAMP_EMAIL_PORT')) else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'WARN', 'class': 'logging.FileHandler', 'filename': '/opt/logs/rcamp.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'rcamp': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'projects': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, 'accounts': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, }
Use trailing slashes for angular routing urls Currently angular js still strips the trailing slashes from the url. With angular 1.3 this cane be changed via a resourceProvider.
// -*- coding: utf-8 -*- // // (c) 2014 Bjoern Ricks <[email protected]> // // See LICENSE comming with the source of 'trex' for details. // 'use strict'; var trexApp = angular.module('trex.app', ['ngRoute', 'ngCookies', 'ngTagsInput', 'ngResource', 'angular-loading-bar', 'trex.controllers', 'trex.filters', 'trex.services', 'trex.directives']); trexApp.config(['$routeProvider', '$resourceProvider', function($routeProvider, $resourceProvider) { // will be available with Angular JS 1.3 // https://github.com/angular/angular.js/commit/3878be52f6d95fca4c386d4a5523f3c8fcb04270 // $resourceProvider.defaults.stripTrailingSlashes = false; $routeProvider. when("/projects/", { templateUrl: 'static/html/projects.html', controller: 'ProjectListCtrl' }). when("/projects/:id/", { templateUrl: 'static/html/project-detail.html', controller: 'ProjectDetailCtrl' }). when("/entries/:id/", { templateUrl: 'static/html/entry-detail.html', controller: 'EntryDetailCtrl' }). otherwise({ redirectTo: '/' }); }] ); trexApp.run(['$http', '$cookies', function($http, $cookies) { $http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken; }] );
// -*- coding: utf-8 -*- // // (c) 2014 Bjoern Ricks <[email protected]> // // See LICENSE comming with the source of 'trex' for details. // 'use strict'; var trexApp = angular.module('trex.app', ['ngRoute', 'ngCookies', 'ngTagsInput', 'angular-loading-bar', 'trex.controllers', 'trex.filters', 'trex.services', 'trex.directives']); trexApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when("/projects/", { templateUrl: 'static/html/projects.html', controller: 'ProjectListCtrl' }). when("/projects/:id", { templateUrl: 'static/html/project-detail.html', controller: 'ProjectDetailCtrl' }). when("/entries/:id", { templateUrl: 'static/html/entry-detail.html', controller: 'EntryDetailCtrl' }). otherwise({ redirectTo: '/' }); }] ); trexApp.run(['$http', '$cookies', function($http, $cookies) { $http.defaults.headers.common['X-CSRFToken'] = $cookies.csrftoken; }] );
Upgrade to working MozillaPulse version
from setuptools import setup, find_packages deps = [ 'ijson==2.2', 'mozci==0.15.1', 'MozillaPulse==1.2.2', 'requests==2.7.0', # Maximum version taskcluster will work with 'taskcluster==0.0.27', 'treeherder-client==1.7.0', ] setup(name='pulse-actions', version='0.2.0', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], author='Alice Scarpa', author_email='[email protected]', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps, url='https://github.com/adusca/pulse_actions', entry_points={ 'console_scripts': [ 'run-pulse-actions = pulse_actions.worker:main' ], })
from setuptools import setup, find_packages deps = [ 'ijson==2.2', 'mozci==0.15.1', 'MozillaPulse==1.2.1', 'requests==2.7.0', # Maximum version taskcluster will work with 'taskcluster==0.0.27', 'treeherder-client==1.7.0', ] setup(name='pulse-actions', version='0.2.0', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], author='Alice Scarpa', author_email='[email protected]', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps, url='https://github.com/adusca/pulse_actions', entry_points={ 'console_scripts': [ 'run-pulse-actions = pulse_actions.worker:main' ], })
Improve code structure in preparation for implementation of localization for projects page.
'use strict'; angular.module('arachne.controllers') /** * TODO adjust title according to language * for now, set it to german language * * @author: Daniel M. de Oliveira * @author: Sebastian Cuy */ .controller('ProjectsController', ['$scope', '$http', function ($scope, $http ) { var restructureByLang = function(el,lang){ el.title=el.title[lang]; el.selectedLang=lang; } var restructureRecursively = function(el){ restructureByLang(el,'de'); if (! el.children) return; for (var i=0;i<el.children.length;i++) { restructureRecursively(el.children[i]); } } $scope.columns = []; var sliceColumns = function(){ $scope.columns[0] = $scope.projects.slice(0,3); $scope.columns[1] = $scope.projects.slice(3,5); $scope.columns[2] = $scope.projects.slice(5); } $http.get('con10t/projects.json').success(function(data){ $scope.projects = data[0].children; for (var i=0;i<$scope.projects.length;i++) restructureRecursively($scope.projects[i]); sliceColumns(); }); } ]);
'use strict'; angular.module('arachne.controllers') /** * @author: Daniel M. de Oliveira * @author: Sebastian Cuy */ .controller('ProjectsController', ['$scope', '$http', function ($scope, $http ) { $scope.columns = []; $http.get('con10t/projects.json').success(function(data){ $scope.projects = data[0].children; // TODO adjust title according to language // for now, set it to german language for (var i=0;i<$scope.projects.length;i++){ // 1st order elements $scope.projects[i].title=$scope.projects[i].title['de']; if (! $scope.projects[i].children) continue; for (var j=0;j<$scope.projects[i].children.length;j++){ // 2nd order elements $scope.projects[i].children[j].title=$scope.projects[i].children[j].title['de']; if (! $scope.projects[i].children[j].children) continue; for (var k = 0; k < $scope.projects[i].children[j].children.length; k++) { // 3nd order elements $scope.projects[i].children[j].children[k].title = $scope.projects[i].children[j].children[k].title['de']; } } } $scope.columns[0] = $scope.projects.slice(0,3); $scope.columns[1] = $scope.projects.slice(3,5); $scope.columns[2] = $scope.projects.slice(5); }); } ]);
Change to app from dist
var http = require("http"); var fs = require("fs"); var path = require("path"); var mime = require("mime"); function send404(response) { response.writeHead(404, {"Content-type" : "text/plain"}); response.write("Error 404: resource not found"); response.end(); } function sendPage(response, filePath, fileContents) { response.writeHead(200, {"Content-type" : mime.lookup(path.basename(filePath))}); response.end(fileContents); } function serverWorking(response, absPath) { fs.exists(absPath, function(exists) { if (exists) { fs.readFile(absPath, function(err, data) { if (err) { send404(response) } else { sendPage(response, absPath, data); } }); } else { send404(response); } }); } var server = http.createServer(function(request, response) { var filePath = false; if (request.url == "/") { filePath = "app/index.html"; } else { filePath = "app" + request.url; } var absPath = "./" + filePath; serverWorking(response, absPath); }); var port_number = server.listen(process.env.PORT || 3000);
var http = require("http"); var fs = require("fs"); var path = require("path"); var mime = require("mime"); function send404(response) { response.writeHead(404, {"Content-type" : "text/plain"}); response.write("Error 404: resource not found"); response.end(); } function sendPage(response, filePath, fileContents) { response.writeHead(200, {"Content-type" : mime.lookup(path.basename(filePath))}); response.end(fileContents); } function serverWorking(response, absPath) { fs.exists(absPath, function(exists) { if (exists) { fs.readFile(absPath, function(err, data) { if (err) { send404(response) } else { sendPage(response, absPath, data); } }); } else { send404(response); } }); } var server = http.createServer(function(request, response) { var filePath = false; if (request.url == "/") { filePath = "dist/index.html"; } else { filePath = "dist" + request.url; } var absPath = "./" + filePath; serverWorking(response, absPath); }); var port_number = server.listen(process.env.PORT || 3000);
Refactor usage cssProperties in $.fn.anim
// Zepto.js // (c) 2010, 2011 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. (function($, undefined){ var supportedTransforms = [ 'scale scaleX scaleY', 'translate', 'translateX', 'translateY', 'translate3d', 'skew', 'skewX', 'skewY', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'rotate3d', 'matrix' ]; $.fn.anim = function(properties, duration, ease, callback){ var transforms = [], cssProperties = {}, key, that = this, wrappedCallback; for (key in properties) if (supportedTransforms.indexOf(key)>0) transforms.push(key + '(' + properties[key] + ')'); else cssProperties[key] = properties[key]; wrappedCallback = function(){ that.css({'-webkit-transition':'none'}); callback && callback(); } if (duration > 0) this.one('webkitTransitionEnd', wrappedCallback); else setTimeout(wrappedCallback, 0); if (transforms.length > 0) { cssProperties['-webkit-transform'] = transforms.join(' ') } cssProperties['-webkit-transition'] = 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || ''); setTimeout(function () { that.css(cssProperties); }, 0); return this; } })(Zepto);
// Zepto.js // (c) 2010, 2011 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. (function($, undefined){ var supportedTransforms = [ 'scale scaleX scaleY', 'translate', 'translateX', 'translateY', 'translate3d', 'skew', 'skewX', 'skewY', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'rotate3d', 'matrix' ]; $.fn.anim = function(properties, duration, ease, callback){ var transforms = [], cssProperties = {}, key, that = this, wrappedCallback; for (key in properties) if (supportedTransforms.indexOf(key)>0) transforms.push(key + '(' + properties[key] + ')'); else cssProperties[key] = properties[key]; wrappedCallback = function(){ that.css({'-webkit-transition':'none'}); callback && callback(); } if (duration > 0) this.one('webkitTransitionEnd', wrappedCallback); else setTimeout(wrappedCallback, 0); setTimeout(function () { that.css( $.extend({ '-webkit-transition': 'all ' + (duration !== undefined ? duration : 0.5) + 's ' + (ease || ''), '-webkit-transform': transforms.join(' ') }, cssProperties) ); }, 0); return this; } })(Zepto);
Use markitup widget in talk form
from django import forms from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, HTML from markitup.widgets import MarkItUpWidget from wafer.talks.models import Talk class TalkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TalkForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) submit_button = Submit('submit', _('Submit')) instance = kwargs['instance'] if instance: self.helper.layout.append( FormActions( submit_button, HTML('<a href="%s" class="btn btn-danger">%s</a>' % (reverse('wafer_talk_delete', args=(instance.pk,)), _('Delete'))))) else: self.helper.add_input(submit_button) class Meta: model = Talk fields = ('title', 'abstract', 'authors', 'notes') widgets = { 'abstract': MarkItUpWidget(), 'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}), } # TODO: authors widget is ugly
from django import forms from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, HTML from wafer.talks.models import Talk class TalkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TalkForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) submit_button = Submit('submit', _('Submit')) instance = kwargs['instance'] if instance: self.helper.layout.append( FormActions( submit_button, HTML('<a href="%s" class="btn btn-danger">%s</a>' % (reverse('wafer_talk_delete', args=(instance.pk,)), _('Delete'))))) else: self.helper.add_input(submit_button) class Meta: model = Talk fields = ('title', 'abstract', 'authors', 'notes') widgets = { 'abstract': forms.Textarea(attrs={'class': 'input-xxlarge', 'rows': 20}), 'notes': forms.Textarea(attrs={'class': 'input-xxlarge'}), } # TODO: authors widget is ugly
Update the version to 0.1.0
#!/usr/bin/env python # http://stackoverflow.com/questions/9810603/adding-install-requires-to-setup-py-when-making-a-python-package try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='molml', version='0.1.0', description='An interface between molecules and machine learning', author='Chris Collins', author_email='[email protected]', url='https://github.com/crcollins/molml/', license='MIT', packages=['molml'], test_suite='nose.collector', tests_require=['nose'], install_requires=[ 'pathos', ], classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Bio-Informatics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Scientific/Engineering :: Physics", ] )
#!/usr/bin/env python # http://stackoverflow.com/questions/9810603/adding-install-requires-to-setup-py-when-making-a-python-package try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='molml', version='0.0.1', description='An interface between molecules and machine learning', author='Chris Collins', author_email='[email protected]', url='https://github.com/crcollins/molml/', license='MIT', packages=['molml'], test_suite='nose.collector', tests_require=['nose'], install_requires=[ 'pathos', ], classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Bio-Informatics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Scientific/Engineering :: Physics", ] )
Use const instead of let on never reassigned var Signed-off-by: Julen Landa Alustiza <[email protected]>
const templateUrl = require('~components/layout/side-nav.partial.html'); function atSideNavLink (scope, element, attrs, ctrl) { scope.layoutVm = ctrl; document.on('click', (e) => { if ($(e.target).parents('.at-Layout-side').length === 0) { scope.$emit('clickOutsideSideNav'); } }); } function AtSideNavController ($scope, $window) { const vm = this || {}; const breakpoint = 700; vm.isExpanded = false; vm.toggleExpansion = () => { vm.isExpanded = !vm.isExpanded; }; $scope.$watch('layoutVm.currentState', () => { if ($window.innerWidth <= breakpoint) { vm.isExpanded = false; } }); $scope.$on('clickOutsideSideNav', () => { if ($window.innerWidth <= breakpoint) { vm.isExpanded = false; } }); } AtSideNavController.$inject = ['$scope', '$window']; function atSideNav () { return { restrict: 'E', replace: true, require: '^^atLayout', controller: AtSideNavController, controllerAs: 'vm', link: atSideNavLink, transclude: true, templateUrl, scope: { } }; } export default atSideNav;
const templateUrl = require('~components/layout/side-nav.partial.html'); function atSideNavLink (scope, element, attrs, ctrl) { scope.layoutVm = ctrl; document.on('click', (e) => { if ($(e.target).parents('.at-Layout-side').length === 0) { scope.$emit('clickOutsideSideNav'); } }); } function AtSideNavController ($scope, $window) { let vm = this || {}; const breakpoint = 700; vm.isExpanded = false; vm.toggleExpansion = () => { vm.isExpanded = !vm.isExpanded; }; $scope.$watch('layoutVm.currentState', () => { if ($window.innerWidth <= breakpoint) { vm.isExpanded = false; } }); $scope.$on('clickOutsideSideNav', () => { if ($window.innerWidth <= breakpoint) { vm.isExpanded = false; } }); } AtSideNavController.$inject = ['$scope', '$window']; function atSideNav () { return { restrict: 'E', replace: true, require: '^^atLayout', controller: AtSideNavController, controllerAs: 'vm', link: atSideNavLink, transclude: true, templateUrl, scope: { } }; } export default atSideNav;
Set methods that don't use any fields as static
package com.alexstyl.specialdates.contact; import android.content.ContentResolver; import android.database.Cursor; import android.provider.ContactsContract; import com.alexstyl.specialdates.DisplayName; class DeviceContactFactory { private final ContentResolver resolver; DeviceContactFactory(ContentResolver contentResolver) { resolver = contentResolver; } DeviceContact createContactWithId(long contactID) throws ContactNotFoundException { String selection = ContactsContract.Data.CONTACT_ID + " = " + contactID + " AND " + ContactsContract.Data.MIMETYPE + " = ?"; Cursor cursor = resolver.query(ContactsQuery.CONTENT_URI, ContactsQuery.PROJECTION, selection, new String[]{ ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsQuery.SORT_ORDER + " LIMIT 1"); if (isInvalid(cursor)) { throw new RuntimeException("Cursor was invalid"); } try { if (cursor.moveToFirst()) { DisplayName displayName = getDisplayNameFrom(cursor); String lookupKey = getLookupKeyFrom(cursor); return new DeviceContact(contactID, displayName, lookupKey); } } finally { cursor.close(); } throw new ContactNotFoundException(contactID); } private static boolean isInvalid(Cursor cursor) { return cursor == null || cursor.isClosed(); } private static DisplayName getDisplayNameFrom(Cursor cursor) { return DisplayName.from(cursor.getString(ContactsQuery.DISPLAY_NAME)); } private static String getLookupKeyFrom(Cursor cursor) { return cursor.getString(ContactsQuery.LOOKUP_KEY); } }
package com.alexstyl.specialdates.contact; import android.content.ContentResolver; import android.database.Cursor; import android.provider.ContactsContract; import com.alexstyl.specialdates.DisplayName; class DeviceContactFactory { private final ContentResolver resolver; DeviceContactFactory(ContentResolver contentResolver) { resolver = contentResolver; } DeviceContact createContactWithId(long contactID) throws ContactNotFoundException { String selection = ContactsContract.Data.CONTACT_ID + " = " + contactID + " AND " + ContactsContract.Data.MIMETYPE + " = ?"; Cursor cursor = resolver.query(ContactsQuery.CONTENT_URI, ContactsQuery.PROJECTION, selection, new String[]{ ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsQuery.SORT_ORDER + " LIMIT 1"); if (isInvalid(cursor)) { throw new RuntimeException("Cursor was invalid"); } try { if (cursor.moveToFirst()) { DisplayName displayName = getDisplayNameFrom(cursor); String lookupKey = getLookupKeyFrom(cursor); return new DeviceContact(contactID, displayName, lookupKey); } } finally { cursor.close(); } throw new ContactNotFoundException(contactID); } private boolean isInvalid(Cursor cursor) { return cursor == null || cursor.isClosed(); } private String getLookupKeyFrom(Cursor cursor) { return cursor.getString(ContactsQuery.LOOKUP_KEY); } private DisplayName getDisplayNameFrom(Cursor cursor) { return DisplayName.from(cursor.getString(ContactsQuery.DISPLAY_NAME)); } }
Support replacing all instances of the string in a html file
function HtmlReplaceWebpackPlugin(options) { options = Array.isArray(options) ? options : [options] options.forEach(function(option) { if(typeof option.pattern == 'undefined' || typeof option.replacement == 'undefined') { throw new Error('Both `pattern` and `replacement` options must be defined!') } }) this.replace = function(htmlData) { options.forEach(function(option) { if(typeof option.replacement === 'function') { var matches = null while((matches = option.pattern.exec(htmlData)) != null) { var replacement = option.replacement.apply(null, matches) // matches[0]: matching content string htmlData = htmlData.replace(matches[0], replacement) } } else { htmlData = htmlData.split(option.pattern).join(option.replacement) } }) return htmlData } } HtmlReplaceWebpackPlugin.prototype.apply = function(compiler) { var self = this compiler.plugin('compilation', function(compilation) { // console.log('The compiler is starting a new compilation...') compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) { htmlPluginData.html = self.replace(htmlPluginData.html) callback(null, htmlPluginData) }) }) } module.exports = HtmlReplaceWebpackPlugin
function HtmlReplaceWebpackPlugin(options) { options = Array.isArray(options) ? options : [options] options.forEach(function(option) { if(typeof option.pattern == 'undefined' || typeof option.replacement == 'undefined') { throw new Error('Both `pattern` and `replacement` options must be defined!') } }) this.replace = function(htmlData) { options.forEach(function(option) { if(typeof option.replacement === 'function') { var matches = null while((matches = option.pattern.exec(htmlData)) != null) { var replacement = option.replacement.apply(null, matches) // matches[0]: matching content string htmlData = htmlData.replace(matches[0], replacement) } } else { htmlData = htmlData.replace(option.pattern, option.replacement) } }) return htmlData } } HtmlReplaceWebpackPlugin.prototype.apply = function(compiler) { var self = this compiler.plugin('compilation', function(compilation) { // console.log('The compiler is starting a new compilation...') compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) { htmlPluginData.html = self.replace(htmlPluginData.html) callback(null, htmlPluginData) }) }) } module.exports = HtmlReplaceWebpackPlugin
Update to make Travis-CI happier.
package myessentials.chat.api; import myessentials.localization.api.LocalManager; import net.minecraft.command.ICommandSender; import net.minecraft.util.IChatComponent; import net.minecraft.entity.player.EntityPlayerMP; import java.util.List; public class ChatManager { /** * Global method for sending localized messages */ public static void send(ICommandSender sender, String localizationKey, Object... args) { send(sender, LocalManager.get(localizationKey, args)); } /** * Global method for sending messages * If the message sent is a ChatComponentList then only its siblings are sent, omitting the root component */ @SuppressWarnings("unchecked") public static void send(ICommandSender sender, IChatComponent message) { if (sender == null) { return; } if (message == null) { return; } if (message instanceof ChatComponentList) { for (IChatComponent sibling : (List<IChatComponent>)message.getSiblings()) { if (sibling == null) { continue; } sender.addChatMessage(sibling); } } else { sender.addChatMessage(message); } } public static void addChatMessageFixed(ICommandSender sender, IChatComponent message) { if (!(sender instanceof EntityPlayerMP)||((EntityPlayerMP)sender).playerNetServerHandler != null) sender.addChatMessage(message); } //TODO Find a way to re-send the message. } }
package myessentials.chat.api; import myessentials.localization.api.LocalManager; import net.minecraft.command.ICommandSender; import net.minecraft.util.IChatComponent; import net.minecraft.entity.player.EntityPlayerMP; import java.util.List; public class ChatManager { /** * Global method for sending localized messages */ public static void send(ICommandSender sender, String localizationKey, Object... args) { send(sender, LocalManager.get(localizationKey, args)); } /** * Global method for sending messages * If the message sent is a ChatComponentList then only its siblings are sent, omitting the root component */ @SuppressWarnings("unchecked") public static void send(ICommandSender sender, IChatComponent message) { if (sender == null) { return; } if (message == null) { return; } if (message instanceof ChatComponentList) { for (IChatComponent sibling : (List<IChatComponent>)message.getSiblings()) { if (sibling == null) { continue; } sender.addChatMessage(sibling); } } else { sender.addChatMessage(message); } } public static void addChatMessageFixed(ICommandSender sender, IChatComponent message) { if (!(sender instanceof EntityPlayerMP)||((EntityPlayerMP)sender).playerNetServerHandler != null) sender.addChatMessage(message); } else { //TODO Find a way to re-send the message. } } }
Fix room not recalculating sources
SetupPrototypes(); SetupRooms(); SpawnCreeps(); HandleCreeps(); EndTick(); function SetupPrototypes() { Room.prototype.getLOIs = function() { var lois = []; this.memory.sources.forEach(function(sourceId) { lois.push(sourceId); }); if(this.controller) { lois.push(this.controller.id); } return lois; }; } function SetupRooms() { Object.keys(Game.rooms).forEach(function (roomName) { var room = Game.rooms[roomName]; if (!room.memory.calcComplete || Memory.recalcRooms) { // Do one time room calculations here if(!room.memory.sources || Memory.recalcRooms) { room.memory.sources = room.find(FIND_SOURCES).map(function (sourceObject) { return sourceObject.id; }); } room.memory.calcComplete = true; } }); } function SpawnCreeps() { if(Object.keys(Game.creeps).length < 4) { // Spawn a new creep } } function HandleCreeps() { Object.keys(Game.creeps).forEach(function (creepName) { var creep = Game.creeps[creepName]; if(creep.carry.energy < creep.carryCapacity) { // Move to source or harvest } else { // Move to spawn or transfer } }); } function EndTick() { Memory.recalcRooms = false; console.log(Game.getUsedCpu()); }
SetupPrototypes(); SetupRooms(); SpawnCreeps(); HandleCreeps(); EndTick(); function SetupPrototypes() { Room.prototype.getLOIs = function() { var lois = []; this.memory.sources.forEach(function(sourceId) { lois.push(sourceId); }); if(this.controller) { lois.push(this.controller.id); } return lois; }; } function SetupRooms() { Object.keys(Game.rooms).forEach(function (roomName) { var room = Game.rooms[roomName]; if (!room.memory.calcComplete || Memory.recalcRooms) { // Do one time room calculations here if(!room.memory.sources) { room.memory.sources = room.find(FIND_SOURCES).map(function (sourceObject) { return sourceObject.id; }); } room.memory.calcComplete = true; } }); } function SpawnCreeps() { if(Object.keys(Game.creeps).length < 4) { // Spawn a new creep } } function HandleCreeps() { Object.keys(Game.creeps).forEach(function (creepName) { var creep = Game.creeps[creepName]; if(creep.carry.energy < creep.carryCapacity) { // Move to source or harvest } else { // Move to spawn or transfer } }); } function EndTick() { Memory.recalcRooms = false; console.log(Game.getUsedCpu()); }
Simplify test task since typescript coverage is not supported
"use strict"; require('babel-core/register'); const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), istanbul = require('gulp-istanbul'), isparta = require('isparta'), Promise = require('bluebird'); class TestTask extends Task { constructor(buildManager) { super(buildManager); this.command = "test"; this.dependsOn = [() => { if (this._buildManager.options.typescript) return Promise.resolve(); return gulp.src([this._buildManager.options.scripts + '*/*.js']) .pipe(istanbul({ instrumenter: isparta.Instrumenter, includeUntested: true })) .pipe(istanbul.hookRequire()); }]; } action() { return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({ reporter: 'spec', compilers: { ts: require('ts-node/register'), js: require('babel-core/register') } })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })) } } module.exports = TestTask;
"use strict"; const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), istanbul = require('gulp-istanbul'), isparta = require('isparta'), Promise = require('bluebird'); class TestTask extends Task { constructor(buildManager) { super(buildManager); this.command = "test"; let extension = null; if (this._buildManager.options.typescript) { require('ts-node/register'); extension = 'ts'; } else { require('babel-core/register'); extension = 'js'; } this.dependsOn = [() => { if (this._buildManager.options.typescript) return Promise.resolve(); return gulp.src([this._buildManager.options.scripts + '*/*.' + extension]) .pipe(istanbul({ instrumenter: isparta.Instrumenter, includeUntested: true })) .pipe(istanbul.hookRequire()); }]; } action() { return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({ reporter: 'spec', compilers: { ts: require('ts-node/register'), js: require('babel-core/register') } })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })) } } module.exports = TestTask;
Fix extension loading, namespace extensions behind ext
<?php namespace Prontotype\Extension; class Manager { public function __construct($extpath, $app) { $this->app = $app; $this->path = rtrim($extpath,'/'); $this->extensions = array(); } public function loadExtensions($extensions) { if ( count($extensions) ) { foreach( $extensions as $extensionKey => $extensionFile ) { $extPath = $this->path . '/' . $extensionFile; if ( file_exists($extPath) ) { require_once $extPath; $pathInfo = pathinfo($extPath); $extName = $pathInfo['filename']; $extension = new $extName($this->app); $this->extensions[$extensionKey] = $extension; } } $this->app['twig']->addGlobal('ext', $this->extensions); } } public function before() { foreach($this->extensions as $extension) { $extension->before(); } } public function after() { foreach($this->extensions as $extension) { $extension->after(); } } }
<?php namespace Prontotype\Extension; class Manager { public function __construct($extpath, $app) { $this->app = $app; $this->path = rtrim($extpath,'/'); $this->extensions = array(); } public function loadExtensions($extensions) { if ( count($extensions) ) { $allGlobals = array(); foreach( $extensions as $extensionKey => $extensionFile ) { $extPath = $this->path . '/' . $extensionFile; if ( file_exists($extPath) ) { require_once $extPath; $pathInfo = pathinfo($extPath); $extName = $pathInfo['filename']; $extension = new $extName($this->app); $globals = $extension->globals(); if ( $globals || is_array($globals) && count($globals) ) { $this->app['twig']->addGlobal($extensionKey, $globals); } $this->extensions[] = $extension; } } } } public function before() { foreach($this->extensions as $extension) { $extension->before(); } } public function after() { foreach($this->extensions as $extension) { $extension->after(); } } }
Remove superfluous option from print_row.
import fileinput import textwrap import sys class Table(object): def __init__(self): self.lines = [] self.width = 20 def feed(self,line): self.lines.append(line.split("\t")) def print_sep(self): for _ in range(len(self.lines[0])): print "-"*self.width, print def print_begin(self): for _ in self.lines[0][0:-1]: sys.stdout.write("-"*(self.width+1)) sys.stdout.write("-"*self.width) print def print_end(self): self.print_begin() def print_row(self,line): cells = [] for celldata in line: cells.append(textwrap.wrap(celldata,self.width)) max_d = max(map(len,cells)) for i in range(max_d): for cell in cells: try: print "%-*s" % (self.width,cell[i]), except IndexError: print " "*self.width, print def print_blank_line(self): print def dump(self): lines = self.lines header = lines[0] self.print_begin() self.print_row(header) self.print_sep() for line in lines[1:]: self.print_row(line) self.print_blank_line() self.print_end() def main(): table = Table() for line in fileinput.input(): table.feed(line.rstrip()) table.dump()
import fileinput import textwrap import sys class Table(object): def __init__(self): self.lines = [] self.width = 20 def feed(self,line): self.lines.append(line.split("\t")) def print_sep(self): for _ in range(len(self.lines[0])): print "-"*self.width, print def print_begin(self): for _ in self.lines[0][0:-1]: sys.stdout.write("-"*(self.width+1)) sys.stdout.write("-"*self.width) print def print_end(self): self.print_begin() def print_row(self,line,spacer=True): cells = [] for celldata in line: cells.append(textwrap.wrap(celldata,self.width)) max_d = max(map(len,cells)) for i in range(max_d): for cell in cells: try: print "%-*s" % (self.width,cell[i]), except IndexError: print " "*self.width, print def print_blank_line(self): print def dump(self): lines = self.lines header = lines[0] self.print_begin() self.print_row(header) self.print_sep() for line in lines[1:]: self.print_row(line) self.print_blank_line() self.print_end() def main(): table = Table() for line in fileinput.input(): table.feed(line.rstrip()) table.dump()
Update tasks to generate docs on watch
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ concat: { all: { src: [ 'src/module.js', 'src/*/**/*.js' ], dest: 'build/ng-drag.js' } }, uglify: { drag: { files: { 'build/ng-drag.min.js': ['build/ng-drag.js'] } } }, ngAnnotate: { survey: { files: { 'build/ng-drag.js': ['build/ng-drag.js'] } } }, watch: { all: { files: ['src/**/*.js'], tasks: [ 'build', 'docs' ], options: { spawn: false } } }, ngdocs: { options: { dest: 'docs' }, ngdrag: { src: ['src/**/*.js'], title: 'ngDrag' } } }); grunt.registerTask('build', [ 'concat', 'ngAnnotate', 'uglify', ]); grunt.registerTask('default', 'build'); grunt.registerTask('docs', [ 'ngdocs' ]); };
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ concat: { all: { src: [ 'src/module.js', 'src/*/**/*.js' ], dest: 'build/ng-drag.js' } }, uglify: { drag: { files: { 'build/ng-drag.min.js': ['build/ng-drag.js'] } } }, ngAnnotate: { survey: { files: { 'build/ng-drag.js': ['build/ng-drag.js'] } } }, watch: { all: { files: ['src/**/*.js'], tasks: ['build'], options: { spawn: false } } }, ngdocs: { options: { dest: 'docs' }, ngdrag: { src: ['src/**/*.js'], title: 'ngDrag' } } }); grunt.registerTask('build', [ 'concat', 'ngAnnotate', 'uglify', ]); grunt.registerTask('default', 'build'); };
Fix the cleaning of the message once it is sent.
$(window).load(function () { var Ector = require('ector'); var ector = new Ector(); var previousResponseNodes = null; var user = { username: "Guy"}; var msgtpl = $('#msgtpl').html(); var lastmsg = false; $('#msgtpl').remove(); var message; $('#send').on('click', function () { var d = new Date(); var entry = $('#message').val(); message = { user: user, message: entry, h: d.getHours(), m: d.getMinutes() }; $('#message').attr('value',''); // FIXME $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); ector.addEntry(entry); ector.linkNodesToLastSentence(previousResponseNodes); var response = ector.generateResponse(); // console.log('%s: %s', ector.name, response.sentence); previousResponseNodes = response.nodes; d = new Date(); message = { user: {username: ector.name}, message: response.sentence, h: d.getHours(), m: d.getMinutes() }; $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); }); });
$(window).load(function () { var Ector = require('ector'); var ector = new Ector(); var previousResponseNodes = null; var user = { username: "Guy"} var msgtpl = $('#msgtpl').html(); var lastmsg = false; $('#msgtpl').remove(); var message; $('#send').on('click', function () { var d = new Date(); var entry = $('#message').val(); message = { user: user, message: entry, h: d.getHours(), m: d.getMinutes() }; $('#message').value = ''; // FIXME $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); ector.addEntry(entry); ector.linkNodesToLastSentence(previousResponseNodes); var response = ector.generateResponse(); // console.log('%s: %s', ector.name, response.sentence); previousResponseNodes = response.nodes; d = new Date(); message = { user: {username: ector.name}, message: response.sentence, h: d.getHours(), m: d.getMinutes() }; $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); }); });
Simplify state setting internally (lose immutability)
import { select, local } from "d3-selection"; var stateLocal = local(), renderLocal = local(), noop = function (){}; export default function (tagName, className){ var render = noop, create, destroy, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className), all = enter.merge(update); if(create){ enter.each(function (){ renderLocal.set(this, noop); stateLocal.set(this, {}); create(function (state){ Object.assign(stateLocal.get(this), state); renderLocal.get(this)(); }.bind(this)); }); all.each(function (props){ renderLocal.set(this, function (){ select(this).call(render, props, stateLocal.get(this)); }.bind(this)); renderLocal.get(this)(); }); if(destroy){ exit.each(function (){ renderLocal.set(this, noop); destroy(stateLocal.get(this)); }); } } else { all.each(function (props){ select(this).call(render, props); }); } exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
import { select, local } from "d3-selection"; var stateLocal = local(), renderLocal = local(), noop = function (){}; export default function (tagName, className){ var render = noop, create, destroy, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className), all = enter.merge(update); if(create){ enter.each(function (){ renderLocal.set(this, noop); create(function (state){ stateLocal.set(this, Object.assign({}, stateLocal.get(this), state)); renderLocal.get(this)(); }.bind(this)); }); all.each(function (props){ renderLocal.set(this, function (){ select(this).call(render, props, stateLocal.get(this)); }.bind(this)); renderLocal.get(this)(); }); if(destroy){ exit.each(function (){ renderLocal.set(this, noop); destroy(stateLocal.get(this)); }); } } else { all.each(function (props){ select(this).call(render, props); }); } exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
Fix a crash in the gear tab when an Artifact's relics are not known
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import ITEM_QUALITIES from 'common/ITEM_QUALITIES'; class Gear extends React.PureComponent { static propTypes = { selectedCombatant: PropTypes.object.isRequired, }; render() { const gear = Object.values(this.props.selectedCombatant._gearItemsBySlotId); const artifact = gear.find(item => item.quality === 6); const relics = artifact && artifact.gems ? artifact.gems : []; return ( <div> <div style={{ marginLeft: 'auto', marginRight: 'auto', display: 'block', width: '90%' }}> {[...gear, ...relics] .filter(item => item.id !== 0) .map(item => ( <div key={item.id} style={{ display: 'inline-block', textAlign: 'center' }}> {item.itemLevel} <ItemLink id={item.id} quality={item.quality || ITEM_QUALITIES.EPIC}// relics don't have a quality, but they're always epic details={item} style={{ margin: '5px', display: 'block', fontSize: '46px', lineHeight: 1 }} > <Icon icon={item.icon} style={{ border: '3px solid currentColor' }} /> </ItemLink> </div> ))} </div> </div> ); } } export default Gear;
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import ITEM_QUALITIES from 'common/ITEM_QUALITIES'; class Gear extends React.PureComponent { static propTypes = { selectedCombatant: PropTypes.object.isRequired, }; render() { const gear = Object.values(this.props.selectedCombatant._gearItemsBySlotId); const artifact = gear.find(item => item.quality === 6); const relics = artifact ? artifact.gems : []; return ( <div> <div style={{ marginLeft: 'auto', marginRight: 'auto', display: 'block', width: '90%' }}> {[...gear, ...relics] .filter(item => item.id !== 0) .map(item => ( <div key={item.id} style={{ display: 'inline-block', textAlign: 'center' }}> {item.itemLevel} <ItemLink id={item.id} quality={item.quality || ITEM_QUALITIES.EPIC}// relics don't have a quality, but they're always epic details={item} style={{ margin: '5px', display: 'block', fontSize: '46px', lineHeight: 1 }} > <Icon icon={item.icon} style={{ border: '3px solid currentColor' }} /> </ItemLink> </div> ))} </div> </div> ); } } export default Gear;
Use the 'should expose some global scope' test As seen in examples when there doesn't seem to be anything else to test.
'use strict'; (function() { describe("voteeHome", function() { beforeEach(function() { module('mean'); module('mean.voteeHome'); }); var $controller; var $scope; beforeEach(inject(function(_$controller_){ // The injector unwraps the underscores (_) from around the parameter names when matching $controller = _$controller_; })); describe("voteeHome controller", function() { beforeEach(function() { $scope = {}; var controller = $controller('VoteeHomeController', { $scope: $scope }); }); it('should expose some global scope', function() { expect(true).toBeTruthy(); }); }); describe("header controller", function() { beforeEach(function() { $scope = {}; var controller = $controller('VoteeHeaderController', { $scope: $scope }); }); it("Has a menu", function() { expect($scope.menus).toBeDefined(); expect($scope.menus).not.toBeNull(); expect($scope.menus.length).not.toBe(0); }); }); }); }());
'use strict'; (function() { describe("voteeHome", function() { beforeEach(function() { module('mean'); module('mean.voteeHome'); }); var $controller; var $scope; beforeEach(inject(function(_$controller_){ // The injector unwraps the underscores (_) from around the parameter names when matching $controller = _$controller_; })); describe("voteeHome controller", function() { beforeEach(function() { $scope = {}; var controller = $controller('VoteeHomeController', { $scope: $scope }); }); it("stub", function() { expect(true).toBe(true); }); }); describe("header controller", function() { beforeEach(function() { $scope = {}; var controller = $controller('VoteeHeaderController', { $scope: $scope }); }); it("Has a menu", function() { expect($scope.menus).toBeDefined(); expect($scope.menus).not.toBeNull(); expect($scope.menus.length).not.toBe(0); }); }); }); }());
Use ponyfil for base error
var captureStackTrace = require('capture-stack-trace'); function BaseError(data){ var oldLimit = Error.stackTraceLimit, error; Error.stackTraceLimit = 20; error = Error.apply(this, arguments); Error.stackTraceLimit = oldLimit; captureStackTrace(this, BaseError); this.__genericError = true; if(typeof data === 'string'){ this.message = data; } else { for(var key in data){ this[key] = data[key]; } if(!this.message && data && data.message){ this.message = data.message; } } if(!this.message){ this.message = this.toString(); } } BaseError.prototype = Object.create(Error.prototype); BaseError.prototype.constructor = BaseError; BaseError.prototype.toString = function(){ return this.message || this.code + ': ' + this.constructor.name; }; BaseError.prototype.valueOf = function(){ return this; }; BaseError.prototype.toJSON = function() { var result = {}; for(var key in this) { if(typeof this[key] !== 'function') result[key] = this[key]; } return result; }; BaseError.prototype.code = 500; BaseError.isGenericError = function(obj){ return obj instanceof BaseError || (obj != null && obj.__genericError); }; module.exports = BaseError;
function BaseError(data){ var oldLimit = Error.stackTraceLimit, error; Error.stackTraceLimit = 20; error = Error.apply(this, arguments); Error.stackTraceLimit = oldLimit; if(Error.captureStackTrace){ Error.captureStackTrace(this, BaseError); } this.__genericError = true; if(typeof data === 'string'){ this.message = data; } else { for(var key in data){ this[key] = data[key]; } if(!this.message && data && data.message){ this.message = data.message; } } if(!this.message){ this.message = this.toString(); } } BaseError.prototype = Object.create(Error.prototype); BaseError.prototype.constructor = BaseError; BaseError.prototype.toString = function(){ return this.message || this.code + ': ' + this.constructor.name; }; BaseError.prototype.valueOf = function(){ return this; }; BaseError.prototype.toJSON = function() { var result = {}; for(var key in this) { if(typeof this[key] !== 'function') result[key] = this[key]; } return result; }; BaseError.prototype.code = 500; BaseError.isGenericError = function(obj){ return obj instanceof BaseError || (obj != null && obj.__genericError); }; module.exports = BaseError;
Change lock name to use a name for this app
package com.markupartist.sthlmtraveling.service; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.util.Log; abstract public class WakefulIntentService extends IntentService { private static String TAG = "WakefulIntentService"; public static final String LOCK_NAME_STATIC = "com.markupartist.sthlmtraveling.service.WakefulIntentService.Static"; private static PowerManager.WakeLock lockStatic = null; public WakefulIntentService(String name) { super(name); } synchronized private static PowerManager.WakeLock getLock(Context context) { Log.d(TAG, "About to get lock"); if (lockStatic == null) { PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC); lockStatic.setReferenceCounted(true); } return lockStatic; } abstract void doWakefulWork(Intent intent); public static void acquireStaticLock(Context context) { Log.d(TAG, "About acquire static lock"); getLock(context).acquire(); } @Override final protected void onHandleIntent(Intent intent) { doWakefulWork(intent); getLock(this).release(); } }
package com.markupartist.sthlmtraveling.service; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.util.Log; abstract public class WakefulIntentService extends IntentService { private static String TAG = "WakefulIntentService"; public static final String LOCK_NAME_STATIC = "com.commonsware.android.syssvc.AppService.Static"; private static PowerManager.WakeLock lockStatic = null; public WakefulIntentService(String name) { super(name); } synchronized private static PowerManager.WakeLock getLock(Context context) { Log.d(TAG, "About to get lock"); if (lockStatic == null) { PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC); lockStatic.setReferenceCounted(true); } return(lockStatic); } abstract void doWakefulWork(Intent intent); public static void acquireStaticLock(Context context) { Log.d(TAG, "About acquire static lock"); getLock(context).acquire(); } @Override final protected void onHandleIntent(Intent intent) { doWakefulWork(intent); getLock(this).release(); } }
Set the host for the cli command
<?php namespace Forex\Bundle\EmailBundle\Command; use Forex\Bundle\EmailBundle\Entity\EmailMessage; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\HttpFoundation\Request; class SendPendingEmailsCommand extends ContainerAwareCommand { protected $em; protected $sender; protected function configure() { $this ->setName('email:send-pending-emails') ->setDescription('Sends all pending emails') ; } protected function initialize(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $request = new Request(); $request->headers->set('host', $container->getParameter('cli_host')); $container->set('request', $request); $container->enterScope('request'); $this->em = $container->get('doctrine.orm.default_entity_manager'); $this->sender = $container->get('forex.email_sender'); } protected function execute(InputInterface $input, OutputInterface $output) { $progress = $this->getHelperSet()->get('progress'); $pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails(); $progress->start($output, count($pendingMessages)); foreach ($pendingMessages as $message) { $this->sender->send($message); $progress->advance(); } $progress->finish(); $this->em->flush(); } }
<?php namespace Forex\Bundle\EmailBundle\Command; use Forex\Bundle\EmailBundle\Entity\EmailMessage; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\HttpFoundation\Request; class SendPendingEmailsCommand extends ContainerAwareCommand { protected $em; protected $sender; protected function configure() { $this ->setName('email:send-pending-emails') ->setDescription('Sends all pending emails') ; } protected function initialize(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $request = new Request(); $container->set('request', $request); $container->enterScope('request'); $this->em = $container->get('doctrine.orm.default_entity_manager'); $this->sender = $container->get('forex.email_sender'); } protected function execute(InputInterface $input, OutputInterface $output) { $progress = $this->getHelperSet()->get('progress'); $pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails(); $progress->start($output, count($pendingMessages)); foreach ($pendingMessages as $message) { $this->sender->send($message); $progress->advance(); } $progress->finish(); $this->em->flush(); } }
Add sub views to the router.
"use strict"; (function () { angular .module("argo") .config(config) .run(setup); config.$inject = ["$stateProvider", "$urlRouterProvider"]; function config($stateProvider, $urlRouterProvider) { $stateProvider .state("default", { abstract: true, url: "/", templateUrl: "views/default.html", controller: "DefaultCtrl", controllerAs: "default" }) .state("default.subs", { views: { "header": { templateUrl: "views/header.html" }, "trades": { templateUrl: "views/trades.html" }, "orders": { templateUrl: "views/orders.html" }, "positions": { templateUrl: "views/positions.html" }, "exposure": { templateUrl: "views/exposure.html" }, "activity": { templateUrl: "views/activity.html" }, "news": { templateUrl: "views/news.html" }, "account": { templateUrl: "views/account.html" }, "quotes": { templateUrl: "views/quotes.html" }, "charts": { templateUrl: "views/charts.html" } } }); $urlRouterProvider.otherwise("/"); } setup.$inject = ["$state"]; function setup($state) { $state.transitionTo("default.subs"); } }());
"use strict"; (function () { angular .module("argo") .config(config) .run(setup); config.$inject = ["$stateProvider", "$urlRouterProvider"]; function config($stateProvider, $urlRouterProvider) { $stateProvider .state("index", { abstract: true, url: "/", views: { "default": { templateUrl: "views/default.html", controller: "DefaultCtrl", controllerAs: "default" } } }) .state("index.subs", { url: "", views: { "account@index": { templateUrl: "views/account.html" } } }); $urlRouterProvider.otherwise("/"); } setup.$inject = ["$state"]; function setup($state) { $state.transitionTo("index.subs"); } }());
Fix for markdown handler when using application objects branch
<?php namespace Rhubarb\Website\UrlHandlers; use Rhubarb\Crown\UrlHandlers\UrlHandler; require_once "vendor/rhubarbphp/rhubarb/src/UrlHandlers/UrlHandler.php"; require_once "vendor/geeks-dev/php-markdown-extra-extended-stylish/markdown_extended_stylish.php"; class MarkdownUrlHandler extends UrlHandler { /** * Return the response if appropriate or false if no response could be generated. * * @param mixed $request * @return bool */ protected function generateResponseForRequest($request = null) { $url = $request->urlPath; if ($url[strlen($url) - 1] == "/") { $url = $url . "index"; } $rootPath = "docs"; // If this is the manual - we could be looking at other rhubarb projects. if ( preg_match( "/\/manual\/([^\/]+)\//", $url, $match ) ) { $url = str_replace( $match[0], "", $url ); $rootPath = "vendor/rhubarbphp/".$match[1]."/docs/"; } // Look to see if there's a markdown file at this location. if (file_exists($rootPath . $url . ".md")) { $markDownRaw = file_get_contents($rootPath . $url . ".md"); return MarkdownExtended($markDownRaw); } } }
<?php namespace Rhubarb\Website\UrlHandlers; use Rhubarb\Crown\UrlHandlers\UrlHandler; require_once "vendor/rhubarbphp/rhubarb/src/UrlHandlers/UrlHandler.php"; require_once "vendor/geeks-dev/php-markdown-extra-extended-stylish/markdown_extended_stylish.php"; class MarkdownUrlHandler extends UrlHandler { /** * Return the response if appropriate or false if no response could be generated. * * @param mixed $request * @return bool */ protected function generateResponseForRequest($request = null) { $url = $request->UrlPath; if ($url[strlen($url) - 1] == "/") { $url = $url . "index"; } $rootPath = "docs"; // If this is the manual - we could be looking at other rhubarb projects. if ( preg_match( "/\/manual\/([^\/]+)\//", $url, $match ) ) { $url = str_replace( $match[0], "", $url ); $rootPath = "vendor/rhubarbphp/".$match[1]."/docs/"; } // Look to see if there's a markdown file at this location. if (file_exists($rootPath . $url . ".md")) { $markDownRaw = file_get_contents($rootPath . $url . ".md"); return MarkdownExtended($markDownRaw); } } }
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <[email protected]>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
Use bind instead of wrapping the function to forward errors.
'use strict'; var https = require("https"), EventEmitter = require('events'); /** * Forward an error to another emitter. */ var forwardError = function (emitter) { return emitter.emit.bind(emitter, 'error'); }; /** * Request a JSON object over HTTPS. Returns an emitter. Emits 'response', * 'data' and 'error' events. * The response event is passed the HTTPS response. * If the status code is 200 a 'data' event should be emitted, passed an object * parsed from the JSON data. * If there is an error making the request an error event will be emitted. */ var getJsonOverHttps = function (options) { var emitter = new EventEmitter(); https.get(options, function (res) { emitter.emit('response', res); if (res.statusCode === 200) { var buffers = []; res .on('data', function (d) { buffers.push(d); }) .on('end', function () { var completeBuffer = Buffer.concat(buffers); emitter.emit('data', JSON.parse(completeBuffer)); }); } else { emitter.emit('error', new Error('Response status code was ' + res.statusCode)); } }) .on('error', forwardError(emitter)); return emitter; }; module.exports = { forwardError : forwardError, getJsonOverHttps : getJsonOverHttps };
'use strict'; var https = require("https"), EventEmitter = require('events'); /** * Forward an error to another emitter. */ var forwardError = function (emitter) { return function (error) { emitter.emit('error', error); }; }; /** * Request a JSON object over HTTPS. Returns an emitter. Emits 'response', * 'data' and 'error' events. * The response event is passed the HTTPS response. * If the status code is 200 a 'data' event should be emitted, passed an object * parsed from the JSON data. * If there is an error making the request an error event will be emitted. */ var getJsonOverHttps = function (options) { var emitter = new EventEmitter(); https.get(options, function (res) { emitter.emit('response', res); if (res.statusCode === 200) { var buffers = []; res .on('data', function (d) { buffers.push(d); }) .on('end', function () { var completeBuffer = Buffer.concat(buffers); emitter.emit('data', JSON.parse(completeBuffer)); }); } else { emitter.emit('error', new Error('Response status code was ' + res.statusCode)); } }) .on('error', forwardError(emitter)); return emitter; }; module.exports = { forwardError : forwardError, getJsonOverHttps : getJsonOverHttps };
[Form] Allow setting different options to repeating fields
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class RepeatedType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilder $builder, array $options) { $builder ->appendClientTransformer(new ValueToDuplicatesTransformer(array( $options['first_name'], $options['second_name'], ))) ->add($options['first_name'], $options['type'], 0 < count($options['first_options']) ? $options['first_options'] : $options['options']) ->add($options['second_name'], $options['type'], 0 < count($options['second_options']) ? $options['second_options'] : $options['options']) ; } /** * {@inheritdoc} */ public function getDefaultOptions(array $options) { return array( 'type' => 'text', 'options' => array(), 'first_options' => array(), 'second_options' => array(), 'first_name' => 'first', 'second_name' => 'second', 'error_bubbling' => false, ); } /** * {@inheritdoc} */ public function getName() { return 'repeated'; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class RepeatedType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilder $builder, array $options) { $builder ->appendClientTransformer(new ValueToDuplicatesTransformer(array( $options['first_name'], $options['second_name'], ))) ->add($options['first_name'], $options['type'], $options['options']) ->add($options['second_name'], $options['type'], $options['options']) ; } /** * {@inheritdoc} */ public function getDefaultOptions(array $options) { return array( 'type' => 'text', 'options' => array(), 'first_name' => 'first', 'second_name' => 'second', 'error_bubbling' => false, ); } /** * {@inheritdoc} */ public function getName() { return 'repeated'; } }
Fix bind shared with singleton when registering the HTML service provider
<?php namespace Aginev\Datagrid; use Collective\Html\FormFacade; use Collective\Html\HtmlFacade; use Collective\Html\HtmlServiceProvider; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; class DatagridServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // Tell Laravel where the views for a given namespace are located. $this->loadViewsFrom(__DIR__ . '/Views', 'datagrid'); $this->publishes([ __DIR__ . '/Views' => base_path('resources/views/vendor/datagrid'), base_path('vendor/aginev/datagrid/src/Views') => base_path('resources/views/vendor/datagrid'), ], 'views'); } /** * Register the application services. * * @return void */ public function register() { // Register the HtmlServiceProvider $this->app->singleton('Illuminate\Html\HtmlServiceProvider'); // Add aliases to Form/Html Facade $loader = AliasLoader::getInstance(); $loader->alias('Form', FormFacade::class); $loader->alias('HTML', HtmlFacade::class); // Add alias for datagrid $loader->alias('Datagrid', 'Aginev\Datagrid\Datagrid'); } }
<?php namespace Aginev\Datagrid; use Collective\Html\FormFacade; use Collective\Html\HtmlFacade; use Collective\Html\HtmlServiceProvider; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; class DatagridServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // Tell Laravel where the views for a given namespace are located. $this->loadViewsFrom(__DIR__ . '/Views', 'datagrid'); $this->publishes([ __DIR__ . '/Views' => base_path('resources/views/vendor/datagrid'), base_path('vendor/aginev/datagrid/src/Views') => base_path('resources/views/vendor/datagrid'), ], 'views'); } /** * Register the application services. * * @return void */ public function register() { // Register the HtmlServiceProvider App::register(HtmlServiceProvider::class); // Add aliases to Form/Html Facade $loader = AliasLoader::getInstance(); $loader->alias('Form', FormFacade::class); $loader->alias('HTML', HtmlFacade::class); // Add alias for datagrid $loader->alias('Datagrid', 'Aginev\Datagrid\Datagrid'); } }
Add signal handler for sigterm.
import logging.config from setproctitle import setproctitle import signal def process_setup(): exitcmd = lambda *_: exit(0) signal.signal(signal.SIGINT, exitcmd) signal.signal(signal.SIGTERM, exitcmd) setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
import logging.config from setproctitle import setproctitle def process_setup(): setproctitle('ksurctrobot') logging.config.dictConfig({ 'version': 1, 'formatters': { 'long': { 'format': '%(relativeCreated)d %(threadName)-12s %(levelname)-5s %(name)-20s %(message)s' }, 'brief': { 'format': 'log %(threadName)-12s %(levelname)-8s %(name)-12s %(message)s' }, }, 'handlers': { 'console': { 'formatter': 'brief', 'class': 'logging.StreamHandler', 'level': logging.DEBUG, } }, 'loggers': { 'ksurobot': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, 'websockets.server': { 'propagate': False, 'handlers': ['console'], 'level': logging.DEBUG, }, }, 'root': { 'handlers': ['console'], 'level': logging.INFO, }, })
Support base url in front-end url resolver.
<?php /* * Copyright 2015 Jack Sleight <http://jacksleight.com/> * This source file is subject to the MIT license that is bundled with this package in the file LICENCE. */ namespace Chalk\Frontend; use Chalk\Chalk; use Closure; use Coast\UrlResolver as CoastUrlResolver; class UrlResolver extends CoastUrlResolver { protected $_resolvers = []; public function __invoke() { $args = func_get_args(); if (!isset($args[0])) { $func = array($this, 'string'); } else { $func = array($this, 'content'); } return call_user_func_array($func, $args); } public function content($content) { $info = Chalk::info($content); if (!isset($this->_resolvers[$info->name])) { return false; } foreach ($this->_resolvers[$info->name] as $resolver) { $result = $resolver($content); if (isset($result)) { if ($result) { return $result; } else { return false; } } } } public function resolver($entity, Closure $resolver) { $this->_resolvers[$entity][] = $resolver->bindTo($this); return $this; } }
<?php /* * Copyright 2015 Jack Sleight <http://jacksleight.com/> * This source file is subject to the MIT license that is bundled with this package in the file LICENCE. */ namespace Chalk\Frontend; use Chalk\Chalk; use Closure; use Coast\UrlResolver as CoastUrlResolver; class UrlResolver extends CoastUrlResolver { protected $_resolvers = []; public function __invoke() { $args = func_get_args(); return call_user_func_array([$this, 'content'], $args); } public function content($content) { $info = Chalk::info($content); if (!isset($this->_resolvers[$info->name])) { return false; } foreach ($this->_resolvers[$info->name] as $resolver) { $result = $resolver($content); if (isset($result)) { if ($result) { return $result; } else { return false; } } } } public function resolver($entity, Closure $resolver) { $this->_resolvers[$entity][] = $resolver->bindTo($this); return $this; } }
Use code argument for `timeit`, only time execution
<?php namespace Psy\Command; use Psy\Configuration; use Psy\Input\CodeArgument; use Psy\Shell; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class TimeitCommand * @package Psy\Command */ class TimeitCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this ->setName('timeit') ->setDefinition(array( new CodeArgument('code', InputArgument::REQUIRED, 'Code to execute.'), )) ->setDescription('Profiles with a timer.') ->setHelp( <<<HELP Time profiling for functions and commands. e.g. <return>>>> timeit \$closure()</return> HELP ); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $code = $input->getArgument('code'); /** @var Shell $shell */ $shell = $this->getApplication(); $sh = new Shell(new Configuration()); $sh->setOutput($output); $sh->setScopeVariables($shell->getScopeVariables()); $start = microtime(true); $sh->execute($code); $end = microtime(true); $output->writeln(sprintf('<info>Command took %.6f seconds to complete.</info>', $end-$start)); } }
<?php namespace Psy\Command; use Psy\Configuration; use Psy\Shell; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; /** * Class TimeitCommand * @package Psy\Command */ class TimeitCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this ->setName('timeit') ->setDefinition(array( new InputArgument('target', InputArgument::REQUIRED, 'A target object or primitive to profile.', null), )) ->setDescription('Profiles with a timer.') ->setHelp( <<<HELP Time profiling for functions and commands. e.g. <return>>>> timeit \$closure()</return> HELP ); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $target = $input->getArgument('target'); $start = microtime(true); /** @var Shell $shell */ $shell = $this->getApplication(); $sh = new Shell(new Configuration()); $sh->setOutput($output); $sh->setScopeVariables($shell->getScopeVariables()); $sh->execute($target); $end = microtime(true); $output->writeln(sprintf('<info>Command took %.6f seconds to complete.</info>', $end-$start)); } }
Put time and day in separate columns
import moment from 'moment' import textTable from 'text-table' const find = (apiWrapper) => (search, options) => { const { startdate, enddate, businessunitids } = options return new Promise((resolve, reject) => { apiWrapper.getActivities({ startdate, enddate, businessunitids }) .then((response) => { const searchParam = search.toLowerCase() const activities = response.activities.activity const foundActivities = activities.filter((activity) => { const name = activity.product.name.toLowerCase() const bookableSlots = parseInt(activity.bookableslots, 10) return name.indexOf(searchParam) !== -1 && bookableSlots > 0 }) .map((activity) => { const startTime = activity.start.timepoint.datetime const dayOfWeek = moment(startTime).format('dddd') const time = moment(startTime).format('HH:mm') return [ activity.id, dayOfWeek, time, activity.product.name, activity.bookableslots ] }) if (foundActivities.length === 0) { resolve('No activities found') } const table = textTable(foundActivities) const spacedTable = `\`\`\`${table.toString()}\`\`\`` resolve(spacedTable) }) }) } export default find
import moment from 'moment' import textTable from 'text-table' const find = (apiWrapper) => (search, options) => { const { startdate, enddate, businessunitids } = options return new Promise((resolve, reject) => { apiWrapper.getActivities({ startdate, enddate, businessunitids }) .then((response) => { const searchParam = search.toLowerCase() const activities = response.activities.activity const foundActivities = activities.filter((activity) => { const name = activity.product.name.toLowerCase() const bookableSlots = parseInt(activity.bookableslots, 10) return name.indexOf(searchParam) !== -1 && bookableSlots > 0 }) .map((activity) => { const startTime = activity.start.timepoint.datetime const dayOfWeek = moment(startTime).format('dddd') const time = moment(startTime).format('HH:mm') const formattedStartTime = `${dayOfWeek} ${time}` return [ activity.id, formattedStartTime, activity.product.name, activity.bookableslots ] }) if (foundActivities.length === 0) { resolve('No activities found') } const table = textTable(foundActivities) const spacedTable = `\`\`\`${table.toString()}\`\`\`` resolve(spacedTable) }) }) } export default find
Fix problem with array values.
import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = None self.mean_value = None def filter(self, value): self.last_value = value if self.mean_value is None: self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = np.nan self.mean_value = np.nan def filter(self, value): self.last_value = value if np.isnan(self.mean_value): self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
Test to only use Media if phone-gap version of HTML/JS
var StartView = function(homeView) { this.homeView = homeView; this.initialize = function() { // 'div' wrapper to attach html and events to this.el = $('<div/>'); }; this.render = function() { if (!this.homeView) { this.homeView = { enteredName: "" } } this.el.html(StartView.template(this.homeView)); return this; }; this.getPhoneGapPath = function() { var path = window.location.pathname; path = path.substr( path, path.length - 10 ); return 'file://' + path; }; this.playAudio = function() { if (window.cordova) { var url = this.getPhoneGapPath() + 'audio/eab-innovation.mp3'; var snd = new Media(url, function () { console.log("playAudio():Audio Success"); }, function (err) { console.log("playAudio():Audio Error: " + err); } ); // Play audio snd.play(); } }; this.crossfade = function(delay) { $("#svg-bubbles-div").delay(delay).animate({ opacity: 0 }, 700); $("#after-bubbles").delay(delay).css("display","block").animate({ opacity: 1 }, 700); this.playAudio(); }; this.initialize(); } StartView.template = Handlebars.compile($("#start-tpl").html());
var StartView = function(homeView) { this.homeView = homeView; this.initialize = function() { // 'div' wrapper to attach html and events to this.el = $('<div/>'); }; this.render = function() { if (!this.homeView) { this.homeView = { enteredName: "" } } this.el.html(StartView.template(this.homeView)); return this; }; this.getPhoneGapPath = function() { var path = window.location.pathname; path = path.substr( path, path.length - 10 ); return 'file://' + path; }; this.playAudio = function() { var url = this.getPhoneGapPath() + 'audio/eab-innovation.mp3'; var snd = new Media(url, function () { console.log("playAudio():Audio Success"); }, function (err) { console.log("playAudio():Audio Error: " + err); } ); // Play audio snd.play(); }; this.crossfade = function(delay) { $("#svg-bubbles-div").delay(delay).animate({ opacity: 0 }, 700); $("#after-bubbles").delay(delay).css("display","block").animate({ opacity: 1 }, 700); this.playAudio(); }; this.initialize(); } StartView.template = Handlebars.compile($("#start-tpl").html());
Add node specific tag generation
import io import os import yaml from solar.extensions import base class Discovery(base.BaseExtension): VERSION = '1.0.0' ID = 'discovery' PROVIDES = ['nodes_resources'] COLLECTION_NAME = 'nodes' FILE_PATH = os.path.join( # TODO(pkaminski): no way we need '..' here... os.path.dirname(__file__), '..', '..', '..', '..', 'examples', 'nodes_list.yaml') def discover(self): with io.open(self.FILE_PATH) as f: nodes = yaml.load(f) for node in nodes: node['tags'] = ['node/{0}'.format(node['id'])] self.db.store_list(self.COLLECTION_NAME, nodes) return nodes def nodes_resources(self): nodes_list = self.db.get_list(self.COLLECTION_NAME) nodes_resources = [] for node in nodes_list: node_resource = {} node_resource['id'] = node['id'] node_resource['name'] = node['id'] node_resource['handler'] = 'data' node_resource['type'] = 'resource' node_resource['version'] = self.VERSION node_resource['tags'] = node['tags'] node_resource['output'] = node node_resource['ssh_host'] = node['ip'] # TODO replace it with ssh type node_resource['connection_type'] = 'local' nodes_resources.append(node_resource) return nodes_resources
import io import os import yaml from solar.extensions import base class Discovery(base.BaseExtension): VERSION = '1.0.0' ID = 'discovery' PROVIDES = ['nodes_resources'] COLLECTION_NAME = 'nodes' FILE_PATH = os.path.join( # TODO(pkaminski): no way we need '..' here... os.path.dirname(__file__), '..', '..', '..', '..', 'examples', 'nodes_list.yaml') def discover(self): with io.open(self.FILE_PATH) as f: nodes = yaml.load(f) for node in nodes: node['tags'] = [] self.db.store_list(self.COLLECTION_NAME, nodes) return nodes def nodes_resources(self): nodes_list = self.db.get_list(self.COLLECTION_NAME) nodes_resources = [] for node in nodes_list: node_resource = {} node_resource['id'] = node['id'] node_resource['name'] = node['id'] node_resource['handler'] = 'data' node_resource['type'] = 'resource' node_resource['version'] = self.VERSION node_resource['tags'] = node['tags'] node_resource['output'] = node node_resource['ssh_host'] = node['ip'] # TODO replace it with ssh type node_resource['connection_type'] = 'local' nodes_resources.append(node_resource) return nodes_resources
Resolve all the JS errors
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; var navController = $('#nav-controller'); if (navController) { navController.on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); } /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } var horizontalScrolling = document.getElementById('horizontal-scrolling'); if (horizontalScrolling) { if (horizontalScrolling.addEventListener) { // IE9, Chrome, Safari, Opera horizontalScrolling.addEventListener("mousewheel", scrollHorizontally, false); // Firefox horizontalScrolling.addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 horizontalScrolling.attachEvent("onmousewheel", scrollHorizontally); } } }); /*File uplad button*/ document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; });
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; $('#nav-controller').on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } if (document.getElementById('horizontal-scrolling').addEventListener) { // IE9, Chrome, Safari, Opera document.getElementById('horizontal-scrolling').addEventListener("mousewheel", scrollHorizontally, false); // Firefox document.getElementById('horizontal-scrolling').addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 document.getElementById('horizontal-scrolling').attachEvent("onmousewheel", scrollHorizontally); } }); /*File uplad button*/ document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; });
Add 'handlers' package to distribution.
import os from setuptools import setup setup( name = "prometheus_client", version = "0.0.18", author = "Brian Brazil", author_email = "[email protected]", description = ("Python client for the Prometheus monitoring system."), long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."), license = "Apache Software License 2.0", keywords = "prometheus monitoring instrumentation client", url = "https://github.com/prometheus/client_python", packages=['prometheus_client', 'prometheus_client.bridge', 'prometheus_client.twisted', 'prometheus_client.handlers'], extras_requires={ 'twisted': ['twisted'], }, test_suite="tests", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: System :: Monitoring", "License :: OSI Approved :: Apache Software License", ], )
import os from setuptools import setup setup( name = "prometheus_client", version = "0.0.18", author = "Brian Brazil", author_email = "[email protected]", description = ("Python client for the Prometheus monitoring system."), long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."), license = "Apache Software License 2.0", keywords = "prometheus monitoring instrumentation client", url = "https://github.com/prometheus/client_python", packages=['prometheus_client', 'prometheus_client.bridge', 'prometheus_client.twisted'], extras_requires={ 'twisted': ['twisted'], }, test_suite="tests", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: System :: Monitoring", "License :: OSI Approved :: Apache Software License", ], )
Fix admin table on mobile devices
@extends('layouts.master') @section('title', 'Admin Dashboard') @section('content') <div class="row justify-content-center mt-2"> <div class="col-8"> <div class="card"> <div class="card-header"> Admin </div> <div class="card-body"> <div class="row"> <div class="col-12 table-responsive"> <h2>Server List</h2> <table class="table text-center"> <thead class="thead-light"> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Created At</th> <th scope="col">Actions</th> </tr> </thead> <tbody> @foreach($servers as $server) <tr> <td>{{$server->id}}</td> <td>{{$server->name}}</td> <td>{{$server->created_at}}</td> <td class="d-flex justify-content-center"> <div class="btn-group"> <a class="btn btn-success" href="{{route('dashboard.general', ['server'=>$server->id])}}"><i class="fas fa-pencil-alt"></i> Manage</a> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> </div> @endsection
@extends('layouts.master') @section('title', 'Admin Dashboard') @section('content') <div class="row justify-content-center mt-2"> <div class="col-8"> <div class="card"> <div class="card-header"> Admin </div> <div class="card-body"> <div class="row"> <div class="col-12"> <h2>Server List</h2> <table class="table text-center"> <thead class="thead-light"> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Created At</th> <th scope="col">Actions</th> </tr> </thead> <tbody> @foreach($servers as $server) <tr> <td>{{$server->id}}</td> <td>{{$server->name}}</td> <td>{{$server->created_at}}</td> <td class="d-flex justify-content-center"> <div class="btn-group"> <a class="btn btn-success" href="{{route('dashboard.general', ['server'=>$server->id])}}"><i class="fas fa-pencil-alt"></i> Manage</a> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> </div> @endsection
Use basic properties and make public properties consistent with other interfaces.
var Proteus = require("proteus"); module.exports = Proteus.Class.derive(Object.defineProperties({ init: function () { this.members = []; Proteus.slice(arguments).forEach(this.add, this); }, get: function (idx) { return this.members[idx]; }, add: function (exp) { return this.members.push(exp); }, remove: function (idx) { return this.members.splice(idx, 1); }, reset: function () { this.members.length = 0; return this; } }, { count: { get: function () { return this.members.length; }, set: function (v) { this.members.length = v; } }, valueOf: { value: function () { var results = [], len = this.count, i ; for (i = 0; i < len; i++) { results.push(this.get(i).valueOf()); } return results.length <= 1 ? results[0] : results; } } }));
var Proteus = require("proteus"); module.exports = Proteus.Class.derive(Object.defineProperties({ init: function () { Object.defineProperties(this, { members: { value: [], enumerable: true } }); Proteus.slice(arguments).forEach(this.add, this); }, add: function (exp) { return this.members.push(exp); }, remove: function (idx) { return this.members.splice(idx, 1); }, reset: function () { this.members.length = 0; return this; } }, { length: { get: function () { return this.members.length; }, set: function (v) { this.members.length = v; } }, valueOf: { value: function () { var results = [], members = this.members, len = members.length, i ; for (i = 0; i < len; i++) { results.push(members[i].valueOf()); } return results.length <= 1 ? results[0] : results; } } }));
Use restRequest for Ajax requests to Girder servers
import View from 'girder/views/View'; import { AccessType } from 'girder/constants'; import { restRequest } from 'girder/rest'; import VegaWidgetTemplate from '../templates/vegaWidget.pug'; import '../stylesheets/vegaWidget.styl'; import vg from 'vega'; var VegaWidget = View.extend({ initialize: function (settings) { this.item = settings.item; this.accessLevel = settings.accessLevel; this.item.on('change', function () { this.render(); }, this); this.render(); }, render: function () { var meta = this.item.get('meta'); if (this.accessLevel >= AccessType.READ && meta && meta.vega) { $('#g-app-body-container') .append(VegaWidgetTemplate()); restRequest({ path: '/api/v1/item/' + this.item.get('_id') + '/download', }) .done(function (spec) { vg.parse.spec(spec, function (chart) { chart({ el: '.g-item-vega-vis', renderer: 'svg' }).update(); }); }); } else { $('.g-item-vega') .remove(); } } }); export default VegaWidget;
import View from 'girder/views/View'; import { AccessType } from 'girder/constants'; import VegaWidgetTemplate from '../templates/vegaWidget.pug'; import '../stylesheets/vegaWidget.styl'; import vg from 'vega'; var VegaWidget = View.extend({ initialize: function (settings) { this.item = settings.item; this.accessLevel = settings.accessLevel; this.item.on('change', function () { this.render(); }, this); this.render(); }, render: function () { var meta = this.item.get('meta'); if (this.accessLevel >= AccessType.READ && meta && meta.vega) { $('#g-app-body-container') .append(VegaWidgetTemplate()); $.ajax({ url: '/api/v1/item/' + this.item.get('_id') + '/download', type: 'GET', dataType: 'json', success: function (spec) { vg.parse.spec(spec, function (chart) { chart({ el: '.g-item-vega-vis', renderer: 'svg' }).update(); }); } }); } else { $('.g-item-vega') .remove(); } } }); export default VegaWidget;
Fix sass custom functions fileExists
var sizeOf = require('image-size'); var sass = require('node-sass'); var config = require('../config.js'); var fileExists = require('file-exists'); if (fileExists('./src/sass/styles.json')) { var styles = require('../../src/sass/styles.json'); } var customFunctions = { 'file-exists($path: "")': function(path) { return sass.types.Boolean(fileExists(path)); }, 'get-main-font()': function() { var returnValue = ''; if (styles !== undefined) { var matches = styles.fonts.filter(function(font) { return font.main === true; }); returnValue = (matches.length > 0 ? matches[0].name : config.defaults.sass.mainFont); } else { returnValue = config.defaults.sass.mainFont; } return sass.types.String(returnValue); }, 'image-width($url: "")': function(url) { var image = url.getValue(); var dimensions = sizeOf(config.src + 'img/' + image); return sass.types.Number(dimensions.width, 'px'); }, 'image-height($url: "")': function(url) { var image = url.getValue(); var dimensions = sizeOf(config.src + 'img/' + image); return sass.types.Number(dimensions.height, 'px'); } }; module.exports = customFunctions;
var sizeOf = require('image-size'); var sass = require('node-sass'); var project = require('../../package.json'); var config = require('../config.js'); var fileExists = require('file-exists'); if (fileExists('../../src/sass/styles.json')) { var styles = require('../../src/sass/styles.json'); } var customFunctions = { 'file-exists($path: "")': function(path) { return sass.types.Boolean(fileExists(path)); }, 'get-main-font()': function() { var returnValue = ''; if (fileExists('../../src/sass/styles.json')) { var matches = styles.fonts.filter(function(font) { return font.main === true; }); var returnValue = (matches.length > 0 ? matches[0].name : config.defaults.sass.mainFont); } else { returnValue = config.defaults.sass.mainFont; } return sass.types.String(returnValue); }, 'image-width($url: "")': function(url) { var image = url.getValue(); var dimensions = sizeOf(config.src + 'img/' + image); return sass.types.Number(dimensions.width, 'px'); }, 'image-height($url: "")': function(url) { var image = url.getValue(); var dimensions = sizeOf(config.src + 'img/' + image); return sass.types.Number(dimensions.height, 'px'); } } module.exports = customFunctions;
Fix the grunt base path
module.exports = function(grunt) { grunt.file.setBase('..'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-shell-spawn'); grunt.initConfig({ pkg: { main: grunt.file.readJSON("../src/package.json") }, uglify: { main: { options: { banner: '/*! <%= pkg.main.name %> v<%= pkg.main.version %> created: <%= grunt.template.today("yyyy-mm-dd") %>*/' }, files: [{ expand: true, cwd: '../src', src: '**/*.js', dest: '../lib/js' }] } }, shell: { proxy: { execOptions: { detached: true }, command: "node ../lib/main/index.js" }, digger: { execOptions: { detached: true }, command: "node ../lib/digger/index.js" }, finder: { execOptions: { detached: true }, command: "node ../lib/finder/index.js" } } }) grunt.registerTask('default', ['uglify:main', 'shell:proxy', 'shell:digger', 'shell:finder']); }
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-shell-spawn'); grunt.initConfig({ pkg: { main: grunt.file.readJSON("../src/package.json") }, uglify: { main: { options: { banner: '/*! <%= pkg.main.name %> v<%= pkg.main.version %> created: <%= grunt.template.today("yyyy-mm-dd") %>*/' }, files: [{ expand: true, cwd: '../src', src: '**/*.js', dest: '../lib/js' }] } }, shell: { proxy: { execOptions: { detached: true }, command: "node ../lib/main/index.js" }, digger: { execOptions: { detached: true }, command: "node ../lib/digger/index.js" }, finder: { execOptions: { detached: true }, command: "node ../lib/finder/index.js" } } }) grunt.registerTask('default', ['uglify:main', 'shell:proxy', 'shell:digger', 'shell:finder']); }
Remove terminal Unicode Escape codes
import sublime import sys import re class CrossPlaformCodecs(): @classmethod def decode_line(self, line): line = line.rstrip() decoded_line = self.force_decode(line) if sys.version_info >= (3, 0) else line decoded_line = re.sub(r'\033\[(\d{1,2}m|\d\w)', '', str(decoded_line)) return decoded_line + "\n" @classmethod def force_decode(self, text): try: text = text.decode('utf-8') except UnicodeDecodeError: if sublime.platform() == "windows": text = self.decode_windows_line(text) return text @classmethod def decode_windows_line(self, text): # Import only for Windows import locale, subprocess # STDERR gets the wrong encoding, use chcp to get the real one proccess = subprocess.Popen(["chcp"], shell=True, stdout=subprocess.PIPE) (chcp, _) = proccess.communicate() # Decode using the locale preferred encoding (for example 'cp1251') and remove newlines chcp = chcp.decode(locale.getpreferredencoding()).strip() # Get the actual number chcp = chcp.split(" ")[-1] # Actually decode return text.decode("cp" + chcp) @classmethod def encode_process_command(self, command): is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(sublime.version()) < 3000 return command.encode(sys.getfilesystemencoding()) if is_sublime_2_and_in_windows else command
import sublime import sys class CrossPlaformCodecs(): @classmethod def decode_line(self, line): line = line.rstrip() decoded_line = self.force_decode(line) if sys.version_info >= (3, 0) else line return str(decoded_line) + "\n" @classmethod def force_decode(self, text): try: text = text.decode('utf-8') except UnicodeDecodeError: if sublime.platform() == "windows": text = self.decode_windows_line(text) return text @classmethod def decode_windows_line(self, text): # Import only for Windows import locale, subprocess # STDERR gets the wrong encoding, use chcp to get the real one proccess = subprocess.Popen(["chcp"], shell=True, stdout=subprocess.PIPE) (chcp, _) = proccess.communicate() # Decode using the locale preferred encoding (for example 'cp1251') and remove newlines chcp = chcp.decode(locale.getpreferredencoding()).strip() # Get the actual number chcp = chcp.split(" ")[-1] # Actually decode return text.decode("cp" + chcp) @classmethod def encode_process_command(self, command): is_sublime_2_and_in_windows = sublime.platform() == "windows" and int(sublime.version()) < 3000 return command.encode(sys.getfilesystemencoding()) if is_sublime_2_and_in_windows else command
Add proper css classes to action buttons
from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', classes='btn btn-sm btn-primary', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', classes='btn btn-sm btn-success', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', classes='btn btn-sm btn-danger', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name)
from django.utils.translation import ugettext as _ from achilles import blocks, tables import nazs register = blocks.Library('core') @register.block(template_name='web/core/welcome.html') def home(): return {'version': nazs.__version__} @register.block(template_name='web/core/apply_button.html') def apply_button(): return {'active': nazs.changed()} @register.block('modules') class Modules(tables.Table): id_field = 'name' # Module name name = tables.Column(verbose_name=_('Module')) # Module status status = tables.MergeColumn( verbose_name=_('Status'), columns=( ('install', tables.ActionColumn(verbose_name=_('Install'), action='core:install_module', visible=lambda m: not m.installed)), ('enable', tables.ActionColumn(verbose_name=_('Enable'), action='core:enable_module', visible=lambda m: m.installed and not m.enabled)), ('disable', tables.ActionColumn(verbose_name=_('Disable'), action='core:disable_module', visible=lambda m: m.installed and m.enabled)), ) ) def objects(self): return nazs.modules() def get_object(self, name): for module in nazs.modules(): if module.name == name: return module raise KeyError('Module %s not found' % name)
Add notifications count to global envar
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app.jinja_env.globals.update(discourse=self) def comments(self): """Return an HTML snippet used to embed Discourse comments.""" return Markup(""" <div id="discourse-comments"></div> <script type="text/javascript"> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """).format(self.url, request.base_url) def notifications(self): """Return a count of unread notifications for the current user.""" notifications = discourse_client.user_notifications() if not notifications: return 0 return sum([1 for n in notifications['notifications'] if not n['read']])
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app.jinja_env.globals.update(discourse=self) def comments(self): """Return an HTML snippet used to embed Discourse comments.""" return Markup(""" <div id="discourse-comments"></div> <script type="text/javascript"> DiscourseEmbed = {{ discourseUrl: '{0}/', discourseEmbedUrl: '{1}' }}; window.onload = function() {{ let d = document.createElement('script'), head = document.getElementsByTagName('head')[0], body = document.getElementsByTagName('body')[0]; d.type = 'text/javascript'; d.async = true; d.src = '{0}/javascripts/embed.js'; (head || body).appendChild(d); }} </script> """).format(self.url, request.base_url)
Send email to acadoffice when user acknowledge his AWS. Former-commit-id: 3285ac8554522192665d8a9d65ffd3d25240fd35 Former-commit-id: c262a061a641e53d217875a578a08ca0584cfc74
<?php include_once( "header.php" ); include_once( "methods.php" ); include_once( 'tohtml.php' ); include_once( "check_access_permissions.php" ); mustHaveAnyOfTheseRoles( Array( 'USER' ) ); echo userHTML( ); $user = $_SESSION[ 'user' ]; if( $_POST ) { $data = array( 'speaker' => $user ); $data = array_merge( $_POST, $data ); echo( "Sending your acknowledgment to database " ); $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data ); if( $res ) { echo printInfo( "You have successfully acknowledged your AWS schedule. Please mark your calendar as well." ); $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>"; $email .= "<p>" . humanReadableDate( 'now' ) . "</p>"; $subject = loginToText( $user ) . " has acknowledged his/her AWS date"; $to = '[email protected]'; $cc = '[email protected]'; sendPlainTextEmail( $email, $subject, $to, $cc ); goToPage( "user_aws.php", 1 ); exit; } else { echo printWarning( "Failed to update database ..." ); } } echo goBackToPageLink( "user_aws.php", "Go back" ); ?>
<?php include_once( "header.php" ); include_once( "methods.php" ); include_once( 'tohtml.php' ); include_once( "check_access_permissions.php" ); mustHaveAnyOfTheseRoles( Array( 'USER' ) ); echo userHTML( ); $user = $_SESSION[ 'user' ]; if( $_POST ) { $data = array( 'speaker' => $user ); $data = array_merge( $_POST, $data ); echo( "Sending your acknowledgment to database " ); $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data ); if( $res ) { echo printInfo( "You have successfully acknowledged your AWS schedule. Please mark your calendar as well." ); $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>"; $email .= "<p>" . humanReadableDate( 'now' ) . "</p>"; $subject = "$user has acknowledged his/her AWS date"; $to = '[email protected]'; $cc = '[email protected]'; sendPlainTextEmail( $email, $subject, $to, $cc ); goToPage( "user_aws.php", 1 ); exit; } else { echo printWarning( "Failed to update database ..." ); } } echo goBackToPageLink( "user_aws.php", "Go back" ); ?>
Disable animation effects on barogram.
import React, { PropTypes } from 'react'; import Chart from 'chart.js'; class LineChart extends React.Component { constructor(props, context) { super(props, context); } componentDidMount() { const { data } = this.props; this.chart = new Chart(this.chartCanvas, { type: 'line', data: { datasets: [{ data: data, pointRadius: 0, borderColor: '#0000FF', borderWidth: 1, fill: false }] }, options: { scales: { xAxes: [{ type: 'time', time: { displayFormats: { hour: 'HH:mm', minute: 'HH:mm' } }, position: 'bottom' }] }, legend: { display: false }, maintainAspectRatio: false, animation: false } }); } componentDidUpdate() { this.chart.data.datasets[0].data = this.props.data; this.chart.update(); } componentWillUnmount() { this.chart.destroy(); } render() { return ( <div style={{ width: '100%', height: '50vh' }}> <canvas ref={c => { this.chartCanvas = c; }}/> </div> ); } } LineChart.propTypes = { data: PropTypes.array.isRequired }; export default LineChart;
import React, { PropTypes } from 'react'; import Chart from 'chart.js'; class LineChart extends React.Component { constructor(props, context) { super(props, context); } componentDidMount() { const { data } = this.props; this.chart = new Chart(this.chartCanvas, { type: 'line', data: { datasets: [{ data: data, pointRadius: 0, borderColor: '#0000FF', borderWidth: 1, fill: false }] }, options: { scales: { xAxes: [{ type: 'time', time: { displayFormats: { hour: 'HH:mm', minute: 'HH:mm' } }, position: 'bottom' }] }, legend: { display: false }, maintainAspectRatio: false } }); } componentDidUpdate() { this.chart.data.datasets[0].data = this.props.data; this.chart.update(); } componentWillUnmount() { this.chart.destroy(); } render() { return ( <div style={{ width: '100%', height: '50vh' }}> <canvas ref={c => { this.chartCanvas = c; }}/> </div> ); } } LineChart.propTypes = { data: PropTypes.array.isRequired }; export default LineChart;
Change timeout for events reporting
// Requires var _ = require('underscore'); var wireFriendly = require('../utils').wireFriendly; var timestamp = require('../utils').timestamp; function setup(options, imports, register) { // Import var events = imports.events; var workspace = imports.workspace; var hooks = imports.hooks; var logger = imports.logger.namespace("reporting"); var timeout = Number(options.timeout || 180) * 1e3; // 2mn logger.log("events reporting with timeout of", timeout, "ms") // A queue we push all our events to var eventQueue = []; // Send events and empty queue var sendEvents = _.debounce(function sendEvents() { logger.log("report", _.size(eventQueue), "events"); // Hit hook hooks.use("events", eventQueue); // Empty queue eventQueue = []; }, timeout); var queueEvent = function queueEvent(eventData) { eventQueue.push(eventData); }; // Construct events.onAny(function(data) { // Queue new event queueEvent({ // Type of event event: this.event, // Data of event data: wireFriendly(data), // Workspace ID workspaceId: workspace.id, // Timestamp of event timestamp: timestamp() }); // Send events sendEvents(); }); // Register register(null, {}); } // Exports module.exports = setup;
// Requires var _ = require('underscore'); var wireFriendly = require('../utils').wireFriendly; var timestamp = require('../utils').timestamp; function setup(options, imports, register) { // Import var events = imports.events; var workspace = imports.workspace; var hooks = imports.hooks; var logger = imports.logger.namespace("reporting"); var timeout = Number(options.timeout || 6) * 1e3; // 2mn logger.log("events reporting with timeout of", timeout, "ms") // A queue we push all our events to var eventQueue = []; // Send events and empty queue var sendEvents = _.debounce(function sendEvents() { logger.log("report", _.size(eventQueue), "events"); // Hit hook hooks.use("events", eventQueue); // Empty queue eventQueue = []; }, timeout); var queueEvent = function queueEvent(eventData) { eventQueue.push(eventData); }; // Construct events.onAny(function(data) { // Queue new event queueEvent({ // Type of event event: this.event, // Data of event data: wireFriendly(data), // Workspace ID workspaceId: workspace.id, // Timestamp of event timestamp: timestamp() }); // Send events sendEvents(); }); // Register register(null, {}); } // Exports module.exports = setup;
Fix res returned on delegate
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <[email protected]> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class delegate_child_wizard(orm.TransientModel): _inherit = 'delegate.child.wizard' def delegate(self, cr, uid, ids, context=None): child_ids = self._default_child_ids(cr, uid, context) child_obj = self.pool.get('compassion.child') typo3_to_remove_ids = list() for child in child_obj.browse(cr, uid, child_ids, context): if (child.state == 'I'): typo3_to_remove_ids.append(child.id) if typo3_to_remove_ids: res = child_obj.child_remove_from_typo3( cr, uid, typo3_to_remove_ids, context) res = super(delegate_child_wizard, self).delegate( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <[email protected]> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class delegate_child_wizard(orm.TransientModel): _inherit = 'delegate.child.wizard' def delegate(self, cr, uid, ids, context=None): child_ids = self._default_child_ids(cr, uid, context) child_obj = self.pool.get('compassion.child') typo3_to_remove_ids = list() for child in child_obj.browse(cr, uid, child_ids, context): if (child.state == 'I'): typo3_to_remove_ids.append(child.id) if typo3_to_remove_ids: res = child_obj.child_remove_from_typo3( cr, uid, typo3_to_remove_ids, context) res = super(delegate_child_wizard, self).delegate( cr, uid, ids, context) return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
Introduce optional into the configuration util to simplify the code Signed-off-by: l-1sqared <927badf1468b689b17391b1b1cb5895e9b797b96@users.noreply.github.com>
package com.tngtech.jgiven.config; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.tngtech.jgiven.annotation.JGivenConfiguration; import com.tngtech.jgiven.impl.util.ReflectionUtil; import java.util.Optional; import java.util.concurrent.ExecutionException; public class ConfigurationUtil { private static final LoadingCache<Class<?>, AbstractJGivenConfiguration> configurations = CacheBuilder.newBuilder().build( new CacheLoader<Class<?>, AbstractJGivenConfiguration>() { @Override public AbstractJGivenConfiguration load(Class<?> key) { AbstractJGivenConfiguration result = (AbstractJGivenConfiguration) ReflectionUtil.newInstance(key); result.configure(); return result; } }); @SuppressWarnings({"unchecked"}) public static <A extends AbstractJGivenConfiguration> AbstractJGivenConfiguration getConfiguration( Class<?> testClass) { Class<? extends AbstractJGivenConfiguration> configuration = Optional.ofNullable(testClass) .map(content -> content.getAnnotation(JGivenConfiguration.class)) .map(content -> (Class<A>) content.value()) .orElse((Class<A>) DefaultConfiguration.class); try { return configurations.get(configuration); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } }
package com.tngtech.jgiven.config; import java.util.concurrent.ExecutionException; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.tngtech.jgiven.annotation.JGivenConfiguration; import com.tngtech.jgiven.impl.util.ReflectionUtil; public class ConfigurationUtil { private static final LoadingCache<Class<?>, AbstractJGivenConfiguration> configurations = CacheBuilder.newBuilder().build( new CacheLoader<Class<?>, AbstractJGivenConfiguration>() { @Override public AbstractJGivenConfiguration load( Class<?> key ) throws Exception { AbstractJGivenConfiguration result = (AbstractJGivenConfiguration) ReflectionUtil.newInstance( key ); result.configure(); return result; } } ); public static AbstractJGivenConfiguration getConfiguration( Class<? extends Object> testClass ) { JGivenConfiguration annotation = testClass.getAnnotation( JGivenConfiguration.class ); Class<?> configuration; if( annotation == null ) { configuration = DefaultConfiguration.class; } else { configuration = annotation.value(); } try { return configurations.get( configuration ); } catch( ExecutionException e ) { throw Throwables.propagate( e.getCause() ); } } }
Return xls as type for application/vnd.ms-excel.
(function(module) { module.directive("displayFileContents", displayFileContentsDirective); function displayFileContentsDirective() { return { restrict: "E", controller: 'DisplayFileContentsDirectiveController', controllerAs: 'view', bindToController: true, scope: { file: '=file' }, templateUrl: 'application/core/projects/project/files/display-file-contents.html' }; } module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController); DisplayFileContentsDirectiveController.$inject = ["mcfile"]; /* @ngInject */ function DisplayFileContentsDirectiveController(mcfile) { var ctrl = this; ctrl.fileType = determineFileType(ctrl.file.mediatype); ctrl.fileSrc = mcfile.src(ctrl.file.id); ////////////// function determineFileType(mediatype) { if (isImage(mediatype.mime)) { return "image"; } else { switch(mediatype.mime) { case "application/pdf": return "pdf"; case "application/vnd.ms-excel": return "xls"; default: return mediatype.mime; } } } } }(angular.module('materialscommons')));
(function(module) { module.directive("displayFileContents", displayFileContentsDirective); function displayFileContentsDirective() { return { restrict: "E", controller: 'DisplayFileContentsDirectiveController', controllerAs: 'view', bindToController: true, scope: { file: '=file' }, templateUrl: 'application/core/projects/project/files/display-file-contents.html' }; } module.controller("DisplayFileContentsDirectiveController", DisplayFileContentsDirectiveController); DisplayFileContentsDirectiveController.$inject = ["mcfile"]; /* @ngInject */ function DisplayFileContentsDirectiveController(mcfile) { var ctrl = this; ctrl.fileType = determineFileType(ctrl.file.mediatype); ctrl.fileSrc = mcfile.src(ctrl.file.id); ////////////// function determineFileType(mediatype) { if (isImage(mediatype.mime)) { return "image"; } else { switch(mediatype.mime) { case "application/pdf": return "pdf"; case "application/vnd.ms-excel": return "excel"; default: return mediatype.mime; } } } } }(angular.module('materialscommons')));
Create the directory before calling the startprojcet command
import os import logging from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): logging.info("Initializing project structure in %s", directory) os.makedirs(directory) from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
import os from optparse import make_option from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Init the static site project" args = '[directory]' option_list = ( make_option( '--title', '-t', dest='title', default='Default site', help='Site title [Default: "%defaults"]'), make_option( '--domain', '-d', dest='domain', default='example.com', help='Domain name [Default: "%default"]'), make_option( '--languages', '-l', dest='languages', default=['he', 'en'], action='append', help='Supported languages. [Default: "%default"]') ) + BaseCommand.option_list def handle(self, directory, **options): from django.conf.global_settings import LANGUAGES extra = { 'build': 'build', 'default_lang': options['languages'][0], 'languages': [l for l in LANGUAGES if l[0] in options["languages"]], 'extensions': ('py', ), 'files': (), 'template': os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, 'project_template')), } extra.update(options) from django.core.management import call_command call_command('startproject', 'conf', directory, **extra)
Fix for error: Cannot find module '../modules' when --ls specified.
#!/usr/bin/env node var fs = require('fs'); var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version var opt = require('optimist') .usage('jQuery Builder '+ version +'\nUsage: $0') .options('e', { alias: 'exclude', describe: 'Modules to exclude [module,module]', type: 'string' }) .option('m', { alias: 'minify', describe: 'Minify output', type: 'boolean' }) .options('l', { alias: 'ls', describe: 'List available modules', type: 'boolean' }) .options('v', { alias: 'version', describe: 'Version of jQuery to use (1.8.0, 1.8.1, 1.8.2)', type: 'string', default: '1.8.2' }) .options('h', { alias: 'help', descripe: 'Show help info' }); var argv = opt.argv; if (argv.help) { return opt.showHelp(); } if (argv.ls) { var comp = require('../data').modules; console.log('Modules:'); comp.forEach(function(c) { console.log(c); }); return; } var exclude = (argv.exclude) ? argv.exclude.split(',') : undefined; var builder = require('../lib/builder'); builder(exclude, argv.version, argv.minify, function(err, source) { process.stdout.write(source); });
#!/usr/bin/env node var fs = require('fs'); var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version var opt = require('optimist') .usage('jQuery Builder '+ version +'\nUsage: $0') .options('e', { alias: 'exclude', describe: 'Modules to exclude [module,module]', type: 'string' }) .option('m', { alias: 'minify', describe: 'Minify output', type: 'boolean' }) .options('l', { alias: 'ls', describe: 'List available modules', type: 'boolean' }) .options('v', { alias: 'version', describe: 'Version of jQuery to use (1.8.0, 1.8.1, 1.8.2)', type: 'string', default: '1.8.2' }) .options('h', { alias: 'help', descripe: 'Show help info' }); var argv = opt.argv; if (argv.help) { return opt.showHelp(); } if (argv.ls) { var comp = require('../modules'); console.log('Modules:'); comp.forEach(function(c) { console.log(c); }); return; } var exclude = (argv.exclude) ? argv.exclude.split(',') : undefined; var builder = require('../lib/builder'); builder(exclude, argv.version, argv.minify, function(err, source) { process.stdout.write(source); });
Make tests fail if jshint does not pass correctly
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var sourcemaps = require('gulp-sourcemaps'); var coveralls = require('gulp-coveralls'); var del = require('del'); gulp.task('clean', function() { "use strict"; del(['node_modules', 'coverage'], function(err, delfiles) { return err; }); }); gulp.task('dist', function() { "use strict"; return gulp.src(['./index.js', './lib/**/*.js']) .pipe(sourcemaps.init()) .pipe(concat('libtlks.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('dist')) .pipe(rename('libtlks.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')) .pipe(sourcemaps.write()) .pipe(gulp.dest('dist')); }); gulp.task('jshint', function() { "use strict"; return gulp.src(['./test/**/*.js', './lib/**/*.js', 'index.js', 'gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('coveralls', function() { "use strict"; gulp.src('./coverage/**/lcov.info') .pipe(coveralls()); }); gulp.task('default', ['jshint'], function() {});
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var sourcemaps = require('gulp-sourcemaps'); var coveralls = require('gulp-coveralls'); var del = require('del'); gulp.task('clean', function() { "use strict"; del(['node_modules', 'coverage'], function(err, delfiles) { return err; }); }); gulp.task('dist', function() { "use strict"; return gulp.src(['./index.js', './lib/**/*.js']) .pipe(sourcemaps.init()) .pipe(concat('libtlks.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('dist')) .pipe(rename('libtlks.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')) .pipe(sourcemaps.write()) .pipe(gulp.dest('dist')); }); gulp.task('jshint', function() { "use strict"; return gulp.src(['./test/**/*.js', './lib/**/*.js', 'index.js', 'gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('coveralls', function() { "use strict"; gulp.src('./coverage/**/lcov.info') .pipe(coveralls()); }); gulp.task('default', ['jshint'], function() {});