commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
c0da9801f726ab3ac5c360f77598f1d14c615c2e
make sure windrose_utils._make_plot gets exercised!
pyiem/tests/test_windrose_utils.py
pyiem/tests/test_windrose_utils.py
import unittest import datetime import psycopg2 from pyiem.windrose_utils import windrose, _get_timeinfo class Test(unittest.TestCase): def test_timeinfo(self): """Exercise the _get_timeinfo method""" res = _get_timeinfo(range(1, 10), 'hour', 24) self.assertEquals(res['labeltext'], '(1, 2, 3, 4, 5, 6, 7, 8, 9)') res = _get_timeinfo([1], 'month', 1) self.assertEquals(res['sqltext'], ' and extract(month from valid) = 1 ') def test_windrose(self): """Exercise the windrose code""" pgconn = psycopg2.connect(database='asos', host="iemdb") cursor = pgconn.cursor() v = datetime.datetime(2015, 1, 1, 6) for s in range(100): v += datetime.timedelta(hours=1) cursor.execute("""INSERT into t2015(station, valid, sknt, drct) VALUES (%s, %s, %s, %s)""", ('AMW2', v, s, s)) fig = windrose('AMW2', cursor=cursor, sname='Ames') self.assertTrue(fig is not None) fig = windrose('AMW2', cursor=cursor, sts=datetime.datetime(2001, 1, 1), ets=datetime.datetime(2016, 1, 1)) # fig.savefig('/tmp/test_plot_windrose.png') self.assertTrue(fig is not None) res = windrose('AMW2', cursor=cursor, sts=datetime.datetime(2015, 1, 1), ets=datetime.datetime(2015, 10, 2), justdata=True) assert isinstance(res, str)
import unittest import datetime import psycopg2 from pyiem.windrose_utils import windrose, _get_timeinfo class Test(unittest.TestCase): def test_timeinfo(self): """Exercise the _get_timeinfo method""" res = _get_timeinfo(range(1, 10), 'hour', 24) self.assertEquals(res['labeltext'], '(1, 2, 3, 4, 5, 6, 7, 8, 9)') res = _get_timeinfo([1], 'month', 1) self.assertEquals(res['sqltext'], ' and extract(month from valid) = 1 ') def test_windrose(self): """Exercise the windrose code""" pgconn = psycopg2.connect(database='asos', host="iemdb") cursor = pgconn.cursor() v = datetime.datetime(2015, 1, 1, 6) for s in range(100): v += datetime.timedelta(hours=1) cursor.execute("""INSERT into t2015(station, valid, sknt, drct) VALUES (%s, %s, %s, %s)""", ('AMW2', v, s, s)) # plot.windrose('AMW2', fp='/tmp/test_plot_windrose.png', # cursor=cursor) fig = windrose('AMW2', cursor=cursor, justdata=True) self.assertTrue(fig is not None) fig = windrose('AMW2', cursor=cursor, sts=datetime.datetime(2001, 1, 1), ets=datetime.datetime(2001, 1, 2)) self.assertTrue(fig is not None) res = windrose('AMW2', cursor=cursor, sts=datetime.datetime(2015, 1, 1), ets=datetime.datetime(2015, 10, 2), justdata=True) assert isinstance(res, str)
Python
0
d32d57fc07b595c4dc0a24a04ac4589ad5d16918
Make modules uninstallable
hotel/__openerp__.py
hotel/__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name" : "Hotel Management Base", "version" : "1.0", "author" : "Tiny,Odoo Community Association (OCA)", "category" : "Generic Modules/Hotel Management", "description": """ Module for Hotel/Resort/Rooms/Property management. You can manage: * Configure Property * Hotel Configuration * Check In, Check out * Manage Folio * Payment Different reports are also provided, mainly for hotel statistics. """, "depends" : ["sale"], "init_xml" : [], "demo_xml" : [ ], "update_xml" : [ "hotel_view.xml", "hotel_data.xml", "hotel_folio_workflow.xml", "report/hotel_report.xml", "wizard/hotel_wizard.xml", "security/hotel_security.xml", "security/ir.model.access.csv", ], "active": False, 'installable': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name" : "Hotel Management Base", "version" : "1.0", "author" : "Tiny,Odoo Community Association (OCA)", "category" : "Generic Modules/Hotel Management", "description": """ Module for Hotel/Resort/Rooms/Property management. You can manage: * Configure Property * Hotel Configuration * Check In, Check out * Manage Folio * Payment Different reports are also provided, mainly for hotel statistics. """, "depends" : ["sale"], "init_xml" : [], "demo_xml" : [ ], "update_xml" : [ "hotel_view.xml", "hotel_data.xml", "hotel_folio_workflow.xml", "report/hotel_report.xml", "wizard/hotel_wizard.xml", "security/hotel_security.xml", "security/ir.model.access.csv", ], "active": False, 'installable': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Python
0
eca18d440d37e3caebe049617910420e6d37d507
remove execute bit from compare_ir python script
src/compiler/glsl/tests/compare_ir.py
src/compiler/glsl/tests/compare_ir.py
#!/usr/bin/env python # coding=utf-8 # # Copyright © 2011 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # Compare two files containing IR code. Ignore formatting differences # and declaration order. import os import os.path import subprocess import sys import tempfile from sexps import * if len(sys.argv) != 3: print 'Usage: python2 ./compare_ir.py <file1> <file2>' exit(1) with open(sys.argv[1]) as f: ir1 = sort_decls(parse_sexp(f.read())) with open(sys.argv[2]) as f: ir2 = sort_decls(parse_sexp(f.read())) if ir1 == ir2: exit(0) else: file1, path1 = tempfile.mkstemp(os.path.basename(sys.argv[1])) file2, path2 = tempfile.mkstemp(os.path.basename(sys.argv[2])) try: os.write(file1, '{0}\n'.format(sexp_to_string(ir1))) os.close(file1) os.write(file2, '{0}\n'.format(sexp_to_string(ir2))) os.close(file2) subprocess.call(['diff', '-u', path1, path2]) finally: os.remove(path1) os.remove(path2) exit(1)
#!/usr/bin/env python # coding=utf-8 # # Copyright © 2011 Intel Corporation # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # Compare two files containing IR code. Ignore formatting differences # and declaration order. import os import os.path import subprocess import sys import tempfile from sexps import * if len(sys.argv) != 3: print 'Usage: python2 ./compare_ir.py <file1> <file2>' exit(1) with open(sys.argv[1]) as f: ir1 = sort_decls(parse_sexp(f.read())) with open(sys.argv[2]) as f: ir2 = sort_decls(parse_sexp(f.read())) if ir1 == ir2: exit(0) else: file1, path1 = tempfile.mkstemp(os.path.basename(sys.argv[1])) file2, path2 = tempfile.mkstemp(os.path.basename(sys.argv[2])) try: os.write(file1, '{0}\n'.format(sexp_to_string(ir1))) os.close(file1) os.write(file2, '{0}\n'.format(sexp_to_string(ir2))) os.close(file2) subprocess.call(['diff', '-u', path1, path2]) finally: os.remove(path1) os.remove(path2) exit(1)
Python
0
39d89982a2a2bba810e51614158bf474cba500dc
Add more ComputerPlayer names
computer_player.py
computer_player.py
import random import sys import time from player import Player from solving_algorithm import generate_solutions class ComputerPlayer(Player): def __init__(self): super(ComputerPlayer, self).__init__() self.PAUSE = 0.1 self.names = ['Chell', 'GLaDOS', 'Curiosity Core', 'Turret', 'Companion Cube', 'Wheatley', 'Cave Johnson', 'Caroline', 'Cake'] self.solutions = [] def __type(self, message): sys.stdout.write(' ') sys.stdout.flush() time.sleep(self.PAUSE * 5) for character in message: sys.stdout.write(character) sys.stdout.flush() time.sleep(self.PAUSE) time.sleep(self.PAUSE * 5) print def remember_rules(self, pattern_length, pattern_colours): self.pattern_length = pattern_length self.pattern_colours = pattern_colours def get_ready(self): self.colours = [] self.colours_tried = 0 self.solving_phase = 1 def ask_for_name(self, message=''): self.name = random.choice(self.names) if message: print message.rstrip(), self.__type(self.name) def choose_secret_pattern(self, message=''): self.secret_pattern = [] for colour in range(self.pattern_length): self.secret_pattern.append(random.choice(self.pattern_colours)) if message: print message.rstrip(), self.__type("?" * self.pattern_length) def make_guess(self, message=''): self.guess = [] if self.solving_phase == 1: colour = list(self.pattern_colours).pop(self.colours_tried) for peg in range(self.pattern_length): self.guess.append(colour) elif self.solving_phase == 2: for colour in self.solutions: self.guess.append(colour) elif self.solving_phase == 3: solution = self.solutions.pop() for colour in solution: self.guess.append(colour) if message: print message.rstrip(), self.__type(''.join(self.guess)) def analyse_feedback(self, feedback): if self.solving_phase == 1: colour = self.guess[0] for key in feedback: self.colours.append(colour) self.colours_tried += 1 if self.colours_tried == len(self.pattern_colours) - 1: colour = list(self.pattern_colours).pop(self.colours_tried) for colour in range(self.pattern_length - len(self.colours)): self.colours.append(colour) self.colours_tried += 1 if len(self.colours) == self.pattern_length: self.solutions = self.colours self.solving_phase = 2 elif self.solving_phase == 2: self.solutions = generate_solutions(self.guess, feedback) self.solving_phase = 3 elif self.solving_phase == 3: new_solutions = generate_solutions(self.guess, feedback) solutions = [] for solution in self.solutions: if solution in new_solutions: solutions.append(solution) self.solutions = solutions
import random import sys import time from player import Player from solving_algorithm import generate_solutions class ComputerPlayer(Player): def __init__(self): super(ComputerPlayer, self).__init__() self.PAUSE = 0.1 self.names = ['Chell', 'GLaDOS', 'Companion Cube', 'Curiosity Core', 'Wheatley', 'Caroline'] self.solutions = [] def __type(self, message): sys.stdout.write(' ') sys.stdout.flush() time.sleep(self.PAUSE * 5) for character in message: sys.stdout.write(character) sys.stdout.flush() time.sleep(self.PAUSE) time.sleep(self.PAUSE * 5) print def remember_rules(self, pattern_length, pattern_colours): self.pattern_length = pattern_length self.pattern_colours = pattern_colours def get_ready(self): self.colours = [] self.colours_tried = 0 self.solving_phase = 1 def ask_for_name(self, message=''): self.name = random.choice(self.names) if message: print message.rstrip(), self.__type(self.name) def choose_secret_pattern(self, message=''): self.secret_pattern = [] for colour in range(self.pattern_length): self.secret_pattern.append(random.choice(self.pattern_colours)) if message: print message.rstrip(), self.__type("?" * self.pattern_length) def make_guess(self, message=''): self.guess = [] if self.solving_phase == 1: colour = list(self.pattern_colours).pop(self.colours_tried) for peg in range(self.pattern_length): self.guess.append(colour) elif self.solving_phase == 2: for colour in self.solutions: self.guess.append(colour) elif self.solving_phase == 3: solution = self.solutions.pop() for colour in solution: self.guess.append(colour) if message: print message.rstrip(), self.__type(''.join(self.guess)) def analyse_feedback(self, feedback): if self.solving_phase == 1: colour = self.guess[0] for key in feedback: self.colours.append(colour) self.colours_tried += 1 if self.colours_tried == len(self.pattern_colours) - 1: colour = list(self.pattern_colours).pop(self.colours_tried) for colour in range(self.pattern_length - len(self.colours)): self.colours.append(colour) self.colours_tried += 1 if len(self.colours) == self.pattern_length: self.solutions = self.colours self.solving_phase = 2 elif self.solving_phase == 2: self.solutions = generate_solutions(self.guess, feedback) self.solving_phase = 3 elif self.solving_phase == 3: new_solutions = generate_solutions(self.guess, feedback) solutions = [] for solution in self.solutions: if solution in new_solutions: solutions.append(solution) self.solutions = solutions
Python
0
068e12ebb0fc36fc3bfa397a58c54aa92e361f9a
Clean up unit test in test_notifier
st2actions/tests/unit/test_notifier.py
st2actions/tests/unit/test_notifier.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import unittest2 import st2tests.config as tests_config tests_config.parse_args() from st2actions.notifier import Notifier from st2common.constants.triggers import INTERNAL_TRIGGER_TYPES from st2common.models.db.action import LiveActionDB, NotificationSchema from st2common.models.db.action import NotificationSubSchema from st2common.models.system.common import ResourceReference ACTION_TRIGGER_TYPE = INTERNAL_TRIGGER_TYPES['action'][0] NOTIFY_TRIGGER_TYPE = INTERNAL_TRIGGER_TYPES['action'][1] class NotifierTestCase(unittest2.TestCase): class MockDispatcher(object): def __init__(self, tester): self.tester = tester self.notify_trigger = ResourceReference.to_string_reference( pack=NOTIFY_TRIGGER_TYPE['pack'], name=NOTIFY_TRIGGER_TYPE['name']) self.action_trigger = ResourceReference.to_string_reference( pack=ACTION_TRIGGER_TYPE['pack'], name=ACTION_TRIGGER_TYPE['name']) def dispatch(self, *args, **kwargs): try: self.tester.assertEqual(len(args), 1) self.tester.assertTrue('payload' in kwargs) payload = kwargs['payload'] if args[0] == self.notify_trigger: self.tester.assertEqual(payload['status'], 'succeeded') self.tester.assertTrue('execution_id' in payload) self.tester.assertTrue('start_timestamp' in payload) self.tester.assertTrue('end_timestamp' in payload) self.tester.assertEqual('core.local', payload['action_ref']) self.tester.assertEqual('Action succeeded.', payload['message']) self.tester.assertTrue('data' in payload) if args[0] == self.action_trigger: self.tester.assertEqual(payload['status'], 'succeeded') self.tester.assertTrue('execution_id' in payload) self.tester.assertTrue('start_timestamp' in payload) self.tester.assertEqual('core.local', payload['action_name']) self.tester.assertTrue('result' in payload) self.tester.assertTrue('parameters' in payload) except Exception: self.tester.fail('Test failed') def test_notify_triggers(self): liveaction = LiveActionDB(action='core.local') liveaction.description = '' liveaction.status = 'succeeded' liveaction.parameters = {} on_success = NotificationSubSchema(message='Action succeeded.') on_failure = NotificationSubSchema(message='Action failed.') liveaction.notify = NotificationSchema(on_success=on_success, on_failure=on_failure) liveaction.start_timestamp = datetime.datetime.utcnow() dispatcher = NotifierTestCase.MockDispatcher(self) notifier = Notifier(connection=None, queues=[], trigger_dispatcher=dispatcher) notifier.process(liveaction)
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import unittest2 import st2tests.config as tests_config tests_config.parse_args() from st2actions.notifier import Notifier from st2common.constants.triggers import INTERNAL_TRIGGER_TYPES from st2common.models.db.action import LiveActionDB, NotificationSchema from st2common.models.db.action import NotificationSubSchema from st2common.models.system.common import ResourceReference ACTION_TRIGGER_TYPE = INTERNAL_TRIGGER_TYPES['action'][0] NOTIFY_TRIGGER_TYPE = INTERNAL_TRIGGER_TYPES['action'][1] class NotifierTestCase(unittest2.TestCase): class MockDispatcher(object): def __init__(self, tester): self.tester = tester self.notify_trigger = ResourceReference.to_string_reference( pack=NOTIFY_TRIGGER_TYPE['pack'], name=NOTIFY_TRIGGER_TYPE['name']) self.action_trigger = ResourceReference.to_string_reference( pack=ACTION_TRIGGER_TYPE['pack'], name=ACTION_TRIGGER_TYPE['name']) def dispatch(self, *args, **kwargs): try: self.tester.assertEqual(len(args), 1) self.tester.assertTrue('payload' in kwargs) payload = kwargs['payload'] if args[0] == self.notify_trigger: self.tester.assertEqual(payload['status'], 'succeeded') self.tester.assertTrue('execution_id' in payload) self.tester.assertTrue('start_timestamp' in payload) self.tester.assertTrue('end_timestamp' in payload) self.tester.assertEqual('core.local', payload['action_ref']) self.tester.assertEqual('Action succeeded.', payload['message']) self.tester.assertTrue('data' in payload) if args[0] == self.action_trigger: self.tester.assertEqual(payload['status'], 'succeeded') self.tester.assertTrue('execution_id' in payload) self.tester.assertTrue('start_timestamp' in payload) self.tester.assertEqual('core.local', payload['action_name']) self.tester.assertTrue('result' in payload) self.tester.assertTrue('parameters' in payload) except Exception: self.tester.fail('Test failed') def test_notify_triggers(self): liveaction = LiveActionDB(action='core.local') liveaction.description = '' liveaction.status = 'succeeded' liveaction.parameters = {} on_success = NotificationSubSchema(message='Action succeeded.') on_failure = NotificationSubSchema(message='Action failed.') liveaction.notify = NotificationSchema(on_success=on_success, on_failure=on_failure) liveaction.start_timestamp = datetime.datetime.utcnow() dispatcher = NotifierTestCase.MockDispatcher(self) notifier = Notifier(None, [], trigger_dispatcher=dispatcher) notifier.process(liveaction)
Python
0
cf35695481b703e49fbc00e286ef6380a8aec394
Remove invalid test
corehq/apps/notifications/tests/test_views.py
corehq/apps/notifications/tests/test_views.py
from unittest.mock import patch from corehq.apps.accounting.models import Subscription from corehq.apps.groups.models import Group from ..views import NotificationsServiceRMIView def test_should_hide_feature_notifs_for_pro_with_groups(): with case_sharing_groups_patch(['agroupid']): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for pro domain with groups" def test_should_hide_feature_notifs_for_pro_without_groups(): with case_sharing_groups_patch([]), active_service_type_patch("not_IMPLEMENTATION_or_SANDBOX"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert not hide, "notifications should not be hidden for pro domain without groups" def test_should_hide_feature_notifs_for_implementation_subscription(): with case_sharing_groups_patch([]), active_service_type_patch("IMPLEMENTATION"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for IMPLEMENTATION subscription" def test_should_hide_feature_notifs_for_sandbox_subscription(): with case_sharing_groups_patch([]), active_service_type_patch("SANDBOX"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for SANDBOX subscription" def test_should_hide_feature_notifs_bug(): with case_sharing_groups_patch([]), active_service_type_patch(): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", None) assert not hide, "notifications should not be hidden for null subscription" def active_service_type_patch(service_type=None): def getter(domain): return sub sub = None if service_type is None else Subscription(service_type=service_type) return patch.object(Subscription, "get_active_subscription_by_domain", getter) def case_sharing_groups_patch(groups): # patch because quickcache makes this hard to test def getter(domain, wrap): assert not wrap, "expected wrap to be false" return groups return patch.object(Group, "get_case_sharing_groups", getter)
from unittest.mock import patch from corehq.apps.accounting.models import Subscription from corehq.apps.groups.models import Group from ..views import NotificationsServiceRMIView def test_should_hide_feature_notifs_for_pro_with_groups(): with case_sharing_groups_patch(['agroupid']): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for pro domain with groups" def test_should_hide_feature_notifs_for_pro_without_groups(): with case_sharing_groups_patch([]), active_service_type_patch("not_IMPLEMENTATION_or_SANDBOX"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert not hide, "notifications should not be hidden for pro domain without groups" def test_should_hide_feature_notifs_for_non_pro_with_groups(): with case_sharing_groups_patch(['agroupid']), active_service_type_patch("not_IMPLEMENTATION_or_SANDBOX"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", None) assert not hide, "notifications should not be hidden for pro domain without groups" def test_should_hide_feature_notifs_for_implementation_subscription(): with case_sharing_groups_patch([]), active_service_type_patch("IMPLEMENTATION"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for IMPLEMENTATION subscription" def test_should_hide_feature_notifs_for_sandbox_subscription(): with case_sharing_groups_patch([]), active_service_type_patch("SANDBOX"): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", "pro") assert hide, "notifications should be hidden for SANDBOX subscription" def test_should_hide_feature_notifs_bug(): with case_sharing_groups_patch([]), active_service_type_patch(): hide = NotificationsServiceRMIView._should_hide_feature_notifs("test", None) assert not hide, "notifications should not be hidden for null subscription" def active_service_type_patch(service_type=None): def getter(domain): return sub sub = None if service_type is None else Subscription(service_type=service_type) return patch.object(Subscription, "get_active_subscription_by_domain", getter) def case_sharing_groups_patch(groups): # patch because quickcache makes this hard to test def getter(domain, wrap): assert not wrap, "expected wrap to be false" return groups return patch.object(Group, "get_case_sharing_groups", getter)
Python
0
9df00bbfa829006396c2a6718e4540410b27c4c6
Clear the job queue upon kolibri initialization.
kolibri/tasks/apps.py
kolibri/tasks/apps.py
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): from kolibri.tasks.api import client client.clear(force=True)
from __future__ import absolute_import, print_function, unicode_literals from django.apps import AppConfig class KolibriTasksConfig(AppConfig): name = 'kolibri.tasks' label = 'kolibritasks' verbose_name = 'Kolibri Tasks' def ready(self): pass
Python
0
6a6cb75ad2c29435d74768aa88c5d925570a6ad0
Add some meta
flask_environments.py
flask_environments.py
# -*- coding: utf-8 -*- """ flask_environments ~~~~~~~~~~~~~~~~~~ Environment tools and configuration for Flask applications :copyright: (c) 2012 by Matt Wright. :license: MIT, see LICENSE for more details. """ import os import yaml from flask import current_app class Environments(object): def __init__(self, app=None, var_name=None, default_env=None): self.app = app self.var_name = var_name or 'FLASK_ENV' self.default_env = default_env or 'DEVELOPMENT' self.env = os.environ.get(self.var_name, self.default_env) if app is not None: self.init_app(app) def init_app(self, app): app.config['ENVIORNMENT'] = self.env if app.extensions is None: app.extensions = {} app.extensions['environments'] = self def get_app(self, reference_app=None): if reference_app is not None: return reference_app if self.app is not None: return self.app return current_app def from_object(self, config_obj): app = self.get_app() for name in self._possible_names(): try: obj = '%s.%s' % (config_obj, name) app.config.from_object(obj) return except: pass app.config.from_object(config_obj) def from_yaml(self, path): with open(path) as f: c = yaml.load(f) for name in self._possible_names(): try: c = c[name] except: pass app = self.get_app() for key in c.iterkeys(): if key.isupper(): app.config[key] = c[key] def _possible_names(self): return (self.env, self.env.capitalize(), self.env.lower())
import os import yaml from flask import current_app class Environments(object): def __init__(self, app=None, var_name=None, default_env=None): self.app = app self.var_name = var_name or 'FLASK_ENV' self.default_env = default_env or 'DEVELOPMENT' self.env = os.environ.get(self.var_name, self.default_env) if app is not None: self.init_app(app) def init_app(self, app): app.config['ENVIORNMENT'] = self.env if app.extensions is None: app.extensions = {} app.extensions['environments'] = self def get_app(self, reference_app=None): if reference_app is not None: return reference_app if self.app is not None: return self.app return current_app def from_object(self, config_obj): app = self.get_app() for name in self._possible_names(): try: obj = '%s.%s' % (config_obj, name) app.config.from_object(obj) return except: pass app.config.from_object(config_obj) def from_yaml(self, path): with open(path) as f: c = yaml.load(f) for name in self._possible_names(): try: c = c[name] except: pass app = self.get_app() for key in c.iterkeys(): if key.isupper(): app.config[key] = c[key] def _possible_names(self): return (self.env, self.env.capitalize(), self.env.lower())
Python
0.000134
cff83c316663975af2e838cbd8c365a68079c369
In plugin child_plugin_instances may be None
shop/cascade/extensions.py
shop/cascade/extensions.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from cms.plugin_pool import plugin_pool from cmsplugin_cascade.plugin_base import TransparentContainer from .plugin_base import ShopPluginBase class ShopExtendableMixin(object): """ Add this mixin class to the list of ``model_mixins``, in the plugin class wishing to use extensions. """ @property def left_extension(self): if self.child_plugin_instances is None: return result = [cp for cp in self.child_plugin_instances if cp.plugin_type == 'ShopLeftExtension'] if result: return result[0] @property def right_extension(self): if self.child_plugin_instances is None: return result = [cp for cp in self.child_plugin_instances if cp.plugin_type == 'ShopRightExtension'] if result: return result[0] class LeftRightExtensionMixin(object): """ Plugin classes wishing to use extensions shall inherit from this class. """ @classmethod def get_child_classes(cls, slot, page, instance=None): child_classes = ['ShopLeftExtension', 'ShopRightExtension', None] # allow only one left and one right extension for child in instance.get_children(): child_classes.remove(child.plugin_type) return child_classes class ShopLeftExtension(TransparentContainer, ShopPluginBase): name = _("Left Extension") require_parent = True parent_classes = ('ShopCartPlugin', 'ShopOrderViewsPlugin') allow_children = True render_template = 'cascade/generic/naked.html' plugin_pool.register_plugin(ShopLeftExtension) class ShopRightExtension(TransparentContainer, ShopPluginBase): name = _("Right Extension") require_parent = True parent_classes = ('ShopCartPlugin', 'ShopOrderViewsPlugin') allow_children = True render_template = 'cascade/generic/naked.html' plugin_pool.register_plugin(ShopRightExtension)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from cms.plugin_pool import plugin_pool from cmsplugin_cascade.plugin_base import TransparentContainer from .plugin_base import ShopPluginBase class ShopExtendableMixin(object): """ Add this mixin class to the list of ``model_mixins``, in the plugin class wishing to use extensions. """ @property def left_extension(self): result = [cp for cp in self.child_plugin_instances if cp.plugin_type == 'ShopLeftExtension'] if result: return result[0] @property def right_extension(self): result = [cp for cp in self.child_plugin_instances if cp.plugin_type == 'ShopRightExtension'] if result: return result[0] class LeftRightExtensionMixin(object): """ Plugin classes wishing to use extensions shall inherit from this class. """ @classmethod def get_child_classes(cls, slot, page, instance=None): child_classes = ['ShopLeftExtension', 'ShopRightExtension', None] # allow only one left and one right extension for child in instance.get_children(): child_classes.remove(child.plugin_type) return child_classes class ShopLeftExtension(TransparentContainer, ShopPluginBase): name = _("Left Extension") require_parent = True parent_classes = ('ShopCartPlugin', 'ShopOrderViewsPlugin') allow_children = True render_template = 'cascade/generic/naked.html' plugin_pool.register_plugin(ShopLeftExtension) class ShopRightExtension(TransparentContainer, ShopPluginBase): name = _("Right Extension") require_parent = True parent_classes = ('ShopCartPlugin', 'ShopOrderViewsPlugin') allow_children = True render_template = 'cascade/generic/naked.html' plugin_pool.register_plugin(ShopRightExtension)
Python
0.999998
77e5dcc8592686202045a79cea293af602ed5d49
delete is trickle-down, so I think this is more precise
corehq/apps/reminders/tests/test_recipient.py
corehq/apps/reminders/tests/test_recipient.py
from django.test import TestCase from corehq.apps.domain.models import Domain from corehq.apps.locations.models import SQLLocation, LocationType from corehq.apps.reminders.models import CaseReminder, CaseReminderHandler from corehq.apps.users.models import CommCareUser from corehq.form_processor.tests.utils import run_with_all_backends from corehq.util.test_utils import create_test_case from mock import patch class ReminderRecipientTest(TestCase): domain = 'reminder-recipient-test' def setUp(self): self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.parent_location_type = LocationType.objects.create( domain=self.domain, name='parent type', code='parent' ) self.child_location_type = LocationType.objects.create( domain=self.domain, name='child type', code='child', parent_type=self.parent_location_type ) self.user = CommCareUser.create(self.domain, 'test', 'test') def tearDown(self): self.parent_location_type.delete() self.child_location_type.delete() self.user.delete() self.domain_obj.delete() @run_with_all_backends def test_recipient_case_owner_location_parent(self): parent_location = SQLLocation.objects.create( domain=self.domain, name='parent test', site_code='parent', location_type=self.parent_location_type ) child_location = SQLLocation.objects.create( domain=self.domain, name='child test', site_code='child', location_type=self.child_location_type, parent=parent_location ) self.user.set_location(child_location) with create_test_case(self.domain, 'test-case', 'test-name', owner_id=self.user.get_id) as case: self.assertEqual(case.owner_id, self.user.get_id) handler = CaseReminderHandler(domain=self.domain, recipient='CASE_OWNER_LOCATION_PARENT') reminder = CaseReminder(domain=self.domain, case_id=case.case_id) # Test the recipient is returned correctly with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertEqual(reminder.recipient, [parent_location]) # Remove parent location child_location.parent = None child_location.save() parent_location.delete() with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient) # Remove child location self.user.unset_location() child_location.delete() with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient) # Remove case reminder.case_id = None with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient)
from django.test import TestCase from corehq.apps.domain.models import Domain from corehq.apps.locations.models import SQLLocation, LocationType from corehq.apps.reminders.models import CaseReminder, CaseReminderHandler from corehq.apps.users.models import CommCareUser from corehq.form_processor.tests.utils import run_with_all_backends from corehq.util.test_utils import create_test_case from mock import patch class ReminderRecipientTest(TestCase): domain = 'reminder-recipient-test' def setUp(self): self.domain_obj = Domain(name=self.domain) self.domain_obj.save() self.parent_location_type = LocationType.objects.create( domain=self.domain, name='parent type', code='parent' ) self.child_location_type = LocationType.objects.create( domain=self.domain, name='child type', code='child', parent_type=self.parent_location_type ) self.user = CommCareUser.create(self.domain, 'test', 'test') def tearDown(self): self.parent_location_type.delete() self.child_location_type.delete() self.user.delete() self.domain_obj.delete() @run_with_all_backends def test_recipient_case_owner_location_parent(self): parent_location = SQLLocation.objects.create( domain=self.domain, name='parent test', site_code='parent', location_type=self.parent_location_type ) child_location = SQLLocation.objects.create( domain=self.domain, name='child test', site_code='child', location_type=self.child_location_type, parent=parent_location ) self.user.set_location(child_location) with create_test_case(self.domain, 'test-case', 'test-name', owner_id=self.user.get_id) as case: self.assertEqual(case.owner_id, self.user.get_id) handler = CaseReminderHandler(domain=self.domain, recipient='CASE_OWNER_LOCATION_PARENT') reminder = CaseReminder(domain=self.domain, case_id=case.case_id) # Test the recipient is returned correctly with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertEqual(reminder.recipient, [parent_location]) # Remove parent location parent_location.delete() child_location.parent = None child_location.save() with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient) # Remove child location self.user = CommCareUser.get(self.user._id) self.user.unset_location() child_location.delete() with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient) # Remove case reminder.case_id = None with patch('corehq.apps.reminders.models.CaseReminder.handler', new=handler): self.assertIsNone(reminder.recipient)
Python
0.000012
bb5cbae79ef8efb8d0b7dd3ee95e76955317d3d7
Fix for broken container security test
tests/integration/api/test_sc_test_jobs.py
tests/integration/api/test_sc_test_jobs.py
from tests.base import BaseTest from tenable_io.api.models import ScTestJob class TestScTestJobsApi(BaseTest): def test_status(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' test_job = client.sc_test_jobs_api.status(jobs[0].job_id) assert isinstance(test_job, ScTestJob), u'The method returns type.' def test_by_image(self, client, image): job = client.sc_test_jobs_api.by_image(image['id']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_by_image_digest(self, client, image): job = client.sc_test_jobs_api.by_image_digest(image['digest']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_list(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
from tests.base import BaseTest from tenable_io.api.models import ScTestJob class TestScTestJobsApi(BaseTest): def test_status(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' test_job = client.sc_test_jobs_api.status(jobs[0].job_id) assert isinstance(test_job, ScTestJob), u'The method returns type.' def test_by_image(self, client, image): job = client.sc_test_jobs_api.by_image(image['id']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_by_image_digest(self, client, image): job = client.sc_test_jobs_api.by_image(image['digest']) assert isinstance(job, ScTestJob), u'The method returns type.' def test_list(self, client, image): jobs = client.sc_test_jobs_api.list() assert len(jobs) > 0, u'At least one job exists.' assert isinstance(jobs[0], ScTestJob), u'The method returns job list.'
Python
0
db6e23671a82a76afc13b4a69422a6b0d3c381df
Rearrange tests
h5py/tests/high/test_hlobject.py
h5py/tests/high/test_hlobject.py
from tempfile import mktemp from h5py import tests import h5py class Base(tests.HTest): def setUp(self): self.name = mktemp() self.f = h5py.File(self.name, 'w') def tearDown(self): import os try: if self.f: self.f.close() finally: if self.name and os.path.exists(self.name): os.unlink(self.name) class TestComparison(Base): def test_eq(self): """ (HLObject) __eq__ and __ne__ are opposite (files and groups) """ g1 = self.f.create_group('a') g2 = self.f['a'] g3 = self.f.create_group('b') f1 = self.f f2 = g1.file self.assert_(g1 == g2) self.assert_(not g1 != g2) self.assert_(g1 != g3) self.assert_(not g1 == g3) self.assert_(f1 == f2) self.assert_(not f1 != f2) def test_grp(self): """ (HLObject) File objects don't compare equal to root group """ g = self.f['/'] self.assert_(not g == self.f) self.assert_(g != self.f) class TestProps(Base): def test_file2(self): """ (HLObject) .file """ g = self.f.create_group('foo') g2 = self.f.create_group('foo/bar') self.assertEqual(self.f, self.f.file) self.assertEqual(self.f, g.file) self.assertEqual(self.f, g2.file) def test_parent(self): """ (HLObject) .parent """ self.assertEqual(self.f.parent, self.f['/']) g = self.f.create_group('a') g2 = self.f.create_group('a/b') self.assertEqual(g2.parent, g) self.assertEqual(g.parent, self.f['/']) class TestProps(Base): @tests.require(api=18) def test_lcpl(self): """ (HLObject) lcpl """ lcpl = self.f._lcpl self.assertIsInstance(lcpl, h5py.h5p.PropLCID) @tests.require(api=18) def test_lapl(self): """ (HLObject) lapl """ lapl = self.f._lapl self.assertIsInstance(lapl, h5py.h5p.PropLAID)
from tempfile import mktemp from h5py import tests import h5py class Base(tests.HTest): def setUp(self): self.name = mktemp() self.f = h5py.File(self.name, 'w') def tearDown(self): import os try: if self.f: self.f.close() finally: if self.name and os.path.exists(self.name): os.unlink(self.name) class TestComparison(Base): def test_eq(self): """ (HLObject) __eq__ and __ne__ are opposite (files and groups) """ g1 = self.f.create_group('a') g2 = self.f['a'] g3 = self.f.create_group('b') f1 = self.f f2 = g1.file self.assert_(g1 == g2) self.assert_(not g1 != g2) self.assert_(g1 != g3) self.assert_(not g1 == g3) self.assert_(f1 == f2) self.assert_(not f1 != f2) def test_grp(self): """ (HLObject) File objects don't compare equal to root group """ g = self.f['/'] self.assert_(not g == self.f) self.assert_(g != self.f) class TestPropFile(Base): def test_file2(self): """ (HLObject) .file property on subclasses """ g = self.f.create_group('foo') g2 = self.f.create_group('foo/bar') self.assertEqual(self.f, self.f.file) self.assertEqual(self.f, g.file) self.assertEqual(self.f, g2.file) class TestProps(Base): @tests.require(api=18) def test_lcpl(self): """ (HLObject) lcpl """ lcpl = self.f._lcpl self.assertIsInstance(lcpl, h5py.h5p.PropLCID) @tests.require(api=18) def test_lapl(self): """ (HLObject) lapl """ lapl = self.f._lapl self.assertIsInstance(lapl, h5py.h5p.PropLAID) class TestParent(Base): def test_parent(self): """ (HLObject) .parent """ self.assertEqual(self.f.parent, self.f['/']) g = self.f.create_group('a') g2 = self.f.create_group('a/b') self.assertEqual(g2.parent, g) self.assertEqual(g.parent, self.f['/'])
Python
0.000015
6594bb843998ee22b0a12036a0e16c1fd625fd03
Revert "Catch Validation error"
shop/context_processors.py
shop/context_processors.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from shop.models.customer import CustomerModel def customer(request): """ Add the customer to the RequestContext """ msg = "The request object does not contain a customer. Edit your MIDDLEWARE_CLASSES setting to insert 'shop.middlerware.CustomerMiddleware'." assert hasattr(request, 'customer'), msg context = { 'customer': request.customer, 'site_header': settings.SHOP_APP_LABEL.capitalize(), } if request.user.is_staff: try: context.update(customer=CustomerModel.objects.get(pk=request.session['emulate_user_id'])) except (CustomerModel.DoesNotExist, KeyError, AttributeError): pass return context
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.forms.utils import ValidationError from shop.models.customer import CustomerModel def customer(request): """ Add the customer to the RequestContext """ msg = "The request object does not contain a customer. Edit your MIDDLEWARE_CLASSES setting to insert 'shop.middlerware.CustomerMiddleware'." assert hasattr(request, 'customer'), msg context = { 'customer': request.customer, 'site_header': settings.SHOP_APP_LABEL.capitalize(), } if request.user.is_staff: try: context.update(customer=CustomerModel.objects.get(pk=request.session['emulate_user_id'])) except (CustomerModel.DoesNotExist, KeyError, AttributeError, ValidationError): pass return context
Python
0
0cb7f9c41c7ae0a7f487188721f56adf2ff9999d
add type hints.
lib/acli/services/route53.py
lib/acli/services/route53.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, print_function, unicode_literals) from boto3.session import Session from acli.output.route53 import (output_route53_list, output_route53_info) import botocore.exceptions def get_boto3_session(aws_config): """ @type aws_config: Config """ return Session(region_name=aws_config.region, aws_access_key_id=aws_config.access_key_id, aws_secret_access_key=aws_config.secret_access_key) def route53_list(aws_config=None): """ @type aws_config: Config """ session = get_boto3_session(aws_config) conn = session.client('route53') output_route53_list(output_media='console', zones=conn.list_hosted_zones()) def route53_info(aws_config=None, zone_id=None): """ @type aws_config: Config @type zone_id: unicode """ session = get_boto3_session(aws_config) conn = session.client('route53') try: hosted_zone = conn.get_hosted_zone(Id=zone_id) record_sets = conn.list_resource_record_sets(HostedZoneId=zone_id) if hosted_zone['HostedZone']['Id']: output_route53_info(output_media='console', zone=hosted_zone, record_sets=record_sets) except AttributeError: exit("Cannot find hosted zone: {0}".format(zone_id)) except botocore.exceptions.ClientError: exit("Cannot request hosted zone: {0}".format(zone_id))
# -*- coding: utf-8 -*- from __future__ import (absolute_import, print_function, unicode_literals) from boto3.session import Session from acli.output.route53 import (output_route53_list, output_route53_info) import botocore.exceptions def get_boto3_session(aws_config): return Session(region_name=aws_config.region, aws_access_key_id=aws_config.access_key_id, aws_secret_access_key=aws_config.secret_access_key) def route53_list(aws_config=None): session = get_boto3_session(aws_config) conn = session.client('route53') output_route53_list(output_media='console', zones=conn.list_hosted_zones()) def route53_info(aws_config=None, zone_id=None): """ @type aws_config: Config @type zone_id: unicode """ session = get_boto3_session(aws_config) conn = session.client('route53') try: hosted_zone = conn.get_hosted_zone(Id=zone_id) record_sets = conn.list_resource_record_sets(HostedZoneId=zone_id) if hosted_zone['HostedZone']['Id']: output_route53_info(output_media='console', zone=hosted_zone, record_sets=record_sets) except AttributeError: exit("Cannot find hosted zone: {0}".format(zone_id)) except botocore.exceptions.ClientError: exit("Cannot request hosted zone: {0}".format(zone_id))
Python
0
b747391c748c94cd8433dfacd935d131b484a29c
Improve error handling and refactor base path
java/ql/src/utils/model-generator/RegenerateModels.py
java/ql/src/utils/model-generator/RegenerateModels.py
#!/usr/bin/python3 # Tool to regenerate existing framework CSV models. from pathlib import Path import json import os import requests import shutil import subprocess import tempfile import sys defaultModelPath = "java/ql/lib/semmle/code/java/frameworks" lgtmSlugToModelFile = { # "apache/commons-beanutils": "apache/BeanUtilsGenerated.qll", # "apache/commons-codec": "apache/CodecGenerated.qll", # "apache/commons-lang": "apache/Lang3Generated.qll", "apache/commons-io": "apache/IOGenerated.qll", } def findGitRoot(): return subprocess.check_output( ["git", "rev-parse", "--show-toplevel"]).decode("utf-8").strip() def regenerateModel(lgtmSlug, extractedDb): tmpDir = tempfile.mkdtemp() print("============================================================") print("Generating models for " + lgtmSlug) print("============================================================") # check if lgtmSlug exists as key if lgtmSlug not in lgtmSlugToModelFile: print("ERROR: slug " + lgtmSlug + " is not mapped to a model file in script " + sys.argv[0]) sys.exit(1) modelFile = defaultModelPath + \ lgtmSlugToModelFile[lgtmSlug] codeQlRoot = findGitRoot() targetModel = codeQlRoot + "/" + modelFile subprocess.check_call([codeQlRoot + "/java/ql/src/utils/model-generator/GenerateFlowModel.py", extractedDb, targetModel]) print("Regenerated " + targetModel) shutil.rmtree(tmpDir) if len(sys.argv) == 3: lgtmSlug = sys.argv[1] db = sys.argv[2] regenerateModel(lgtmSlug, db) else: print('error')
#!/usr/bin/python3 # Tool to regenerate existing framework CSV models. from pathlib import Path import json import os import requests import shutil import subprocess import tempfile import sys lgtmSlugToModelFile = { # "apache/commons-beanutils": "java/ql/lib/semmle/code/java/frameworks/apache/BeanUtilsGenerated.qll", # "apache/commons-codec": "java/ql/lib/semmle/code/java/frameworks/apache/CodecGenerated.qll", # "apache/commons-lang": "java/ql/lib/semmle/code/java/frameworks/apache/Lang3Generated.qll", "apache/commons-io": "java/ql/lib/semmle/code/java/frameworks/apache/IOGenerated.qll", } def findGitRoot(): return subprocess.check_output( ["git", "rev-parse", "--show-toplevel"]).decode("utf-8").strip() def regenerateModel(lgtmSlug, extractedDb): tmpDir = tempfile.mkdtemp() print("============================================================") print("Generating models for " + lgtmSlug) print("============================================================") modelFile = lgtmSlugToModelFile[lgtmSlug] codeQlRoot = findGitRoot() targetModel = codeQlRoot + "/" + modelFile subprocess.check_call([codeQlRoot + "/java/ql/src/utils/model-generator/GenerateFlowModel.py", extractedDb, targetModel]) print("Regenerated " + targetModel) shutil.rmtree(tmpDir) if len(sys.argv) == 3: lgtmSlug = sys.argv[1] db = sys.argv[2] regenerateModel(lgtmSlug, db) else: print('error')
Python
0
f3fd4d098ef5465776cd3e71a8e6c889a2b74ff6
Update proxy.py
lazada_scsdk/proxy.py
lazada_scsdk/proxy.py
# -*- coding: utf-8 -*- # @Author: Phu Hoang # @Date: 2017-05-23 09:40:32 # @Last Modified by: Phu Hoang # @Last Modified time: 2017-06-16 10:53:12 import logging from requests.exceptions import ReadTimeout from http_request_randomizer.requests.proxy.requestProxy import RequestProxy from http_request_randomizer.requests.parsers.FreeProxyParser import FreeProxyParser from http_request_randomizer.requests.parsers.ProxyForEuParser import ProxyForEuParser from http_request_randomizer.requests.parsers.RebroWeeblyParser import RebroWeeblyParser from http_request_randomizer.requests.parsers.SamairProxyParser import SamairProxyParser from http_request_randomizer.requests.parsers.HideMyAssProxyParser import HideMyAssProxyParser from http_request_randomizer.requests.useragent.userAgent import UserAgentManager # Push back requests library to at least warnings logging.getLogger("requests").setLevel(logging.WARNING) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-6s %(levelname)-8s %(message)s') handler.setFormatter(formatter) class Proxy(RequestProxy): def __init__(self, web_proxy_list=[], sustain=False, timeout=20): self.userAgent = UserAgentManager() self.logger = logging.getLogger() self.logger.addHandler(handler) self.logger.setLevel(0) ##### # Each of the classes below implements a specific URL Parser ##### parsers = list([]) parsers.append(FreeProxyParser('http://free-proxy-list.net', timeout=timeout)) parsers.append(ProxyForEuParser('http://proxyfor.eu/geo.php', 1.0, timeout=timeout)) parsers.append(RebroWeeblyParser('http://rebro.weebly.com', timeout=timeout)) parsers.append(SamairProxyParser('http://samair.ru/proxy/time-01.htm', timeout=timeout)) parsers.append(HideMyAssProxyParser('http://proxylist.hidemyass.com/', timeout=timeout)) self.sustain = sustain self.parsers = parsers self.proxy_list = web_proxy_list if len(self.proxy_list) == 0: self.logger.debug("=== Initialized Proxy Parsers ===") for i in range(len(parsers)): self.logger.debug("\t {0}".format(parsers[i].__str__())) self.logger.debug("=================================") for i in range(len(parsers)): try: self.proxy_list += parsers[i].parse_proxyList() except ReadTimeout: self.logger.warn("Proxy Parser: '{}' TimedOut!".format(parsers[i].url)) else: print("Loaded proxies from file") self.current_proxy = self.randomize_proxy()
# -*- coding: utf-8 -*- # @Author: Phu Hoang # @Date: 2017-05-23 09:40:32 # @Last Modified by: Phu Hoang # @Last Modified time: 2017-06-16 10:53:12 import logging from requests.exceptions import ReadTimeout from http_request_randomizer.requests.proxy.requestProxy import RequestProxy from http_request_randomizer.requests.parsers.FreeProxyParser import FreeProxyParser from http_request_randomizer.requests.parsers.ProxyForEuParser import ProxyForEuParser from http_request_randomizer.requests.parsers.RebroWeeblyParser import RebroWeeblyParser from http_request_randomizer.requests.parsers.SamairProxyParser import SamairProxyParser from http_request_randomizer.requests.parsers.HideMyAssProxyParser import HideMyAssProxyParser from http_request_randomizer.requests.useragent.userAgent import UserAgentManager # Push back requests library to at least warnings logging.getLogger("requests").setLevel(logging.WARNING) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-6s %(levelname)-8s %(message)s') handler.setFormatter(formatter) class Proxy(RequestProxy): def __init__(self, web_proxy_list=[], sustain=False, timeout=20): self.userAgent = UserAgentManager() self.logger = logging.getLogger() self.logger.addHandler(handler) self.logger.setLevel(0) ##### # Each of the classes below implements a specific URL Parser ##### parsers = list([]) # parsers.append(FreeProxyParser('http://free-proxy-list.net', timeout=timeout)) parsers.append(ProxyForEuParser('http://proxyfor.eu/geo.php', 1.0, timeout=timeout)) parsers.append(RebroWeeblyParser('http://rebro.weebly.com', timeout=timeout)) parsers.append(SamairProxyParser('http://samair.ru/proxy/time-01.htm', timeout=timeout)) parsers.append(HideMyAssProxyParser('http://proxylist.hidemyass.com/', timeout=timeout)) self.sustain = sustain self.parsers = parsers self.proxy_list = web_proxy_list if len(self.proxy_list) == 0: self.logger.debug("=== Initialized Proxy Parsers ===") for i in range(len(parsers)): self.logger.debug("\t {0}".format(parsers[i].__str__())) self.logger.debug("=================================") for i in range(len(parsers)): try: self.proxy_list += parsers[i].parse_proxyList() except ReadTimeout: self.logger.warn("Proxy Parser: '{}' TimedOut!".format(parsers[i].url)) else: print("Loaded proxies from file") self.current_proxy = self.randomize_proxy()
Python
0.000001
394d5f9cd7c911fa790a63332101b784f67f8b55
Add dual variables to constraints
cvxpy/constraints/leq_constraint.py
cvxpy/constraints/leq_constraint.py
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CVXPY. If not, see <http://www.gnu.org/licenses/>. """ import cvxpy.utilities as u import cvxpy.lin_ops.lin_utils as lu # Only need Variable from expressions, but that would create a circular import. from cvxpy import expressions from cvxpy.constraints.constraint import Constraint import numpy as np class LeqConstraint(u.Canonical, Constraint): OP_NAME = "<=" TOLERANCE = 1e-4 def __init__(self, lh_exp, rh_exp): self.args = [lh_exp, rh_exp] self._expr = lh_exp - rh_exp self.dual_variable = expressions.variables.Variable(*self._expr.size) super(LeqConstraint, self).__init__() @property def id(self): """Wrapper for compatibility with variables. """ return self.constr_id def name(self): return ' '.join([str(self.args[0].name()), self.OP_NAME, str(self.args[1].name())]) def __str__(self): """Returns a string showing the mathematical constraint. """ return self.name() def __repr__(self): """Returns a string with information about the constraint. """ return "%s(%s, %s)" % (self.__class__.__name__, repr(self.args[0]), repr(self.args[1])) def __nonzero__(self): """Raises an exception when called. Python 2 version. Called when evaluating the truth value of the constraint. Raising an error here prevents writing chained constraints. """ raise Exception("Cannot evaluate the truth value of a constraint.") def __bool__(self): """Raises an exception when called. Python 3 version. Called when evaluating the truth value of the constraint. Raising an error here prevents writing chained constraints. """ raise Exception("Cannot evaluate the truth value of a constraint.") @property def size(self): return self._expr.size # Left hand expression must be convex and right hand must be concave. def is_dcp(self): return self._expr.is_convex() def canonicalize(self): """Returns the graph implementation of the object. Marks the top level constraint as the dual_holder, so the dual value will be saved to the LeqConstraint. Returns ------- tuple A tuple of (affine expression, [constraints]). """ obj, constraints = self._expr.canonical_form dual_holder = lu.create_leq(obj, constr_id=self.id) return (None, constraints + [dual_holder]) def variables(self): """Returns the variables in the compared expressions. """ return self._expr.variables() def parameters(self): """Returns the parameters in the compared expressions. """ return self._expr.parameters() @property def value(self): """Does the constraint hold? Returns ------- bool """ if self._expr.value is None: return None else: return np.all(self._expr.value <= self.TOLERANCE) @property def violation(self): """How much is this constraint off by? Returns ------- NumPy matrix """ if self._expr.value is None: return None else: return np.maximum(self._expr.value, 0) # The value of the dual variable. @property def dual_value(self): return self.dual_variable.value def save_value(self, value): """Save the value of the dual variable for the constraint's parent. Args: value: The value of the dual variable. """ self.dual_variable.save_value(value)
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CVXPY. If not, see <http://www.gnu.org/licenses/>. """ import cvxpy.utilities as u import cvxpy.lin_ops.lin_utils as lu from cvxpy.constraints.constraint import Constraint import numpy as np class LeqConstraint(u.Canonical, Constraint): OP_NAME = "<=" TOLERANCE = 1e-4 def __init__(self, lh_exp, rh_exp): self.args = [lh_exp, rh_exp] self._expr = lh_exp - rh_exp self._dual_value = None super(LeqConstraint, self).__init__() @property def id(self): """Wrapper for compatibility with variables. """ return self.constr_id def name(self): return ' '.join([str(self.args[0].name()), self.OP_NAME, str(self.args[1].name())]) def __str__(self): """Returns a string showing the mathematical constraint. """ return self.name() def __repr__(self): """Returns a string with information about the constraint. """ return "%s(%s, %s)" % (self.__class__.__name__, repr(self.args[0]), repr(self.args[1])) def __nonzero__(self): """Raises an exception when called. Python 2 version. Called when evaluating the truth value of the constraint. Raising an error here prevents writing chained constraints. """ raise Exception("Cannot evaluate the truth value of a constraint.") def __bool__(self): """Raises an exception when called. Python 3 version. Called when evaluating the truth value of the constraint. Raising an error here prevents writing chained constraints. """ raise Exception("Cannot evaluate the truth value of a constraint.") @property def size(self): return self._expr.size # Left hand expression must be convex and right hand must be concave. def is_dcp(self): return self._expr.is_convex() def canonicalize(self): """Returns the graph implementation of the object. Marks the top level constraint as the dual_holder, so the dual value will be saved to the LeqConstraint. Returns ------- tuple A tuple of (affine expression, [constraints]). """ obj, constraints = self._expr.canonical_form dual_holder = lu.create_leq(obj, constr_id=self.id) return (None, constraints + [dual_holder]) def variables(self): """Returns the variables in the compared expressions. """ return self._expr.variables() def parameters(self): """Returns the parameters in the compared expressions. """ return self._expr.parameters() @property def value(self): """Does the constraint hold? Returns ------- bool """ if self._expr.value is None: return None else: return np.all(self._expr.value <= self.TOLERANCE) @property def violation(self): """How much is this constraint off by? Returns ------- NumPy matrix """ if self._expr.value is None: return None else: return np.maximum(self._expr.value, 0) # The value of the dual variable. @property def dual_value(self): return self._dual_value def save_value(self, value): """Save the value of the dual variable for the constraint's parent. Args: value: The value of the dual variable. """ self._dual_value = value
Python
0
1e1e2793bad3db9201e51c5038edde5373424ad6
Put infrastructure in place for javascript targetting
client/compile.py
client/compile.py
#!/usr/bin/env python import os.path from HTMLParser import HTMLParser import re """ Certain runtimes (like AIR) don't support dynamic function creation. Parse the JavaScript and create the template beforehand. """ class Compiler(HTMLParser): script = '' scripts = {} javascripts = {} inScript = False scriptName = '' def handle_startendtag(self, tag, attrs): if self.inScript: self.script += '<' + tag if attrs: for key, value in attrs: self.script += ' ' + key + '=' + '"' + value + '"' self.script += '/>' def handle_starttag(self, tag, attrs): if self.inScript: self.script += '<' + tag if attrs: for key, value in attrs: self.script += ' ' + key + '=' + '"' + value + '"' self.script += '>' if tag == 'script': name = '' target = '' for i in attrs: if i[0] == 'type': if i[1] == 'text/html': self.inScript = True; elif i[1] == 'text/javascript': # Evaluate the target and built it for the necesarry runtime. found = True elif i[0] == 'name': name = i[1] if self.inScript: self.scriptName = name def handle_endtag(self, tag): if tag == 'script' and self.inScript: self.inScript = False self.scripts[self.scriptName] = self.script self.script = '' elif self.inScript: self.script += '</' + tag + '>' def handle_data(self, data): if self.inScript: self.script += data def main(): html_path = os.path.join(os.path.dirname(__file__), 'index.html') buffer = open(html_path) data = buffer.read() buffer.close() parser = Compiler() parser.feed(data) parser.close() scripts = '' for name, script in parser.scripts.items(): # Convert the template into pure JavaScript scr = re.sub(r'\s+', ' ', re.sub(r"(\r|\t|\n)", ' ', script)) scr = scr.replace('<%', '\t') scr = re.sub(r"((^|%>)[^\t]*)'", r'\1\n', scr) scr = scr.replace("'", "\\'") scr = re.sub(r"\t=(.*?)%>", "',\\1,'", scr) scr = scr.replace("\t", "');").replace('%>', "p.push('").replace("\n", "\\'") scr = "TileMill.templates['%s']=function(obj) {var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('" % (name) + scr + "');}return p.join(''); }\n" scripts += scr js_path = os.path.join(os.path.dirname(__file__), 'js', 'includes', 'template.cache.js') buffer = open(js_path, 'w') buffer.write(scripts) buffer.close() if __name__ == "__main__": main()
#!/usr/bin/env python import os.path from HTMLParser import HTMLParser import re """ Certain runtimes (like AIR) don't support dynamic function creation. Parse the JavaScript and create the template beforehand. """ class Compiler(HTMLParser): script = '' scripts = {} inScript = False scriptName = '' def handle_startendtag(self, tag, attrs): if self.inScript: self.script += '<' + tag if attrs: for key, value in attrs: self.script += ' ' + key + '=' + '"' + value + '"' self.script += '/>' def handle_starttag(self, tag, attrs): if self.inScript: self.script += '<' + tag if attrs: for key, value in attrs: self.script += ' ' + key + '=' + '"' + value + '"' self.script += '>' if tag == 'script': found = False name = '' for i in attrs: if i[0] == 'type' and i[1] == 'text/html': found = True elif i[0] == 'name': name = i[1] if found: self.inScript = True self.scriptName = name def handle_endtag(self, tag): if tag == 'script' and self.inScript: self.inScript = False self.scripts[self.scriptName] = self.script self.script = '' elif self.inScript: self.script += '</' + tag + '>' def handle_data(self, data): if self.inScript: self.script += data def main(): html_path = os.path.join(os.path.dirname(__file__), 'index.html') buffer = open(html_path) data = buffer.read() buffer.close() parser = Compiler() parser.feed(data) parser.close() scripts = '' for name, script in parser.scripts.items(): # Convert the template into pure JavaScript scr = re.sub(r'\s+', ' ', re.sub(r"(\r|\t|\n)", ' ', script)) scr = scr.replace('<%', '\t') scr = re.sub(r"((^|%>)[^\t]*)'", r'\1\n', scr) scr = scr.replace("'", "\\'") scr = re.sub(r"\t=(.*?)%>", "',\\1,'", scr) scr = scr.replace("\t", "');").replace('%>', "p.push('").replace("\n", "\\'") scr = "TileMill.templates['%s']=function(obj) {var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('" % (name) + scr + "');}return p.join(''); }\n" scripts += scr js_path = os.path.join(os.path.dirname(__file__), 'js', 'includes', 'template.cache.js') buffer = open(js_path, 'w') buffer.write(scripts) buffer.close() if __name__ == "__main__": main()
Python
0.000001
7dffc7115b5e91ba13de8cb3e306832be7f8e185
print result in show components
client/jiraffe.py
client/jiraffe.py
import urllib import os SERVICE_URL = "http://jiraffe.cloudhub.io/api" CREATE_SERVICE = SERVICE_URL + "/issues" DEFAULT_SERVICE = SERVICE_URL + "/defaults" COMPONENT_SERVICE = SERVICE_URL + "/components" def get_valid_reporter(reporter): if reporter == "": return os.environ['JIRA_ID'] return reporter def createIssue(project, summary, bug_type, sprint, reporter, assignee, priority, component): query_args = {'summary': summary, 'reporter': get_valid_reporter(reporter)} headers = {"content-type": "application/plain-text"} if project != "": query_args['project'] = project if bug_type != "": query_args['type'] = bug_type if sprint != "": query_args['sprint'] = sprint valid_assignee = get_valid_reporter(assignee) if valid_assignee != "": query_args['assignee'] = valid_assignee if priority != "": query_args['priority'] = priority encoded_args = urllib.urlencode(query_args) #print(encoded_args) print(urllib.urlopen(CREATE_SERVICE +"?"+ encoded_args, encoded_args).read()) def update_defaults(project, sprint, bug_type): #{"sprint":"123","type":"Bug","project":"AUTOMATION","id":9} query_args = {} if project != "": query_args['project'] = project if bug_type != "": query_args['type'] = bug_type if sprint != "": query_args['sprint'] = sprint encoded_args = urllib.urlencode(query_args) #print(encoded_args) headers = {"content-type": "application/plain-text"} print(urllib.urlopen(DEFAULT_SERVICE +"?"+ encoded_args, encoded_args).read()) def show_issue(issue_id): response = urllib.urlopen(CREATE_SERVICE + "/" + issue_id) print(response.read()) def show_components(project_id): query_args = {} if project_id != "": query_args['project'] = project_id encoded_args = urllib.urlencode(query_args) response = urllib.urlopen(COMPONENT_SERVICE+ "?" + encoded_args) print(response.read()) def show_defaults(): response = urllib.urlopen(DEFAULT_SERVICE) print(response.read())
import urllib import os SERVICE_URL = "http://jiraffe.cloudhub.io/api" CREATE_SERVICE = SERVICE_URL + "/issues" DEFAULT_SERVICE = SERVICE_URL + "/defaults" COMPONENT_SERVICE = SERVICE_URL + "/components" def get_valid_reporter(reporter): if reporter == "": return os.environ['JIRA_ID'] return reporter def createIssue(project, summary, bug_type, sprint, reporter, assignee, priority, component): query_args = {'summary': summary, 'reporter': get_valid_reporter(reporter)} headers = {"content-type": "application/plain-text"} if project != "": query_args['project'] = project if bug_type != "": query_args['type'] = bug_type if sprint != "": query_args['sprint'] = sprint valid_assignee = get_valid_reporter(assignee) if valid_assignee != "": query_args['assignee'] = valid_assignee if priority != "": query_args['priority'] = priority encoded_args = urllib.urlencode(query_args) #print(encoded_args) print(urllib.urlopen(CREATE_SERVICE +"?"+ encoded_args, encoded_args).read()) def update_defaults(project, sprint, bug_type): #{"sprint":"123","type":"Bug","project":"AUTOMATION","id":9} query_args = {} if project != "": query_args['project'] = project if bug_type != "": query_args['type'] = bug_type if sprint != "": query_args['sprint'] = sprint encoded_args = urllib.urlencode(query_args) #print(encoded_args) headers = {"content-type": "application/plain-text"} print(urllib.urlopen(DEFAULT_SERVICE +"?"+ encoded_args, encoded_args).read()) def show_issue(issue_id): response = urllib.urlopen(CREATE_SERVICE + "/" + issue_id) print(response.read()) def show_components(project_id): query_args = {} if project_id != "": query_args['project'] = project_id encoded_args = urllib.urlencode(query_args) response = urllib.urlopen(COMPONENT_SERVICE+ "?" + encoded_args) def show_defaults(): response = urllib.urlopen(DEFAULT_SERVICE) print(response.read())
Python
0
a7e45cc5cd9ec9d706b4160f988616d87e185cb8
FIX survey validate_questions
survey_conditional_questions/survey.py
survey_conditional_questions/survey.py
# -*- coding: utf-8 -*- from openerp import fields, models import logging _logger = logging.getLogger(__name__) class survey_question(models.Model): _inherit = 'survey.question' conditional = fields.Boolean( 'Conditional Question', copy=False, # we add copy = false to avoid wrong link on survey copy, # should be improoved ) question_conditional_id = fields.Many2one( 'survey.question', 'Question', copy=False, help="In order to edit this field you should first save the question" ) answer_id = fields.Many2one( 'survey.label', 'Answer', copy=False, ) def validate_question( self, cr, uid, question, post, answer_tag, context=None): ''' Validate question, depending on question type and parameters ''' input_answer_id = self.pool['survey.user_input_line'].search( cr, uid, [('user_input_id.token', '=', post.get('token')), ('question_id', '=', question.question_conditional_id.id)]) try: checker = getattr(self, 'validate_' + question.type) except AttributeError: _logger.warning( question.type + ": This type of question has no validation method") return {} else: if question.conditional and question.answer_id != self.pool['survey.user_input_line'].browse( cr, uid, input_answer_id).value_suggested: return {} else: return checker(cr, uid, question, post, answer_tag, context=context) class survey_user_input(models.Model): _inherit = 'survey.user_input' def get_list_questions(self, cr, uid, survey, user_input_id): obj_questions = self.pool['survey.question'] obj_user_input_line = self.pool['survey.user_input_line'] questions_to_hide = [] question_ids = obj_questions.search( cr, uid, [('survey_id', '=', survey.id)]) for question in obj_questions.browse(cr, uid, question_ids): if question.conditional: for question2 in obj_questions.browse(cr, uid, question_ids): if question2 == question.question_conditional_id: input_answer_id = obj_user_input_line.search( cr, uid, [('user_input_id', '=', user_input_id), ('question_id', '=', question2.id)]) if question.answer_id != obj_user_input_line.browse( cr, uid, input_answer_id).value_suggested: questions_to_hide.append(question.id) return questions_to_hide
# -*- coding: utf-8 -*- from openerp import fields, models class survey_question(models.Model): _inherit = 'survey.question' conditional = fields.Boolean( 'Conditional Question', copy=False, # we add copy = false to avoid wrong link on survey copy, # should be improoved ) question_conditional_id = fields.Many2one( 'survey.question', 'Question', copy=False, help="In order to edit this field you should first save the question" ) answer_id = fields.Many2one( 'survey.label', 'Answer', copy=False, ) # NO HACEMOS ESTA MOD GENERICA PORQUE DA ERROR AL ALMACENAR LOS CHOICE # def validate_question( # self, cr, uid, question, post, answer_tag, context=None): # """We add answer_tag if not in post because it gets an error in this # method, this happens when question is not display so the answer_tag # value is no on post dictionary""" # if answer_tag not in post: # post[answer_tag] = '' # return super(survey_question, self).validate_question( # cr, uid, question, post, answer_tag, context=context) def validate_free_text( self, cr, uid, question, post, answer_tag, context=None): """We add answer_tag if not in post because it gets an error in this method, this happens when question is not display so the answer_tag value is no on post dictionary""" if answer_tag not in post: post[answer_tag] = '' return super(survey_question, self).validate_free_text( cr, uid, question, post, answer_tag, context=context) def validate_textbox( self, cr, uid, question, post, answer_tag, context=None): """We add answer_tag if not in post because it gets an error in this method, this happens when question is not display so the answer_tag value is no on post dictionary""" if answer_tag not in post: post[answer_tag] = '' return super(survey_question, self).validate_textbox( cr, uid, question, post, answer_tag, context=context) def validate_numerical_box( self, cr, uid, question, post, answer_tag, context=None): """We add answer_tag if not in post because it gets an error in this method, this happens when question is not display so the answer_tag value is no on post dictionary""" if answer_tag not in post: post[answer_tag] = '' return super(survey_question, self).validate_numerical_box( cr, uid, question, post, answer_tag, context=context) def validate_datetime( self, cr, uid, question, post, answer_tag, context=None): """We add answer_tag if not in post because it gets an error in this method, this happens when question is not display so the answer_tag value is no on post dictionary""" if answer_tag not in post: post[answer_tag] = '' return super(survey_question, self).validate_datetime( cr, uid, question, post, answer_tag, context=context) class survey_user_input(models.Model): _inherit = 'survey.user_input' def get_list_questions(self, cr, uid, survey, user_input_id): obj_questions = self.pool['survey.question'] obj_user_input_line = self.pool['survey.user_input_line'] questions_to_hide = [] question_ids = obj_questions.search( cr, uid, [('survey_id', '=', survey.id)]) for question in obj_questions.browse(cr, uid, question_ids): if question.conditional: for question2 in obj_questions.browse(cr, uid, question_ids): if question2 == question.question_conditional_id: input_answer_id = obj_user_input_line.search( cr, uid, [('user_input_id', '=', user_input_id), ('question_id', '=', question2.id)]) if question.answer_id != obj_user_input_line.browse( cr, uid, input_answer_id).value_suggested: questions_to_hide.append(question.id) return questions_to_hide
Python
0
f6be438e01a499dc2bde6abfa5a00fb281db7b83
Add account_id as the element of this class
kamboo/core.py
kamboo/core.py
import botocore from kotocore.session import Session class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region)
import botocore from kotocore.session import Session class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", credentials=None): self.region = region_name self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region)
Python
0.000001
a76b866862874ce52c762b4e0381b233917a977a
Increment version
karld/_meta.py
karld/_meta.py
version_info = (0, 2, 7) version = '.'.join(map(str, version_info))
version_info = (0, 2, 6) version = '.'.join(map(str, version_info))
Python
0.000002
31d7df470dbaf996f4f3c7639107ec04afda1ec4
Update runcount.py
bin/runcount.py
bin/runcount.py
#!/usr/bin/python import os from count import countfile import common def runAll(args): print('\n\n\nYou have requested to count unique sam files') print('\tWARNING:') print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY') print('\n') #set up environment# args.SamDirectory = common.fixDirName(args.SamDirectory) countDir = os.path.dirname(args.SamDirectory[:-1]) + '/' + BinCounts + '/' if args.output: countDir = common.fixDirName(args.output) statsDir = os.path.dirname(args.SamDirectory[:-1]) + '/' + PipelineStats + '/' if args.statdir: statsDir = common.fixDirName(args.statdir) for i in [countDir, statsDir]: common.makeDir(i) samFiles = common.getSampleList(args.SamDirectory, args.samples, 'sam') #run multiprocessing of all bin counting commands# argList = [(x, countDir, statsDir, args.species) for x in samFiles] common.daemon(countfile.runOne, argList, 'count sam files') print('\nBin counts complete\n\n\n')
#!/usr/bin/python import os from count import countfile import common def runAll(args): print('\n\n\nYou have requested to count unique sam files') print('\tWARNING:') print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY') print('\n') #set up environment# args.SamDirectory = common.fixDirName(args.SamDirectory) countDir = os.path.dirname(args.SamDirectory[:-1]) + '/' + BinCounts + '/' if args.output: countDir = common.fixDirName(args.output) statsDir = os.path.dirname(args.SamDirectory[:-1]) + '/' + PipelineStats + '/' if args.statdir: statsDir = common.fixDirName(args.statdir) for i in [countDir, statsDir]: common.makeDir(i) samFiles = common.getSampleList(args.SamDirectory, args.samples, 'sam') #run multiprocessing of all mapping commands# argList = [(x, countDir, statsDir, args.species) for x in samFiles] common.daemon(countfile.runOne, argList, 'count sam files') print('\nBin counts complete\n\n\n')
Python
0.000001
e6520bb2c2f016f39ae76bfb15dd62cfdb2fdf63
update rcomp CLI index printing, given new serv format
frontend/rcomp/cli.py
frontend/rcomp/cli.py
"""command-line interface (CLI) For local development, use the `--rcomp-server` switch to direct this client at the localhost. E.g., rcomp --rcomp-server http://127.0.0.1:8000 """ import argparse import sys import json import requests from . import __version__ def main(argv=None): parser = argparse.ArgumentParser(prog='rcomp', add_help=False) parser.add_argument('--rcomp-help', action='store_true', dest='show_help', help='print this help message and exit') parser.add_argument('--rcomp-version', action='store_true', dest='show_version', help='print version number and exit') parser.add_argument('--rcomp-server', metavar='URI', dest='base_uri', help=('base URI for job requests.' ' (default is https://api.fmtools.org)')) parser.add_argument('--rcomp-nonblocking', action='store_true', dest='nonblocking', default=False, help=('Default behavior is to wait for remote job' ' to complete. Use this switch to immediately' ' return after job successfully starts.')) parser.add_argument('--rcomp-continue', metavar='JOBID', dest='job_id', default=None, nargs='?', help='') parser.add_argument('COMMAND', nargs='?') parser.add_argument('ARGV', nargs=argparse.REMAINDER) if argv is None: args = parser.parse_args() else: args = parser.parse_args(argv) if args.show_help: parser.print_help() return 0 if args.show_version: print('rcomp '+__version__) return 0 if args.base_uri is None: base_uri = 'https://api.fmtools.org' else: base_uri = args.base_uri if args.COMMAND is None: res = requests.get(base_uri+'/') if res.ok: index = json.loads(res.text) assert 'commands' in index print('The following commands are available at {}' .format(base_uri)) for cmd in index['commands'].values(): print('{NAME} {SUMMARY}' .format(NAME=cmd['name'], SUMMARY=cmd['summary'])) else: res = requests.get(base_uri+'/' + args.COMMAND) if res.ok: print(res.text) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
"""command-line interface (CLI) For local development, use the `--rcomp-server` switch to direct this client at the localhost. E.g., rcomp --rcomp-server http://127.0.0.1:8000 """ import argparse import sys import json import requests from . import __version__ def main(argv=None): parser = argparse.ArgumentParser(prog='rcomp', add_help=False) parser.add_argument('--rcomp-help', action='store_true', dest='show_help', help='print this help message and exit') parser.add_argument('--rcomp-version', action='store_true', dest='show_version', help='print version number and exit') parser.add_argument('--rcomp-server', metavar='URI', dest='base_uri', help=('base URI for job requests.' ' (default is https://api.fmtools.org)')) parser.add_argument('--rcomp-nonblocking', action='store_true', dest='nonblocking', default=False, help=('Default behavior is to wait for remote job' ' to complete. Use this switch to immediately' ' return after job successfully starts.')) parser.add_argument('--rcomp-continue', metavar='JOBID', dest='job_id', default=None, nargs='?', help='') parser.add_argument('COMMAND', nargs='?') parser.add_argument('ARGV', nargs=argparse.REMAINDER) if argv is None: args = parser.parse_args() else: args = parser.parse_args(argv) if args.show_help: parser.print_help() return 0 if args.show_version: print('rcomp '+__version__) return 0 if args.base_uri is None: base_uri = 'https://api.fmtools.org' else: base_uri = args.base_uri if args.COMMAND is None: res = requests.get(base_uri+'/') if res.ok: index = json.loads(res.text) assert 'commands' in index print('The following commands are available at {}' .format(base_uri)) for cmd in index['commands']: print('{NAME} {SUMMARY}' .format(NAME=cmd['name'], SUMMARY=cmd['summary'])) else: res = requests.get(base_uri+'/' + args.COMMAND) if res.ok: print(res.text) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
Python
0
c4a0a83fe4a028b1d571058aed755be5b4714531
fix logging
includes/SteamGroupMembers.py
includes/SteamGroupMembers.py
import logging import urllib2 import xml.etree.ElementTree as ElementTree logger = logging.getLogger() class SteamGroupMembers(object): """ Retrives all members of the specified group. """ _members = None def __init__(self, group_id): self._group_id = group_id def __len__(self): return len(self._get_members()) def __contains__(self, item): return item in self._get_members() def __iter__(self): return self._get_members().__iter__() def _get_members(self): if self._members is None: self._members = [] url = 'http://steamcommunity.com/gid/%s/memberslistxml/?xml=1' % self._group_id logger.debug('Loading steam group members %s', url) while True: responce = urllib2.urlopen(url) xml = ElementTree.parse(responce).getroot() members_elements = xml.findall('members/steamID64') members = map(lambda e: e.text, members_elements) self._members.extend(members) next_page = xml.find('nextPageLink') if next_page is not None: url = next_page.text logger.debug('Loading steam group members (next page) %s', url) else: break logger.debug('Found %d members in group %s', len(self._members), self._group_id) return self._members
import logging import urllib2 import xml.etree.ElementTree as ElementTree logger = logging.getLogger() class SteamGroupMembers(object): """ Retrives all members of the specified group. """ _members = None def __init__(self, group_id): self._group_id = group_id def __len__(self): return len(self._get_members()) def __contains__(self, item): return item in self._get_members() def __iter__(self): return self._get_members().__iter__() def _get_members(self): if self._members is None: self._members = [] url = 'http://steamcommunity.com/gid/%s/memberslistxml/?xml=1' % self._group_id while True: logger.debug('Requesting %s', url) responce = urllib2.urlopen(url) xml = ElementTree.parse(responce).getroot() members_elements = xml.findall('members/steamID64') logger.info('Found %d members in group %d', len(members_elements), self._group_id) members = map(lambda e: e.text, members_elements) self._members.extend(members) next_page = xml.find('nextPageLink') if next_page is not None: logger.debug('Found next page link') url = next_page.text else: break return self._members
Python
0.000002
5ffa9f7054f9fcced99e366cfb8ea6de4dd1a01c
Recognize "Sinhala" as an Indic script
hindkit/constants/linguistics.py
hindkit/constants/linguistics.py
INDIC_SCRIPTS = { 'devanagari': { 'abbreviation': 'dv', 'indic1 tag': 'deva', 'indic2 tag': 'dev2', }, 'bangla': { 'abbreviation': 'bn', 'indic1 tag': 'beng', 'indic2 tag': 'bng2', 'alternative name': 'Bengali', }, 'gurmukhi': { 'abbreviation': 'gr', 'indic1 tag': 'guru', 'indic2 tag': 'gur2', }, 'gujarati': { 'abbreviation': 'gj', 'indic1 tag': 'gujr', 'indic2 tag': 'gjr2', }, 'odia': { 'abbreviation': 'od', 'indic1 tag': 'orya', 'indic2 tag': 'ory2', 'alternative name': 'Oriya', }, 'tamil': { 'abbreviation': 'tm', 'indic1 tag': 'taml', 'indic2 tag': 'tml2', }, 'telugu': { 'abbreviation': 'tl', 'indic1 tag': 'telu', 'indic2 tag': 'tel2', }, 'kannada': { 'abbreviation': 'kn', 'indic1 tag': 'knda', 'indic2 tag': 'knd2', }, 'malayalam': { 'abbreviation': 'ml', 'indic1 tag': 'mlym', 'indic2 tag': 'mlm2', }, 'sinhala': { 'abbreviation': 'si', 'tag': 'sinh', }, }
INDIC_SCRIPTS = { 'devanagari': { 'abbreviation': 'dv', 'indic1 tag': 'deva', 'indic2 tag': 'dev2', }, 'bangla': { 'abbreviation': 'bn', 'indic1 tag': 'beng', 'indic2 tag': 'bng2', 'alternative name': 'Bengali', }, 'gurmukhi': { 'abbreviation': 'gr', 'indic1 tag': 'guru', 'indic2 tag': 'gur2', }, 'gujarati': { 'abbreviation': 'gj', 'indic1 tag': 'gujr', 'indic2 tag': 'gjr2', }, 'odia': { 'abbreviation': 'od', 'indic1 tag': 'orya', 'indic2 tag': 'ory2', 'alternative name': 'Oriya', }, 'tamil': { 'abbreviation': 'tm', 'indic1 tag': 'taml', 'indic2 tag': 'tml2', }, 'telugu': { 'abbreviation': 'tl', 'indic1 tag': 'telu', 'indic2 tag': 'tel2', }, 'kannada': { 'abbreviation': 'kn', 'indic1 tag': 'knda', 'indic2 tag': 'knd2', }, 'malayalam': { 'abbreviation': 'ml', 'indic1 tag': 'mlym', 'indic2 tag': 'mlm2', }, }
Python
0.998315
0b7a5929208bddb9e850f10ff40f1521363283fd
decrease map_stats precision
ichnaea/map_stats.py
ichnaea/map_stats.py
import csv from cStringIO import StringIO from ichnaea.db import Measure def map_stats_request(request): session = request.database.session() query = session.query(Measure.lat, Measure.lon) unique = set() for lat, lon in query: unique.add(((lat // 100000) / 1000.0, (lon // 100000) / 1000.0)) rows = StringIO() csvwriter = csv.writer(rows) csvwriter.writerow(('lat', 'lon')) for lat, lon in unique: csvwriter.writerow((lat, lon)) return rows.getvalue()
import csv from cStringIO import StringIO from ichnaea.db import Measure def map_stats_request(request): session = request.database.session() query = session.query(Measure.lat, Measure.lon) unique = set() for lat, lon in query: unique.add(((lat // 10000) / 1000.0, (lon // 10000) / 1000.0)) rows = StringIO() csvwriter = csv.writer(rows) csvwriter.writerow(('lat', 'lon')) for lat, lon in unique: csvwriter.writerow((lat, lon)) return rows.getvalue()
Python
0.000007
3def5ee6b6ffbb60260130deedee65cfc0e186f0
add missing super() constructor in IosAccelerometer
plyer/platforms/ios/accelerometer.py
plyer/platforms/ios/accelerometer.py
''' iOS accelerometer ----------------- Taken from: https://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html#accessing-accelerometer ''' from plyer.facades import Accelerometer from pyobjus import autoclass class IosAccelerometer(Accelerometer): def __init__(self): super(IosAccelerometer, self).__init__() self.bridge = autoclass('bridge').alloc().init() self.bridge.motionManager.setAccelerometerUpdateInterval_(0.1) def _enable(self): self.bridge.startAccelerometer() def _disable(self): self.bridge.stopAccelerometer() def _get_acceleration(self): return ( self.bridge.ac_x, self.bridge.ac_y, self.bridge.ac_z) def instance(): return IosAccelerometer()
''' iOS accelerometer ----------------- Taken from: https://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html#accessing-accelerometer ''' from plyer.facades import Accelerometer from pyobjus import autoclass class IosAccelerometer(Accelerometer): def __init__(self): self.bridge = autoclass('bridge').alloc().init() self.bridge.motionManager.setAccelerometerUpdateInterval_(0.1) def _enable(self): self.bridge.startAccelerometer() def _disable(self): self.bridge.stopAccelerometer() def _get_acceleration(self): return ( self.bridge.ac_x, self.bridge.ac_y, self.bridge.ac_z) def instance(): return IosAccelerometer()
Python
0.000001
a536da0d925201fc652b08ad27985f37c5bd4b6c
Fix relative_urls helper for call from initialization code
src/adhocracy/lib/helpers/site_helper.py
src/adhocracy/lib/helpers/site_helper.py
from pylons import config, app_globals as g from pylons.i18n import _ from paste.deploy.converters import asbool from adhocracy.model import instance_filter as ifilter CURRENT_INSTANCE = object() def get_domain_part(domain_with_port): return domain_with_port.split(':')[0] def domain(): return get_domain_part(config.get('adhocracy.domain')) def name(): return config.get('adhocracy.site.name', _("Adhocracy")) def relative_urls(config=config): return asbool(config.get('adhocracy.relative_urls', 'false')) def base_url(path='', instance=CURRENT_INSTANCE, absolute=False, append_slash=False, config=config): """ Constructs an URL. Path is expected to start with '/'. If not, a relative path to the current object will be created. If instance isn't defined, the current instance is assumed. Otherwise, either an instance instance or None has to be passed. If absolute is True, an absolute URL including the protocol part is returned. Otherwise this is avoided, if relative_urls is set to True. """ if instance == CURRENT_INSTANCE: instance = ifilter.get_instance() if relative_urls(config): if instance is None: prefix = '' else: prefix = '/i/' + instance.key if absolute: protocol = config.get('adhocracy.protocol', 'http').strip() domain = config.get('adhocracy.domain').strip() result = '%s://%s%s%s' % (protocol, domain, prefix, path) else: result = '%s%s' % (prefix, path) else: protocol = config.get('adhocracy.protocol', 'http').strip() domain = config.get('adhocracy.domain').strip() if instance is None or g.single_instance: subdomain = '' else: subdomain = '%s.' % instance.key result = '%s://%s%s%s' % (protocol, subdomain, domain, path) if result == '': result = '/' if append_slash and not result.endswith('/'): result += '/' return result def shortlink_url(delegateable): path = "/d/%s" % delegateable.id return base_url(path, None, absolute=True)
from pylons import config, app_globals as g from pylons.i18n import _ from paste.deploy.converters import asbool from adhocracy.model import instance_filter as ifilter CURRENT_INSTANCE = object() def get_domain_part(domain_with_port): return domain_with_port.split(':')[0] def domain(): return get_domain_part(config.get('adhocracy.domain')) def name(): return config.get('adhocracy.site.name', _("Adhocracy")) def relative_urls(): return asbool(config.get('adhocracy.relative_urls', 'false')) def base_url(path='', instance=CURRENT_INSTANCE, absolute=False, append_slash=False, config=config): """ Constructs an URL. Path is expected to start with '/'. If not, a relative path to the current object will be created. If instance isn't defined, the current instance is assumed. Otherwise, either an instance instance or None has to be passed. If absolute is True, an absolute URL including the protocol part is returned. Otherwise this is avoided, if relative_urls is set to True. """ if instance == CURRENT_INSTANCE: instance = ifilter.get_instance() if relative_urls(): if instance is None: prefix = '' else: prefix = '/i/' + instance.key if absolute: protocol = config.get('adhocracy.protocol', 'http').strip() domain = config.get('adhocracy.domain').strip() result = '%s://%s%s%s' % (protocol, domain, prefix, path) else: result = '%s%s' % (prefix, path) else: protocol = config.get('adhocracy.protocol', 'http').strip() domain = config.get('adhocracy.domain').strip() if instance is None or g.single_instance: subdomain = '' else: subdomain = '%s.' % instance.key result = '%s://%s%s%s' % (protocol, subdomain, domain, path) if result == '': result = '/' if append_slash and not result.endswith('/'): result += '/' return result def shortlink_url(delegateable): path = "/d/%s" % delegateable.id return base_url(path, None, absolute=True)
Python
0.000006
3f8a29efa3128f8167306b46e47e7ac18cf592ab
set broker pool limit
celeryconfig.py
celeryconfig.py
import os import sys import urlparse from kombu import Exchange, Queue sys.path.append('.') redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/") if not redis_url.endswith("/"): redis_url += "/" BROKER_URL = redis_url + "1" # REDIS_CELERY_TASKS_DATABASE_NUMBER = 1 CELERY_RESULT_BACKEND = redis_url + "2" # REDIS_CELERY_RESULTS_DATABASE_NUMBER = 2 REDIS_CONNECT_RETRY = True # these options will be defaults in future as per http://celery.readthedocs.org/en/latest/getting-started/brokers/redis.html BROKER_TRANSPORT_OPTIONS = {'fanout_prefix': True, 'fanout_patterns': True, 'visibility_timeout': 60 # one minute } CELERY_DEFAULT_QUEUE = 'core_high' CELERY_QUEUES = [ Queue('core_high', routing_key='core_high'), Queue('core_low', routing_key='core_low') ] # added because https://github.com/celery/celery/issues/896 BROKER_POOL_LIMIT = 100 CELERY_CREATE_MISSING_QUEUES = True CELERY_ACCEPT_CONTENT = ['pickle', 'json'] CELERY_ENABLE_UTC = True CELERY_TASK_RESULT_EXPIRES = 60*60 # 1 hour CELERY_ACKS_LATE = True # remove this, might fix deadlocks as per https://github.com/celery/celery/issues/970 # CELERYD_MAX_TASKS_PER_CHILD = 100 CELERYD_FORCE_EXECV = True CELERY_TRACK_STARTED = True # https://groups.google.com/forum/#!topic/celery-users/Y_ifty2l6Fc CELERYD_PREFETCH_MULTIPLIER=1 # List of modules to import when celery starts. CELERY_IMPORTS = ("tasks",) CELERY_ANNOTATIONS = { 'celery.chord_unlock': {'soft_time_limit': 60} # 1 minute }
import os import sys import urlparse from kombu import Exchange, Queue sys.path.append('.') redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/") if not redis_url.endswith("/"): redis_url += "/" BROKER_URL = redis_url + "1" # REDIS_CELERY_TASKS_DATABASE_NUMBER = 1 CELERY_RESULT_BACKEND = redis_url + "2" # REDIS_CELERY_RESULTS_DATABASE_NUMBER = 2 REDIS_CONNECT_RETRY = True # these options will be defaults in future as per http://celery.readthedocs.org/en/latest/getting-started/brokers/redis.html BROKER_TRANSPORT_OPTIONS = {'fanout_prefix': True, 'fanout_patterns': True, 'visibility_timeout': 60 # one minute } CELERY_DEFAULT_QUEUE = 'core_high' CELERY_QUEUES = [ Queue('core_high', routing_key='core_high'), Queue('core_low', routing_key='core_low') ] # added because https://github.com/celery/celery/issues/896 BROKER_POOL_LIMIT = None CELERY_CREATE_MISSING_QUEUES = True CELERY_ACCEPT_CONTENT = ['pickle', 'json'] CELERY_ENABLE_UTC = True CELERY_TASK_RESULT_EXPIRES = 60*60 # 1 hour CELERY_ACKS_LATE = True # remove this, might fix deadlocks as per https://github.com/celery/celery/issues/970 # CELERYD_MAX_TASKS_PER_CHILD = 100 CELERYD_FORCE_EXECV = True CELERY_TRACK_STARTED = True # https://groups.google.com/forum/#!topic/celery-users/Y_ifty2l6Fc CELERYD_PREFETCH_MULTIPLIER=1 # List of modules to import when celery starts. CELERY_IMPORTS = ("tasks",) CELERY_ANNOTATIONS = { 'celery.chord_unlock': {'soft_time_limit': 60} # 1 minute }
Python
0
3abbba864df16e06a768b761baefd3d705008114
Update vigenereCipher: fixed typo
books/CrackingCodesWithPython/Chapter18/vigenereCipher.py
books/CrackingCodesWithPython/Chapter18/vigenereCipher.py
# Vigenere Cipher (Polyalphabetic Substitution Cipher) # https://www.nostarch.com/crackingcodes/ (BSD Licensed) from books.CrackingCodesWithPython.pyperclip import copy LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): # This text can be downloaded from https://www.nostarch.com/crackingcodes/: myMessage = """Alan Mathison Turing was a British mathematician, logician, cryptanalyst, and computer scientist.""" myKey = 'ASIMOV' myMode = 'encrypt' # Set to either 'encrypt' or 'decrypt'. if myMode == 'encrypt': translated = encryptMessage(myKey, myMessage) elif myMode == 'decrypt': translated = decryptMessage(myKey, myMessage) print('%sed message:' % (myMode.title())) print(translated) copy(translated) print() print('The message has been copied to the clipboard.') def encryptMessage(key, message): return translateMessage(key, message, 'encrypt') def decryptMessage(key, message): return translatedMessage(key, message, 'decrypt') def translateMessage(key, message, mode): translated = [] # Stores the encrypted/decrypted message string. keyIndex = 0 key = key.upper() for symbol in message: # Loop through each symbol in message. num = LETTERS.find(symbol.upper()) if num != -1: # -1 means symbol.upper() was not found in LETTERS. if mode == 'encrypt': num += LETTERS.find(key[keyIndex]) # Add if encrypting. elif mode == 'decrypt': num -= LETTERS.find(key[keyIndex]) # Subtract if decrypting. num %= len(LETTERS) # Handle any wraparound. # Add the encrypted/decrypted symbol to the end of translated: if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) keyIndex += 1 # Move to the next letter in the key. if keyIndex == len(key): keyIndex = 0 else: # Append the symbol without encrypting/decrypting: translated.append(symbol) return ''.join(translated) # If vigenereCipher.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
# Vigenere Cipher (Polyalphabetic Substitution Cipher) # https://www.nostarch.com/crackingcodes/ (BSD Licensed) from books.CrackingCodesWithPython.pyperclip import copy LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): # This text can be downloaded from https://www.nostarch.com/crackingcodes/: myMessage = """Alan Mathison Turing was a British mathematician, logician, cryptanalyst, and computer scientist.""" myKey = 'ASIMOV' myMode = 'encrypt' # Set to either 'encrypt' or 'decrypt'. if myMode == 'encrypt': translated = encryptMessage(myKey, myMessage) elif myMode == 'decrypt': translated = decryptMessage(myKey, myMessage) print('%sed message:' % (myMode.title())) print(translated) copy(translated) print() print('The message has been copied to the clipboard.') def encryptMessage(key, message): return translateMessage(key, message, 'encrypt') def decryptMessage(key, message): return translatedMessage(key, message, 'decrypt') def translateMessage(key, message, mode): translated = [] # Stores the encrypted/decrypted message string. keyIndex = 0 key = key.upper() for symbol in message: # Loop through each symbol in message. num = LETTERS.find(symbol.upper()) if num != -1: # -1 means symbol.upper() was not found in LETTERS. if mode == 'encrypt': num += LETTERS.find(key[keyIndex]) # Add if encrypting. elif mode == 'decrypt': num -= LETTERS.find(key[keyIndex]) # Subtract if decrypting. num %= len(LETTERS) # Handle any wraparound. # Add the encrypted/decrypted symbol to the end of translated: if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) keyIndex += 1 # Move to the next letter in the key. if keyIndex == len(key): keyIndex = 0 else: # Append the symbol without encrypting/decrypting: translated.append(symbol) return ''.join(translated) # If vigenereCipher.py is run (instead of imported as a module), call # the main() function: if __name__ = '__main__': main()
Python
0.000001
41126795dec28c8c81f225f65589ba7aa264b4a6
allow any test sample size for cold start scenario
polara/recommender/coldstart/data.py
polara/recommender/coldstart/data.py
from collections import namedtuple import numpy as np import pandas as pd from polara.recommender.data import RecommenderData class ItemColdStartData(RecommenderData): def __init__(self, *args, **kwargs): random_state = kwargs.pop('random_state', None) super(ItemColdStartData, self).__init__(*args, **kwargs) self._test_sample = 1 self._test_unseen_users = False self.random_state = random_state try: permute = self.random_state.permutation except AttributeError: permute = np.random.permutation # build unique items list to split them by folds itemid = self.fields.itemid self._unique_items = permute(self._data[itemid].unique()) def _split_test_index(self): userid = self.fields.userid itemid = self.fields.itemid item_idx = np.arange(len(self._unique_items)) cold_items_split = self._split_fold_index(item_idx, len(item_idx), self._test_fold, self._test_ratio) cold_items = self._unique_items[cold_items_split] cold_items_mask = self._data[itemid].isin(cold_items) return cold_items_mask def _split_data(self): assert self._test_ratio > 0 assert not self._test_unseen_users update_rule = super(ItemColdStartData, self)._split_data() if any(update_rule.values()): testset = self._sample_test_items() self._test = self._test._replace(testset=testset) return update_rule def _sample_test_items(self): userid = self.fields.userid itemid = self.fields.itemid test_split = self._test_split holdout = self.test.evalset user_has_cold_item = self._data[userid].isin(holdout[userid].unique()) sampled = super(ItemColdStartData, self)._sample_testset(user_has_cold_item, holdout.index) testset = (pd.merge(holdout[[userid, itemid]], sampled[[userid, itemid]], on=userid, how='inner', suffixes=('_cold', '')) .drop(userid, axis=1) .drop_duplicates() .sort_values('{}_cold'.format(itemid))) return testset def _sample_holdout(self, test_split): return self._data.loc[test_split, list(self.fields)] def _try_drop_unseen_test_items(self): # there will be no such items except cold-start items pass def _try_drop_invalid_test_users(self): # testset contains items only pass def _try_sort_test_data(self): # no need to sort by users pass def _assign_test_items_index(self): itemid = self.fields.itemid self._map_entity(itemid, self._test.testset) self._reindex_cold_items() # instead of trying to assign known items index def _assign_test_users_index(self): # skip testset as it doesn't contain users userid = self.fields.userid self._map_entity(userid, self._test.evalset) def _reindex_cold_items(self): itemid_cold = '{}_cold'.format(itemid) cold_item_index = self.reindex(self.test.testset, itemid_cold, inplace=True, sort=False) new_item_index = (namedtuple('ItemIndex', 'training cold_start') ._make([self.index.itemid, cold_item_index])) self.index = self.index._replace(itemid=new_item_index)
from collections import namedtuple import numpy as np import pandas as pd from polara.recommender.data import RecommenderData class ItemColdStartData(RecommenderData): def __init__(self, *args, **kwargs): random_state = kwargs.pop('random_state', None) super(ItemColdStartData, self).__init__(*args, **kwargs) self._test_sample = 1 self._test_unseen_users = False self.random_state = random_state try: permute = self.random_state.permutation except AttributeError: permute = np.random.permutation # build unique items list to split them by folds itemid = self.fields.itemid self._unique_items = permute(self._data[itemid].unique()) def _split_test_index(self): userid = self.fields.userid itemid = self.fields.itemid item_idx = np.arange(len(self._unique_items)) cold_items_split = self._split_fold_index(item_idx, len(item_idx), self._test_fold, self._test_ratio) cold_items = self._unique_items[cold_items_split] cold_items_mask = self._data[itemid].isin(cold_items) return cold_items_mask def _split_data(self): assert self._test_ratio > 0 assert self._test_sample > 1 assert not self._test_unseen_users update_rule = super(ItemColdStartData, self)._split_data() if any(update_rule.values()): testset = self._sample_test_items() self._test = self._test._replace(testset=testset) return update_rule def _sample_test_items(self): userid = self.fields.userid itemid = self.fields.itemid test_split = self._test_split holdout = self.test.evalset user_has_cold_item = self._data[userid].isin(holdout[userid].unique()) sampled = super(ItemColdStartData, self)._sample_testset(user_has_cold_item, holdout.index) testset = (pd.merge(holdout[[userid, itemid]], sampled[[userid, itemid]], on=userid, how='inner', suffixes=('_cold', '')) .drop(userid, axis=1) .drop_duplicates() .sort_values('{}_cold'.format(itemid))) return testset def _sample_holdout(self, test_split): return self._data.loc[test_split, list(self.fields)] def _try_drop_unseen_test_items(self): # there will be no such items except cold-start items pass def _try_drop_invalid_test_users(self): # testset contains items only pass def _try_sort_test_data(self): # no need to sort by users pass def _assign_test_items_index(self): itemid = self.fields.itemid self._map_entity(itemid, self._test.testset) self._reindex_cold_items() # instead of trying to assign known items index def _assign_test_users_index(self): # skip testset as it doesn't contain users userid = self.fields.userid self._map_entity(userid, self._test.evalset) def _reindex_cold_items(self): itemid_cold = '{}_cold'.format(itemid) cold_item_index = self.reindex(self.test.testset, itemid_cold, inplace=True, sort=False) new_item_index = (namedtuple('ItemIndex', 'training cold_start') ._make([self.index.itemid, cold_item_index])) self.index = self.index._replace(itemid=new_item_index)
Python
0
ae92abffcbe792d41ee7aafb08e59ba874f3a4c4
Fix migration dependencies
longclaw/basket/migrations/0003_auto_20170207_2053.py
longclaw/basket/migrations/0003_auto_20170207_2053.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-07 20:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('basket', '0001_initial'), ] operations = [ migrations.RenameField( model_name='basketitem', old_name='product', new_name='variant', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-07 20:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('basket', '0002_basketitem_product'), ] operations = [ migrations.RenameField( model_name='basketitem', old_name='product', new_name='variant', ), ]
Python
0.000013
4177655955f38eae919627bd75e0ee7a0c37c0c5
Simplify loading logger
calaccess_raw/management/commands/loadcalaccessrawfile.py
calaccess_raw/management/commands/loadcalaccessrawfile.py
import csv from django.db import connection from django.db.models.loading import get_model from django.core.management.base import LabelCommand from calaccess_raw.management.commands import CalAccessCommand class Command(CalAccessCommand, LabelCommand): help = 'Load a cleaned CalAccess file for a model into the database' args = '<model name>' # Trick for reformating date strings in source data so that they can # be gobbled up by MySQL. You'll see how below. date_sql = "DATE_FORMAT(str_to_date(@`%s`, '%%c/%%e/%%Y'), '%%Y-%%m-%%d')" def handle_label(self, label, **options): self.verbosity = options.get("verbosity") self.load(label) def load(self, model_name): """ Loads the source CSV for the provided model. """ if self.verbosity: self.log(" Loading %s" % model_name) model = get_model("calaccess_raw", model_name) csv_path = model.objects.get_csv_path() # Flush c = connection.cursor() c.execute('TRUNCATE TABLE %s' % model._meta.db_table) # Build the MySQL LOAD DATA INFILE command bulk_sql_load_part_1 = ''' LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES ( ''' % (csv_path, model._meta.db_table) infile = open(csv_path) csv_reader = csv.reader(infile) headers = csv_reader.next() infile.close() infile = open(csv_path) csv_record_cnt = len(infile.readlines()) - 1 infile.close() header_sql_list = [] date_set_list = [] for h in headers: # If it is a date field, we need to reformat the data # so that MySQL will properly parse it on the way in. if h in model.DATE_FIELDS: header_sql_list.append('@`%s`' % h) date_set_list.append( "`%s` = %s" % (h, self.date_sql % h) ) else: header_sql_list.append('`%s`' % h) bulk_sql_load = bulk_sql_load_part_1 + ','.join(header_sql_list) + ')' if date_set_list: bulk_sql_load += " set %s" % ",".join(date_set_list) # Run the query cnt = c.execute(bulk_sql_load) # Report back on how we did if self.verbosity: if cnt != csv_record_cnt: msg = ' Table Record count doesn\'t match CSV. \ Table: %s\tCSV: %s' self.failure(msg % ( cnt, csv_record_cnt, ))
import csv from django.db import connection from django.db.models.loading import get_model from django.core.management.base import LabelCommand from calaccess_raw.management.commands import CalAccessCommand class Command(CalAccessCommand, LabelCommand): help = 'Load a cleaned CalAccess file for a model into the database' args = '<model name>' # Trick for reformating date strings in source data so that they can # be gobbled up by MySQL. You'll see how below. date_sql = "DATE_FORMAT(str_to_date(@`%s`, '%%c/%%e/%%Y'), '%%Y-%%m-%%d')" def handle_label(self, label, **options): self.verbosity = options.get("verbosity") self.load(label) def load(self, model_name): """ Loads the source CSV for the provided model. """ if self.verbosity: self.log(" Loading %s" % model_name) model = get_model("calaccess_raw", model_name) csv_path = model.objects.get_csv_path() # Flush c = connection.cursor() c.execute('TRUNCATE TABLE %s' % model._meta.db_table) # Build the MySQL LOAD DATA INFILE command bulk_sql_load_part_1 = ''' LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES ( ''' % (csv_path, model._meta.db_table) infile = open(csv_path) csv_reader = csv.reader(infile) headers = csv_reader.next() infile.close() infile = open(csv_path) csv_record_cnt = len(infile.readlines()) - 1 infile.close() header_sql_list = [] date_set_list = [] for h in headers: # If it is a date field, we need to reformat the data # so that MySQL will properly parse it on the way in. if h in model.DATE_FIELDS: header_sql_list.append('@`%s`' % h) date_set_list.append( "`%s` = %s" % (h, self.date_sql % h) ) else: header_sql_list.append('`%s`' % h) bulk_sql_load = bulk_sql_load_part_1 + ','.join(header_sql_list) + ')' if date_set_list: bulk_sql_load += " set %s" % ",".join(date_set_list) # Run the query cnt = c.execute(bulk_sql_load) # Report back on how we did if self.verbosity: if cnt == csv_record_cnt: self.success(" Table record count matches CSV") else: msg = ' Table Record count doesn\'t match CSV. \ Table: %s\tCSV: %s' self.failure(msg % ( cnt, csv_record_cnt, ))
Python
0.000025
20003796eb8f3949d931a4b8752fb07f2be39136
Update utils.py
church/utils.py
church/utils.py
from functools import lru_cache from os.path import ( join, dirname, abspath ) PATH = abspath(join(dirname(__file__), 'data')) @lru_cache(maxsize=None) def pull(filename, lang='en_us'): """ Function for getting data from text files in data/ 1. de_de - Folder for Germany. 2. en_us - Folder for United States 3. ru_ru - Folder for Russian Federation. """ with open(join(PATH + '/' + lang, filename), 'r') as f: _result = f.readlines() return _result
from functools import lru_cache from os.path import ( join, dirname, abspath ) PATH = abspath(join(dirname(__file__), 'data')) __all__ = ['priest'] @lru_cache(maxsize=None) def pull(filename, lang='en_us'): """ Function for getting data from text files in data/ 1. de_de - Folder for Germany. 2. en_us - Folder for United States 3. ru_ru - Folder for Russian Federation. """ with open(join(PATH + '/' + lang, filename), 'r') as f: _result = f.readlines() return _result
Python
0.000001
3c978eab962ed8a6158df2266852a1b1a47c4ec7
add more terminal nodes
gdcdatamodel/query.py
gdcdatamodel/query.py
from psqlgraph import Node, Edge traversals = {} terminal_nodes = ['annotations', 'centers', 'archives', 'tissue_source_sites', 'files', 'related_files', 'describing_files', 'clinical_metadata_files', 'experiment_metadata_files', 'run_metadata_files', 'analysis_metadata_files', 'biospecimen_metadata_files', 'aligned_reads_metrics', 'read_group_metrics', 'pathology_reports', 'simple_germline_variations', 'aligned_reads_indexes', 'mirna_expressions', 'exon_expressions', 'simple_somatic_mutations', 'gene_expressions', 'aggregated_somatic_mutations', ] def construct_traversals(root, node, visited, path): recurse = lambda neighbor: ( neighbor # no backtracking and neighbor not in visited and neighbor != node # no traveling THROUGH terminal nodes and (path[-1] not in terminal_nodes if path else neighbor.label not in terminal_nodes) and (not path[-1].startswith('_related') if path else not neighbor.label.startswith('_related'))) for edge in Edge._get_edges_with_src(node.__name__): neighbor = [n for n in Node.get_subclasses() if n.__name__ == edge.__dst_class__][0] if recurse(neighbor): construct_traversals( root, neighbor, visited+[node], path+[edge.__src_dst_assoc__]) for edge in Edge._get_edges_with_dst(node.__name__): neighbor = [n for n in Node.get_subclasses() if n.__name__ == edge.__src_class__][0] if recurse(neighbor): construct_traversals( root, neighbor, visited+[node], path+[edge.__dst_src_assoc__]) traversals[root][node.label] = traversals[root].get(node.label) or set() traversals[root][node.label].add('.'.join(path)) for node in Node.get_subclasses(): traversals[node.label] = {} construct_traversals(node.label, node, [node], []) def union_subq_without_path(q, *args, **kwargs): return q.except_(union_subq_path(q, *args, **kwargs)) def union_subq_path(q, dst_label, post_filters=[]): src_label = q.entity().label if not traversals.get(src_label, {}).get(dst_label, {}): return q paths = list(traversals[src_label][dst_label]) base = q.subq_path(paths.pop(), post_filters) while paths: base = base.union(q.subq_path(paths.pop(), post_filters)) return base
from psqlgraph import Node, Edge traversals = {} terminal_nodes = ['annotations', 'centers', 'archives', 'tissue_source_sites', 'files', 'related_files', 'describing_files'] def construct_traversals(root, node, visited, path): recurse = lambda neighbor: ( neighbor # no backtracking and neighbor not in visited and neighbor != node # no traveling THROUGH terminal nodes and (path[-1] not in terminal_nodes if path else neighbor.label not in terminal_nodes)) for edge in Edge._get_edges_with_src(node.__name__): neighbor = [n for n in Node.get_subclasses() if n.__name__ == edge.__dst_class__][0] if recurse(neighbor): construct_traversals( root, neighbor, visited+[node], path+[edge.__src_dst_assoc__]) for edge in Edge._get_edges_with_dst(node.__name__): neighbor = [n for n in Node.get_subclasses() if n.__name__ == edge.__src_class__][0] if recurse(neighbor): construct_traversals( root, neighbor, visited+[node], path+[edge.__dst_src_assoc__]) traversals[root][node.label] = traversals[root].get(node.label) or set() traversals[root][node.label].add('.'.join(path)) for node in Node.get_subclasses(): traversals[node.label] = {} construct_traversals(node.label, node, [node], []) def union_subq_without_path(q, *args, **kwargs): return q.except_(union_subq_path(q, *args, **kwargs)) def union_subq_path(q, dst_label, post_filters=[]): src_label = q.entity().label if not traversals.get(src_label, {}).get(dst_label, {}): return q paths = list(traversals[src_label][dst_label]) base = q.subq_path(paths.pop(), post_filters) while paths: base = base.union(q.subq_path(paths.pop(), post_filters)) return base
Python
0
7c6c8e9ed2b89c7fa15992b5b68c793a53b327d8
fix test case to run on_commit hook before assertion
django_datawatch/tests/test_trigger_update.py
django_datawatch/tests/test_trigger_update.py
# -*- coding: UTF-8 -*- from __future__ import unicode_literals, print_function try: from unittest import mock except ImportError: import mock from django.db import transaction from django.test.testcases import TestCase, override_settings from django_datawatch.backends.base import BaseBackend from django_datawatch.datawatch import datawatch, run_checks from django_datawatch.base import BaseCheck from django_datawatch.models import Result @datawatch.register class CheckTriggerUpdate(BaseCheck): model_class = Result trigger_update = dict(foobar=Result) def get_foobar_payload(self, instance): return instance def get_identifier(self, payload): return payload.pk def check(self, payload): return payload class TriggerUpdateTestCase(TestCase): @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=True) @mock.patch('django_datawatch.datawatch.DatawatchHandler.update_related') def test_setting_run_signals_true(self, mock_update): run_checks(sender=None, instance=None, created=None, raw=None, using=None) self.assertTrue(mock_update.called) @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=False) @mock.patch('django_datawatch.datawatch.DatawatchHandler.update_related') def test_setting_run_signals_false(self, mock_update): run_checks(sender=None, instance=None, created=None, raw=None, using=None) self.assertFalse(mock_update.called) def run_commit_hooks(self): """ Fake transaction commit to run delayed on_commit functions source: https://medium.com/@juan.madurga/speed-up-django-transaction-hooks-tests-6de4a558ef96 """ for db_name in reversed(self._databases_names()): with mock.patch('django.db.backends.base.base.BaseDatabaseWrapper.validate_no_atomic_block', lambda a: False): transaction.get_connection(using=db_name).run_and_clear_commit_hooks() @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=True) @mock.patch('django_datawatch.datawatch.DatawatchHandler.get_backend') def test_update_related_calls_backend(self, mock_get_backend): backend = mock.Mock(spec=BaseBackend) mock_get_backend.return_value = backend datawatch.update_related(sender=Result, instance=Result()) # run our on_commit hook self.run_commit_hooks() # make sure that we called backend.run self.assertTrue(backend.run.called)
# -*- coding: UTF-8 -*- from __future__ import unicode_literals, print_function from django_datawatch.backends.base import BaseBackend try: from unittest import mock except ImportError: import mock from django.test.testcases import TestCase, override_settings from django_datawatch.datawatch import datawatch, run_checks from django_datawatch.base import BaseCheck from django_datawatch.models import Result @datawatch.register class CheckTriggerUpdate(BaseCheck): model_class = Result trigger_update = dict(foobar=Result) def get_foobar_payload(self, instance): return instance def get_identifier(self, payload): return payload.pk def check(self, payload): return payload class TriggerUpdateTestCase(TestCase): @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=True) @mock.patch('django_datawatch.datawatch.DatawatchHandler.update_related') def test_setting_run_signals_true(self, mock_update): run_checks(sender=None, instance=None, created=None, raw=None, using=None) self.assertTrue(mock_update.called) @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=False) @mock.patch('django_datawatch.datawatch.DatawatchHandler.update_related') def test_setting_run_signals_false(self, mock_update): run_checks(sender=None, instance=None, created=None, raw=None, using=None) self.assertFalse(mock_update.called) @override_settings(DJANGO_DATAWATCH_RUN_SIGNALS=True) @mock.patch('django_datawatch.datawatch.DatawatchHandler.get_backend') def test_update_related_calls_backend(self, mock_get_backend): backend = mock.Mock(spec=BaseBackend) mock_get_backend.return_value = backend datawatch.update_related(sender=Result, instance=Result()) self.assertTrue(backend.run.called)
Python
0.000001
26549566bc502dece76ad596126b219dc5c8991c
Fix for IPv6 Python sockets binding localhost problem
lib/py/src/transport/TSocket.py
lib/py/src/transport/TSocket.py
#!/usr/bin/env python # # Copyright (c) 2006- Facebook # Distributed under the Thrift Software License # # See accompanying file LICENSE or visit the Thrift site at: # http://developers.facebook.com/thrift/ from TTransport import * import socket class TSocket(TTransportBase): """Socket implementation of TTransport base.""" def __init__(self, host='localhost', port=9090): self.host = host self.port = port self.handle = None def setHandle(self, h): self.handle = h def isOpen(self): return self.handle != None def setTimeout(self, ms): if (self.handle != None): self.handle.settimeout(ms/1000.00) else: raise TTransportException(TTransportException.NOT_OPEN, 'No handle yet in TSocket') def open(self): try: res0 = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) for res in res0: self.handle = socket.socket(res[0], res[1]) try: self.handle.connect(res[4]) except socket.error, e: if res is not res0[-1]: continue else: raise e break except socket.error, e: raise TTransportException(TTransportException.NOT_OPEN, 'Could not connect to %s:%d' % (self.host, self.port)) def close(self): if self.handle != None: self.handle.close() self.handle = None def read(self, sz): buff = self.handle.recv(sz) if len(buff) == 0: raise TTransportException('TSocket read 0 bytes') return buff def write(self, buff): sent = 0 have = len(buff) while sent < have: plus = self.handle.send(buff) if plus == 0: raise TTransportException('TSocket sent 0 bytes') sent += plus buff = buff[plus:] def flush(self): pass class TServerSocket(TServerTransportBase): """Socket implementation of TServerTransport base.""" def __init__(self, port): self.port = port self.handle = None def listen(self): res0 = socket.getaddrinfo(None, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) for res in res0: if res[0] is socket.AF_INET6 or res is res0[-1]: break self.handle = socket.socket(res[0], res[1]) self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(self.handle, 'set_timeout'): self.handle.set_timeout(None) self.handle.bind(res[4]) self.handle.listen(128) def accept(self): (client, addr) = self.handle.accept() result = TSocket() result.setHandle(client) return result def close(self): self.handle.close() self.handle = None
#!/usr/bin/env python # # Copyright (c) 2006- Facebook # Distributed under the Thrift Software License # # See accompanying file LICENSE or visit the Thrift site at: # http://developers.facebook.com/thrift/ from TTransport import * import socket class TSocket(TTransportBase): """Socket implementation of TTransport base.""" def __init__(self, host='localhost', port=9090): self.host = host self.port = port self.handle = None def setHandle(self, h): self.handle = h def isOpen(self): return self.handle != None def setTimeout(self, ms): if (self.handle != None): self.handle.settimeout(ms/1000.00) else: raise TTransportException(TTransportException.NOT_OPEN, 'No handle yet in TSocket') def open(self): try: res0 = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) for res in res0: self.handle = socket.socket(res[0], res[1]) try: self.handle.connect(res[4]) except socket.error, e: if res is not res0[-1]: continue else: raise e break except socket.error, e: raise TTransportException(TTransportException.NOT_OPEN, 'Could not connect to %s:%d' % (self.host, self.port)) def close(self): if self.handle != None: self.handle.close() self.handle = None def read(self, sz): buff = self.handle.recv(sz) if len(buff) == 0: raise TTransportException('TSocket read 0 bytes') return buff def write(self, buff): sent = 0 have = len(buff) while sent < have: plus = self.handle.send(buff) if plus == 0: raise TTransportException('TSocket sent 0 bytes') sent += plus buff = buff[plus:] def flush(self): pass class TServerSocket(TServerTransportBase): """Socket implementation of TServerTransport base.""" def __init__(self, port): self.port = port self.handle = None def listen(self): res0 = socket.getaddrinfo(None, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) for res in res0: if res[0] is socket.AF_INET6 or res is res0[-1]: break self.handle = socket.socket(res[0], res[1]) self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(self.handle, 'set_timeout'): self.handle.set_timeout(None) self.handle.bind(res[4]) self.handle.listen(128) def accept(self): (client, addr) = self.handle.accept() result = TSocket() result.setHandle(client) return result def close(self): self.handle.close() self.handle = None
Python
0.000001
2323699ae6b266823b30784293b2d1d900d94700
Bump aioTV version.
rest_framework_swagger/__init__.py
rest_framework_swagger/__init__.py
VERSION = '0.3.5-aio-v3' DEFAULT_SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_key': '', 'token_type': 'Token', 'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'], 'is_authenticated': False, 'is_superuser': False, 'permission_denied_handler': None, 'resource_access_handler': None, 'template_path': 'rest_framework_swagger/index.html', 'doc_expansion': 'none', 'base_path': '' } try: from django.conf import settings from django.test.signals import setting_changed def load_settings(provided_settings): global SWAGGER_SETTINGS SWAGGER_SETTINGS = provided_settings for key, value in DEFAULT_SWAGGER_SETTINGS.items(): if key not in SWAGGER_SETTINGS: SWAGGER_SETTINGS[key] = value def reload_settings(*args, **kwargs): setting, value = kwargs['setting'], kwargs['value'] if setting == 'SWAGGER_SETTINGS': load_settings(value) load_settings(getattr(settings, 'SWAGGER_SETTINGS', DEFAULT_SWAGGER_SETTINGS)) setting_changed.connect(reload_settings) except: SWAGGER_SETTINGS = DEFAULT_SWAGGER_SETTINGS
VERSION = '0.3.5-aio-v2' DEFAULT_SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_key': '', 'token_type': 'Token', 'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'], 'is_authenticated': False, 'is_superuser': False, 'permission_denied_handler': None, 'resource_access_handler': None, 'template_path': 'rest_framework_swagger/index.html', 'doc_expansion': 'none', 'base_path': '' } try: from django.conf import settings from django.test.signals import setting_changed def load_settings(provided_settings): global SWAGGER_SETTINGS SWAGGER_SETTINGS = provided_settings for key, value in DEFAULT_SWAGGER_SETTINGS.items(): if key not in SWAGGER_SETTINGS: SWAGGER_SETTINGS[key] = value def reload_settings(*args, **kwargs): setting, value = kwargs['setting'], kwargs['value'] if setting == 'SWAGGER_SETTINGS': load_settings(value) load_settings(getattr(settings, 'SWAGGER_SETTINGS', DEFAULT_SWAGGER_SETTINGS)) setting_changed.connect(reload_settings) except: SWAGGER_SETTINGS = DEFAULT_SWAGGER_SETTINGS
Python
0
00bf40ba386d7d1ffebcc1a41766250e0fc975ac
Add related name fields
src/core/models/base.py
src/core/models/base.py
from django.db import models from django.contrib.auth.models import User class Location(models.Model): class Meta: app_label = "core" x = models.DecimalField(max_digits=10, decimal_places=5) y = models.DecimalField(max_digits=10, decimal_places=5) def __str__(self): return "x:" + str(self.x) + ", y:" + str(self.y) class Idea(models.Model): class Meta: app_label = "core" time = models.DateTimeField(null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True, related_name='ideas') owner = models.ForeignKey(User, related_name='ideas') users = models.ManyToManyField(User, through='Suggestion', related_name='idea_suggestions') activity = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.owner) + ":" + str(self.activity) + " @ " + str(self.location) + ", " + str(self.time) class Suggestion(models.Model): class Meta: app_label = "core" YES = 'Y' NO = 'N' MAYBE = 'M' NONE = 'O' RESPONSE_CHOICES = ( (YES, 'Yes'), (NO, 'No'), (MAYBE, 'Maybe'), (NONE, 'No vote'), ) response = models.CharField(max_length=1, choices=RESPONSE_CHOICES, default=NONE) user = models.ForeignKey(User, related_name='suggestions') idea = models.ForeignKey(Idea, related_name='suggestions') def __str__(self): return str(self.user) + ":" + str(self.suggestion) class Event(models.Model): class Meta: app_label = "core" owner = models.ForeignKey(User, related_name='events') invites = models.ManyToManyField(User, through='Invite', related_name='event_invites') description = models.TextField() location = models.ForeignKey(Location, related_name='events') start_time = models.DateTimeField() end_time = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.owner) + ":" + str(self.location) + "@" + str(self.start_time) class Invite(models.Model): class Meta: app_label = "core" YES = 'Y' NO = 'N' MAYBE_YES = 'MY' MAYBE_NO = 'MN' NONE = 'O' RSVP_CHOICES = ( (YES, 'Yes'), (NO, 'No'), (MAYBE_YES, 'Maybe Yes'), (MAYBE_NO, 'Maybe No'), (NONE, 'No response'), ) event = models.ForeignKey(Event, related_name='invites') user = models.ForeignKey(User, related_name='invites') rsvp = models.CharField(max_length=2, choices=RSVP_CHOICES, default=NONE) def __str__(self): return str(user) + ":" + str(event)
from django.db import models from django.contrib.auth.models import User class Location(models.Model): class Meta: app_label = "core" x = models.DecimalField(max_digits=10, decimal_places=5) y = models.DecimalField(max_digits=10, decimal_places=5) def __str__(self): return "x:" + str(self.x) + ", y:" + str(self.y) class Idea(models.Model): class Meta: app_label = "core" time = models.DateTimeField(null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True) owner = models.ForeignKey(User, related_name='idea_owner') users = models.ManyToManyField(User, through='Suggestion') activity = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.owner) + ":" + str(self.activity) + " @ " + str(self.location) + ", " + str(self.time) class Suggestion(models.Model): class Meta: app_label = "core" YES = 'Y' NO = 'N' MAYBE = 'M' NONE = 'O' RESPONSE_CHOICES = ( (YES, 'Yes'), (NO, 'No'), (MAYBE, 'Maybe'), (NONE, 'No vote'), ) response = models.CharField(max_length=1, choices=RESPONSE_CHOICES, default=NONE) user = models.ForeignKey(User) idea = models.ForeignKey(Idea) def __str__(self): return str(self.user) + ":" + str(self.suggestion) class Event(models.Model): class Meta: app_label = "core" owner = models.ForeignKey(User, related_name='event_owner') invites = models.ManyToManyField(User, through='Invite') description = models.TextField() location = models.ForeignKey(Location) start_time = models.DateTimeField() end_time = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.owner) + ":" + str(self.location) + "@" + str(self.start_time) class Invite(models.Model): class Meta: app_label = "core" YES = 'Y' NO = 'N' MAYBE_YES = 'MY' MAYBE_NO = 'MN' NONE = 'O' RSVP_CHOICES = ( (YES, 'Yes'), (NO, 'No'), (MAYBE_YES, 'Maybe Yes'), (MAYBE_NO, 'Maybe No'), (NONE, 'No response'), ) event = models.ForeignKey(Event) user = models.ForeignKey(User) rsvp = models.CharField(max_length=2, choices=RSVP_CHOICES, default=NONE) def __str__(self): return str(user) + ":" + str(event)
Python
0.000001
2edb2145f6f7447a7c659d7eeb51c7b75aa0c6d4
Add generate username signal
rhinocloud/contrib/auth/signals.py
rhinocloud/contrib/auth/signals.py
from django.contrib.auth.models import User from rhinocloud.utils import random_generator def generate_username_from_email(sender, instance, **kwargs): if sender == User: username = instance.email if len(username) > 30: username = random_generator(username[:25]) instance.username = username def username_shorten(sender, instance, **kwargs): if sender == User: if len(instance.username) > 30: instance.username = random_generator(instance.username[:25]) def first_name_shorten(sender, instance, **kwargs): if sender == User: if len(instance.first_name) > 30: instance.first_name = instance.first_name[:30] def last_name_shorten(sender, instance, **kwargs): if sender == User: if len(instance.username) > 30: instance.last_name = instance.last_name[:30]
from django.contrib.auth.models import User from rhinocloud.utils import random_generator def username_shorten(sender, instance, **kwargs): if sender == User: if len(instance.username) > 30: instance.username = random_generator(instance.username[:25]) def first_name_shorten(sender, instance, **kwargs): if sender == User: if len(instance.first_name) > 30: instance.first_name = instance.first_name[:30] def last_name_shorten(sender, instance, **kwargs): if sender == User: if len(instance.username) > 30: instance.last_name = instance.last_name[:30]
Python
0.000297
916638e11ef20e2976c81f0e8230079cf96a3c3a
Set DJANGO_SETTINGS_MODULE env variable.
ibms_project/wsgi.py
ibms_project/wsgi.py
""" WSGI config for IBMS project. It exposes the WSGI callable as a module-level variable named ``application``. """ import dotenv from django.core.wsgi import get_wsgi_application import os from pathlib import Path # These lines are required for interoperability between local and container environments. d = Path(__file__).resolve().parents[1] dot_env = os.path.join(str(d), '.env') if os.path.exists(dot_env): dotenv.read_dotenv(dot_env) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ibms_project.settings") application = get_wsgi_application()
""" WSGI config for IBMS project. It exposes the WSGI callable as a module-level variable named ``application``. """ import dotenv from django.core.wsgi import get_wsgi_application import os from pathlib import Path # These lines are required for interoperability between local and container environments. d = Path(__file__).resolve().parents[1] dot_env = os.path.join(str(d), '.env') if os.path.exists(dot_env): dotenv.read_dotenv(dot_env) application = get_wsgi_application()
Python
0
2636d76fa4d9dd820fd673bc6044f4c3ccdfd0b1
Fix permissions fixture problem.
src/encoded/tests/test_permissions.py
src/encoded/tests/test_permissions.py
import pytest @pytest.fixture def users(testapp): from .sample_data import URL_COLLECTION url = '/labs/' for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) url = '/awards/' for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) url = '/users/' users = [] for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) users.append(res.json['@graph'][0]) return users @pytest.fixture def wrangler(users, app, external_tx, zsa_savepoints): user = [u for u in users if 'wrangler' in u['groups']][0] from webtest import TestApp environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': str(user['uuid']), } return TestApp(app, environ) @pytest.fixture def submitter(users, app, external_tx, zsa_savepoints): user = [u for u in users if not u['groups']][0] from webtest import TestApp environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': str(user['uuid']), } return TestApp(app, environ) @pytest.fixture def lab(): return 'b635b4ed-dba3-4672-ace9-11d76a8d03af' @pytest.fixture def award(): return 'Myers' @pytest.mark.parametrize('url', ['/organisms/', '/sources/']) def test_wrangler_post_non_lab_collection(wrangler, url): from .sample_data import URL_COLLECTION collection = URL_COLLECTION[url] for item in collection: res = wrangler.post_json(url, item, status=201) assert item['name'] in res.location @pytest.mark.parametrize('url', ['/organisms/', '/sources/']) def test_submitter_post_non_lab_collection(submitter, url): from .sample_data import URL_COLLECTION collection = URL_COLLECTION[url] for item in collection: item = item.copy() del item['uuid'] submitter.post_json(url, item, status=403) def test_submitter_post_update_experiment(submitter, lab, award): experiment = {'lab': lab, 'award': award} res = submitter.post_json('/experiment/', experiment, status=201) location = res.location res = submitter.get(location + '@@testing-allowed?permission=edit', status=200) assert res.json['has_permission'] is True assert 'submits_for.%s' % lab in res.json['principals_allowed_by_permission'] submitter.patch_json(location, {'description': 'My experiment'}, status=200)
import pytest @pytest.datafixture def users(app): from webtest import TestApp environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': 'TEST', } testapp = TestApp(app, environ) from .sample_data import URL_COLLECTION url = '/labs/' for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) url = '/awards/' for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) url = '/users/' users = [] for item in URL_COLLECTION[url]: res = testapp.post_json(url, item, status=201) users.append(res.json['@graph'][0]) return users @pytest.fixture def wrangler(users, app, external_tx, zsa_savepoints): user = [u for u in users if 'wrangler' in u['groups']][0] from webtest import TestApp environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': str(user['uuid']), } return TestApp(app, environ) @pytest.fixture def submitter(users, app, external_tx, zsa_savepoints): user = [u for u in users if not u['groups']][0] from webtest import TestApp environ = { 'HTTP_ACCEPT': 'application/json', 'REMOTE_USER': str(user['uuid']), } return TestApp(app, environ) @pytest.fixture def lab(): return 'b635b4ed-dba3-4672-ace9-11d76a8d03af' @pytest.fixture def award(): return 'Myers' @pytest.mark.parametrize('url', ['/organisms/', '/sources/']) def test_wrangler_post_non_lab_collection(wrangler, url): from .sample_data import URL_COLLECTION collection = URL_COLLECTION[url] for item in collection: res = wrangler.post_json(url, item, status=201) assert item['name'] in res.location @pytest.mark.parametrize('url', ['/organisms/', '/sources/']) def test_submitter_post_non_lab_collection(submitter, url): from .sample_data import URL_COLLECTION collection = URL_COLLECTION[url] for item in collection: item = item.copy() del item['uuid'] submitter.post_json(url, item, status=403) def test_submitter_post_update_experiment(submitter, lab, award): experiment = {'lab': lab, 'award': award} res = submitter.post_json('/experiment/', experiment, status=201) location = res.location res = submitter.get(location + '@@testing-allowed?permission=edit', status=200) assert res.json['has_permission'] is True assert 'submits_for.%s' % lab in res.json['principals_allowed_by_permission'] submitter.patch_json(location, {'description': 'My experiment'}, status=200)
Python
0
1a6c6228927b343071d0fc5e1959920bf30e6252
clean up
darkoob/social/models.py
darkoob/social/models.py
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from neomodel import StructuredNode, IntegerProperty, RelationshipTo, RelationshipFrom from darkoob.book.models import Quote, Book import datetime from django.utils.timezone import utc SEX_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) class UserNode(StructuredNode): user_id = IntegerProperty(required=True, index=True) following = RelationshipTo('UserNode', 'FOLLOW') followers = RelationshipFrom('UserNode', 'FOLLOW') def follow_person(self, user_id): ''' follow person that user.id=user_id''' followed_user = self.index.get(user_id=user_id) self.following.connect(followed_user, {'time': str(datetime.datetime.utcnow())}) def is_following(self, user_id): ''' return True if user in self.following.all() else False ''' user = self.index.get(user_id=user_id) return True if user in self.following.all() else False def is_followers(self, user_id): ''' return True if user in self.followers.all() else False ''' user = self.index.get(user_id=user_id) return True if user in self.followers.all() else False class Country(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class City(models.Model): name = models.CharField(max_length=50) country = models.OneToOneField(Country) def __unicode__(self): return self.name class UserProfile(models.Model): user = models.OneToOneField(User) sex = models.CharField(max_length=6, choices=SEX_CHOICES) birthday = models.DateField(null=True) mobile = models.CharField(max_length=20, null=True, blank=True) website = models.URLField(null=True, blank=True) city = models.OneToOneField(City, null=True, blank=True) quote = models.ForeignKey(Quote, null=True, blank=True) favorite_books = models.ManyToManyField(Book, null=True, blank=True) # for django model # def favorite_books(self): # return ', '.join([a.title for a in self.favorite_books.all()]) # favorite_books.short_description = "Favorite Book" # NOTE: userprof_obj.education_set.all() return all education set of a person # def get_related_migrations(self): # from darkoob.migration.models import Migration, Hop # print Hop.objects.filter(host=user) def __unicode__(self): return self.user.get_full_name() class School(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Education(models.Model): user_profile = models.ForeignKey(UserProfile, related_name='education_set') school = models.OneToOneField(School) def __unicode__(self): return unicode(self.school) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) UserNode(user_id=instance.id).save() print "a node with user_id %d created!" % instance.id post_save.connect(create_user_profile, sender=User)
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from neomodel import StructuredNode, IntegerProperty, RelationshipTo, RelationshipFrom from darkoob.book.models import Quote, Book import datetime from django.utils.timezone import utc SEX_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ) class UserNode(StructuredNode): user_id = IntegerProperty(required=True, index=True) following = RelationshipTo('UserNode', 'FOLLOW') followers = RelationshipFrom('UserNode', 'FOLLOW') def follow_person(self, user_id): followed_user = self.index.get(user_id=user_id) self.following.connect(followed_user, {'time': str(datetime.datetime.utcnow())}) def is_following(self, user_id): ''' return True if user in self.following.all() else False ''' user = self.index.get(user_id=user_id) return True if user in self.following.all() else False def is_followers(self, user_id): ''' return True if user in self.followers.all() else False ''' user = self.index.get(user_id=user_id) return True if user in self.followers.all() else False class Country(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class City(models.Model): name = models.CharField(max_length=50) country = models.OneToOneField(Country) def __unicode__(self): return self.name class UserProfile(models.Model): user = models.OneToOneField(User) sex = models.CharField(max_length=6, choices=SEX_CHOICES) birthday = models.DateField(null=True) mobile = models.CharField(max_length=20, null=True, blank=True) website = models.URLField(null=True, blank=True) city = models.OneToOneField(City, null=True, blank=True) quote = models.ForeignKey(Quote, null=True, blank=True) favorite_books = models.ManyToManyField(Book, null=True, blank=True) # for django model # def favorite_books(self): # return ', '.join([a.title for a in self.favorite_books.all()]) # favorite_books.short_description = "Favorite Book" # NOTE: userprof_obj.education_set.all() return all education set of a person # def get_related_migrations(self): # from darkoob.migration.models import Migration, Hop # print Hop.objects.filter(host=user) def __unicode__(self): return self.user.get_full_name() class School(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Education(models.Model): user_profile = models.ForeignKey(UserProfile, related_name='education_set') school = models.OneToOneField(School) def __unicode__(self): return unicode(self.school) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) UserNode(user_id=instance.id).save() print "a node with user_id %d created!" % instance.id post_save.connect(create_user_profile, sender=User)
Python
0.000001
d51a13ed70c157d90c2d77461ad1747f7ce12e7c
Improve comment syntax
openfisca_country_template/variables/taxes.py
openfisca_country_template/variables/taxes.py
# -*- coding: utf-8 -*- # This file defines the variables of our legislation. # A variable is property of a person, or an entity (e.g. a household). # See http://openfisca.org/doc/variables.html # Import from openfisca-core the common python objects used to code the legislation in OpenFisca from openfisca_core.model_api import * # Import the entities specifically defined for this tax and benefit system from openfisca_country_template.entities import * class income_tax(Variable): value_type = float entity = Person definition_period = MONTH label = u"Income tax" reference = "https://law.gov.example/income_tax" # Always use the most official source # The formula to compute the income tax for a given person at a given period def formula(person, period, parameters): return person('salary', period) * parameters(period).taxes.income_tax_rate class social_security_contribution(Variable): value_type = float entity = Person definition_period = MONTH label = u"Progressive contribution paid on salaries to finance social security" reference = "https://law.gov.example/social_security_contribution" # Always use the most official source def formula(person, period, parameters): salary = person('salary', period) # The social_security_contribution is computed according to a marginal scale. scale = parameters(period).taxes.social_security_contribution return scale.calc(salary) class housing_tax(Variable): value_type = float entity = Household definition_period = YEAR # This housing tax is defined for a year. label = u"Tax paid by each household proportionally to the size of its accommodation" reference = "https://law.gov.example/housing_tax" # Always use the most official source def formula(household, period, parameters): # The housing tax is defined for a year, but depends on the `accomodation_size` and `housing_occupancy_status` on the first month of the year. # Here period is a year. We can get the first month of a year with the following shortcut. # To build different periods, see http://openfisca.org/doc/coding-the-legislation/35_periods.html#calculating-dependencies-for-a-specific-period january = period.first_month accommodation_size = household('accomodation_size', january) # `housing_occupancy_status` is an Enum variable occupancy_status = household('housing_occupancy_status', january) HousingOccupancyStatus = occupancy_status.possible_values # Get the enum associated with the variable # To access an enum element, we use the `.` notation. tenant = (occupancy_status == HousingOccupancyStatus.tenant) owner = (occupancy_status == HousingOccupancyStatus.owner) # The tax is applied only if the household owns or rents its main residency return (owner + tenant) * accommodation_size * 10
# -*- coding: utf-8 -*- # This file defines the variables of our legislation. # A variable is property of a person, or an entity (e.g. a household). # See http://openfisca.org/doc/variables.html # Import from openfisca-core the common python objects used to code the legislation in OpenFisca from openfisca_core.model_api import * # Import the entities specifically defined for this tax and benefit system from openfisca_country_template.entities import * class income_tax(Variable): value_type = float entity = Person definition_period = MONTH label = u"Income tax" reference = "https://law.gov.example/income_tax" # Always use the most official source # The formula to compute the income tax for a given person at a given period def formula(person, period, parameters): return person('salary', period) * parameters(period).taxes.income_tax_rate class social_security_contribution(Variable): value_type = float entity = Person definition_period = MONTH label = u"Progressive contribution paid on salaries to finance social security" reference = "https://law.gov.example/social_security_contribution" # Always use the most official source def formula(person, period, parameters): salary = person('salary', period) # The social_security_contribution is computed according to a marginal scale. scale = parameters(period).taxes.social_security_contribution return scale.calc(salary) class housing_tax(Variable): value_type = float entity = Household definition_period = YEAR # This housing tax is defined for a year. label = u"Tax paid by each household proportionally to the size of its accommodation" reference = "https://law.gov.example/housing_tax" # Always use the most official source def formula(household, period, parameters): # The housing tax is defined for a year, but depends on the `accomodation_size` and `housing_occupancy_status` on the first month of the year. # Here period is a year. We can get the first month of a year with the following shortcut. # To build different periods, see http://openfisca.org/doc/coding-the-legislation/35_periods.html#calculating-dependencies-for-a-specific-period january = period.first_month accommodation_size = household('accomodation_size', january) # `housing_occupancy_status` is an Enum variable occupancy_status = household('housing_occupancy_status', january) HousingOccupancyStatus = occupancy_status.possible_values # Get the enum associated with the variable # To access an enum element, we use the . notation. tenant = (occupancy_status == HousingOccupancyStatus.tenant) owner = (occupancy_status == HousingOccupancyStatus.owner) # The tax is applied only if the household owns or rents its main residency return (owner + tenant) * accommodation_size * 10
Python
0.000015
da1df870f5d5b7703c4c4c3a6b8cb7d140778469
Set default task target to 100.
source/vistas/core/task.py
source/vistas/core/task.py
from threading import RLock class Task: STOPPED = 'stopped' RUNNING = 'running' INDETERMINATE = 'indeterminate' COMPLETE = 'complete' SHOULD_STOP = 'should_stop' tasks = [] def __init__(self, name, description=None, target=100, progress=0): self.name = name self.description = description self._target = target self._progress = progress self._status = self.STOPPED self.lock = RLock() Task.tasks.append(self) @property def stopped(self): return self._status == self.STOPPED @property def running(self): return self._status == self.RUNNING @property def indeterminate(self): return self._status == self.INDETERMINATE @property def complete(self): return self._status == self.COMPLETE @property def should_stop(self): return self._status == self.SHOULD_STOP @property def status(self): return self._status @status.setter def status(self, value): self._status = value if self.complete: Task.tasks.remove(self) @property def target(self): with self.lock: return self._target @target.setter def target(self, value): with self.lock: self._target = value @property def progress(self): with self.lock: return self._progress @progress.setter def progress(self, value): with self.lock: self._progress = value @property def percent(self): with self.lock: return int(self._progress / self._target * 100) def inc_target(self, increment=1): with self.lock: self._target += increment def inc_progress(self, increment=1): with self.lock: self._progress += increment
from threading import RLock class Task: STOPPED = 'stopped' RUNNING = 'running' INDETERMINATE = 'indeterminate' COMPLETE = 'complete' SHOULD_STOP = 'should_stop' tasks = [] def __init__(self, name, description=None, target=0, progress=0): self.name = name self.description = description self._target = target self._progress = progress self._status = self.STOPPED self.lock = RLock() Task.tasks.append(self) @property def stopped(self): return self._status == self.STOPPED @property def running(self): return self._status == self.RUNNING @property def indeterminate(self): return self._status == self.INDETERMINATE @property def complete(self): return self._status == self.COMPLETE @property def should_stop(self): return self._status == self.SHOULD_STOP @property def status(self): return self._status @status.setter def status(self, value): self._status = value if self.complete: Task.tasks.remove(self) @property def target(self): with self.lock: return self._target @target.setter def target(self, value): with self.lock: self._target = value @property def progress(self): with self.lock: return self._progress @progress.setter def progress(self, value): with self.lock: self._progress = value @property def percent(self): with self.lock: return int(self._progress / self._target * 100) def inc_target(self, increment=1): with self.lock: self._target += increment def inc_progress(self, increment=1): with self.lock: self._progress += increment
Python
0.00002
285d5f43b112354f1d5c05f9dd6b050e30f517e4
Remove country=DE parameter
geocoder/gisgraphy.py
geocoder/gisgraphy.py
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.location import BBox from geocoder.base import OneResult, MultipleResultsQuery class GisgraphyResult(OneResult): @property def lat(self): return self.raw.get('lat') @property def lng(self): return self.raw.get('lng') @property def address(self): return self.raw.get('formatedFull', '') @property def country(self): return self.raw.get('countryCode', '') @property def state(self): return self.raw.get('state', '') @property def city(self): return self.raw.get('city', '') @property def street(self): return self.raw.get('streetName', '') @property def housenumber(self): return self.raw.get('houseNumber', '') @property def postal(self): return self.raw.get('zipCode', '') class GisgraphyQuery(MultipleResultsQuery): """ Gisgraphy REST API ======================= API Reference ------------- http://www.gisgraphy.com/documentation/api/ """ provider = 'gisgraphy' method = 'geocode' _URL = 'https://services.gisgraphy.com/geocoding/' _RESULT_CLASS = GisgraphyResult _KEY_MANDATORY = False def _build_params(self, location, provider_key, **kwargs): return { 'address': location, 'to': kwargs.get('maxRows', 1), 'format': 'json', } def _adapt_results(self, json_response): return json_response['result'] if __name__ == '__main__': logging.basicConfig(level=logging.INFO) g = GisgraphyQuery('Ottawa Ontario', maxRows=3) g.debug()
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import logging from geocoder.location import BBox from geocoder.base import OneResult, MultipleResultsQuery class GisgraphyResult(OneResult): @property def lat(self): return self.raw.get('lat') @property def lng(self): return self.raw.get('lng') @property def address(self): return self.raw.get('formatedFull', '') @property def country(self): return self.raw.get('countryCode', '') @property def state(self): return self.raw.get('state', '') @property def city(self): return self.raw.get('city', '') @property def street(self): return self.raw.get('streetName', '') @property def housenumber(self): return self.raw.get('houseNumber', '') @property def postal(self): return self.raw.get('zipCode', '') class GisgraphyQuery(MultipleResultsQuery): """ Gisgraphy REST API ======================= API Reference ------------- http://www.gisgraphy.com/documentation/api/ """ provider = 'gisgraphy' method = 'geocode' _URL = 'https://services.gisgraphy.com/geocoding/' _RESULT_CLASS = GisgraphyResult _KEY_MANDATORY = False def _build_params(self, location, provider_key, **kwargs): return { 'address': location, 'to': kwargs.get('maxRows', 1), 'format': 'json', 'country': 'DE', } def _adapt_results(self, json_response): return json_response['result'] if __name__ == '__main__': logging.basicConfig(level=logging.INFO) g = GisgraphyQuery('Ottawa Ontario', maxRows=3) g.debug()
Python
0.00039
9f725eae63a7851498a82d3bc06414dc788c0ed7
Update comment style in admin.py
impersonate/admin.py
impersonate/admin.py
# -*- coding: utf-8 -*- '''Admin models for impersonate app.''' import logging from django.conf import settings from django.contrib import admin from .models import ImpersonationLog logger = logging.getLogger(__name__) MAX_FILTER_SIZE = getattr(settings, 'IMPERSONATE_MAX_FILTER_SIZE', 100) def friendly_name(user): '''Return proper name if exists, else username.''' if user.get_full_name() != '': return user.get_full_name() else: return user.username class SessionStateFilter(admin.SimpleListFilter): ''' Custom admin filter based on the session state. Provides two filter values - 'complete' and 'incomplete'. A session that has no session_ended_at timestamp is considered incomplete. This field is set from the session_end signal receiver. ''' title = 'session state' parameter_name = 'session' def lookups(self, request, model_admin): return ( ('incomplete', "Incomplete"), ('complete', "Complete") ) def queryset(self, request, queryset): if self.value() == 'incomplete': return queryset.filter(session_ended_at__isnull=True) if self.value() == 'complete': return queryset.filter(session_ended_at__isnull=False) else: return queryset class ImpersonatorFilter(admin.SimpleListFilter): ''' Custom admin filter based on the impersonator. Provides a set of users who have impersonated at some point. It is assumed that this is a small list of users - a subset of staff and superusers. There is no corresponding filter for users who have been impersonated, as this could be a very large set of users. If the number of unique impersonators exceeds MAX_FILTER_SIZE, then the filter is removed (shows only 'All'). ''' title = 'impersonator' parameter_name = 'impersonator' def lookups(self, request, model_admin): '''Return list of unique users who have been an impersonator.''' # the queryset containing the ImpersonationLog objects qs = model_admin.get_queryset(request).order_by('impersonator__first_name') # dedupe the impersonators impersonators = set([q.impersonator for q in qs]) if len(impersonators) > MAX_FILTER_SIZE: logger.debug( "Hiding admin list filter as number of impersonators " "exceeds MAX_FILTER_SIZE [%s]", len(impersonators), MAX_FILTER_SIZE ) return for i in impersonators: yield (i.id, friendly_name(i)) def queryset(self, request, queryset): if self.value() in (None, ''): return queryset else: return queryset.filter(impersonator_id=self.value()) class ImpersonationLogAdmin(admin.ModelAdmin): list_display = ( 'impersonator_', 'impersonating_', 'session_key', 'session_started_at', 'duration' ) readonly_fields = ( 'impersonator', 'impersonating', 'session_key', 'session_started_at', 'session_ended_at', 'duration' ) list_filter = (SessionStateFilter, ImpersonatorFilter, 'session_started_at') def impersonator_(self, obj): return friendly_name(obj.impersonator) def impersonating_(self, obj): return friendly_name(obj.impersonating) admin.site.register(ImpersonationLog, ImpersonationLogAdmin)
# -*- coding: utf-8 -*- '''Admin models for impersonate app.''' import logging from django.conf import settings from django.contrib import admin from .models import ImpersonationLog logger = logging.getLogger(__name__) MAX_FILTER_SIZE = getattr(settings, 'IMPERSONATE_MAX_FILTER_SIZE', 100) def friendly_name(user): '''Return proper name if exists, else username.''' if user.get_full_name() != '': return user.get_full_name() else: return user.username class SessionStateFilter(admin.SimpleListFilter): '''Custom admin filter based on the session state. Provides two filter values - 'complete' and 'incomplete'. A session that has no session_ended_at timestamp is considered incomplete. This field is set from the session_end signal receiver. ''' title = 'session state' parameter_name = 'session' def lookups(self, request, model_admin): return ( ('incomplete', "Incomplete"), ('complete', "Complete") ) def queryset(self, request, queryset): if self.value() == 'incomplete': return queryset.filter(session_ended_at__isnull=True) if self.value() == 'complete': return queryset.filter(session_ended_at__isnull=False) else: return queryset class ImpersonatorFilter(admin.SimpleListFilter): '''Custom admin filter based on the impersonator. Provides a set of users who have impersonated at some point. It is assumed that this is a small list of users - a subset of staff and superusers. There is no corresponding filter for users who have been impersonated, as this could be a very large set of users. If the number of unique impersonators exceeds MAX_FILTER_SIZE, then the filter is removed (shows only 'All'). ''' title = 'impersonator' parameter_name = 'impersonator' def lookups(self, request, model_admin): '''Return list of unique users who have been an impersonator.''' # the queryset containing the ImpersonationLog objects qs = model_admin.get_queryset(request).order_by('impersonator__first_name') # dedupe the impersonators impersonators = set([q.impersonator for q in qs]) if len(impersonators) > MAX_FILTER_SIZE: logger.debug( "Hiding admin list filter as number of impersonators " "exceeds MAX_FILTER_SIZE [%s]", len(impersonators), MAX_FILTER_SIZE ) return for i in impersonators: yield (i.id, friendly_name(i)) def queryset(self, request, queryset): if self.value() in (None, ''): return queryset else: return queryset.filter(impersonator_id=self.value()) class ImpersonationLogAdmin(admin.ModelAdmin): list_display = ( 'impersonator_', 'impersonating_', 'session_key', 'session_started_at', 'duration' ) readonly_fields = ( 'impersonator', 'impersonating', 'session_key', 'session_started_at', 'session_ended_at', 'duration' ) list_filter = (SessionStateFilter, ImpersonatorFilter, 'session_started_at') def impersonator_(self, obj): return friendly_name(obj.impersonator) def impersonating_(self, obj): return friendly_name(obj.impersonating) admin.site.register(ImpersonationLog, ImpersonationLogAdmin)
Python
0
6d9efe005e346aaef359f369c89d007da1b83189
add more untested changes for slack integration
lampeflaske.py
lampeflaske.py
#!/usr/bin/env python3 import pprint import os import lamper from flask import Flask, request, jsonify from flask_api import status app = Flask(__name__) @app.route("/", methods=['POST', 'GET']) def hello(): pprint.pprint(request.form) if request.form.get('command') != '/lamper': return "wrong command" , status.HTTP_400_BAD_REQUEST if request.form.get('team_id') != os.environ['SLACK_TEAMID']: return "wrong team id" , status.HTTP_403_FORBIDDEN if request.form.get('token') != os.environ['SLACK_TOKEN']: return "wrong token", status.HTTP_403_FORBIDDEN if request.form.get('channel_id') != os.environ['SLACK_CHANNELID']: return "wrong channel id", status.HTTP_403_FORBIDDEN if request.form.get('text') not in lamper.colors.keys(): return "wrong color" , status.HTTP_400_BAD_REQUEST lamper.set_dmx(lamper.colors[request.form.get('text')]) #return "Hello World! " + request.form.get('text') r = { 'response_type': 'in_channel', 'text': 'Light switched to {}'.format(request.form.get('text')), } return jsonify(r)
#!/usr/bin/env python3 import pprint import os import lamper from flask import Flask, request from flask_api import status app = Flask(__name__) @app.route("/", methods=['POST', 'GET']) def hello(): pprint.pprint(request.form) if request.form.get('command') != '/lamper': return "wrong command" , status.HTTP_400_BAD_REQUEST if request.form.get('team_id') != os.environ['SLACK_TEAMID']: return "wrong team id" , status.HTTP_403_FORBIDDEN if request.form.get('token') != os.environ['SLACK_TOKEN']: return "wrong token", status.HTTP_403_FORBIDDEN if request.form.get('channel_id') != os.environ['SLACK_CHANNELID']: return "wrong channel id", status.HTTP_403_FORBIDDEN if request.form.get('text') not in lamper.colors.keys(): return "wrong color" , status.HTTP_400_BAD_REQUEST lamper.set_dmx(lamper.colors[request.form.get('text')]) #return "Hello World! " + request.form.get('text') return """ { "response_type": "in_channel", "text": "Light switched to {}", "attachments": [ { "text":"Light switched to {}" } ] } """.format(request.form.get('text'))
Python
0
70aab65ba167cfd4e24452ca7dd03fe1cabaf6a1
create block on node2
test/functional/feature_asset_reorg.py
test/functional/feature_asset_reorg.py
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import SyscoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error, disconnect_nodes, connect_nodes class AssetReOrgTest(SyscoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [['-assetindex=1'],['-assetindex=1'],['-assetindex=1']] def run_test(self): self.nodes[0].generate(1) self.sync_blocks() self.nodes[2].generate(200) self.sync_blocks() disconnect_nodes(self.nodes[0], 1) disconnect_nodes(self.nodes[0], 2) self.basic_asset() # create fork self.nodes[0].generate(11) # won't exist on node 0 because it was created on node 2 and we are disconnected assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) self.nodes[2].generate(10) assetInfo = self.nodes[2].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) # still won't exist on node 0 yet assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) # connect and sync to longest chain now which does not include the asset connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) self.sync_blocks() assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[1].assetinfo, self.asset) assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[2].assetinfo, self.asset) # node 2 should have the asset in mempool again self.nodes[2].generate(1) self.sync_blocks() # asset is there now assetInfo = self.nodes[0].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) assetInfo = self.nodes[1].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) assetInfo = self.nodes[2].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) def basic_asset(self): self.asset = self.nodes[2].assetnew('1', 'TST', 'asset description', '0x', 8, '1000', '10000', 31, {})['asset_guid'] if __name__ == '__main__': AssetReOrgTest().main()
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import SyscoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error, disconnect_nodes, connect_nodes class AssetReOrgTest(SyscoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [['-assetindex=1'],['-assetindex=1'],['-assetindex=1']] def run_test(self): self.nodes[0].generate(1) self.sync_blocks() self.nodes[2].generate(200) self.sync_blocks() disconnect_nodes(self.nodes[0], 1) disconnect_nodes(self.nodes[0], 2) self.basic_asset() # create fork self.nodes[0].generate(11) # won't exist on node 0 because it was created on node 3 and we are disconnected assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) self.nodes[2].generate(10) assetInfo = self.nodes[2].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) # still won't exist on node 0 yet assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) # connect and sync to longest chain now which does not include the asset connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) self.sync_blocks() assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[0].assetinfo, self.asset) assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[1].assetinfo, self.asset) assert_raises_rpc_error(-20, 'Failed to read from asset DB', self.nodes[2].assetinfo, self.asset) self.nodes[0].generate(1) self.sync_blocks() # asset is there now assetInfo = self.nodes[0].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) assetInfo = self.nodes[1].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) assetInfo = self.nodes[2].assetinfo(self.asset) assert_equal(assetInfo['asset_guid'], self.asset) def basic_asset(self): self.asset = self.nodes[2].assetnew('1', 'TST', 'asset description', '0x', 8, '1000', '10000', 31, {})['asset_guid'] if __name__ == '__main__': AssetReOrgTest().main()
Python
0.000002
1f9dea20b433e5b2a69f348d1a842d71a99bc56e
Modify tests
tests/chainerx_tests/unit_tests/routines_tests/test_evaluation.py
tests/chainerx_tests/unit_tests/routines_tests/test_evaluation.py
import chainer from chainer import functions as F import numpy import chainerx from chainerx_tests import dtype_utils from chainerx_tests import op_utils _in_out_eval_dtypes = [ (('float16', 'int16'), 'float32'), (('float32', 'int32'), 'float32'), (('float64', 'int64'), 'float64'), (('float32', 'int16'), 'float32'), (('float64', 'int16'), 'float64'), (('float64', 'int32'), 'float64'), ] class EvalBase(op_utils.ChainerOpTest): def generate_inputs(self): x_dtype, t_dtype = self.in_dtypes y = numpy.random.uniform(-1, 1, self.x_shape).astype(x_dtype) targ = numpy.random.randint( 3, size=self.t_shape).astype(t_dtype) return y, targ def forward_chainerx(self, inputs): return self.forward_xp(inputs, chainerx) def forward_chainer(self, inputs): return self.forward_xp(inputs, F) def forward_xp(self, inputs, xp): raise NotImplementedError( 'Op test implementation must override `forward_xp`.') @op_utils.op_test(['native:0', 'cuda:0']) @chainer.testing.parameterize(*( chainer.testing.product([ chainer.testing.from_pytest_parameterize( 'x_shape,t_shape', [ ((10, 3), (10,)), ((10, 3, 1), (10,)), ((10, 3, 1, 1), (10,)), ((10, 3, 5), (10, 5)), ((10, 3, 5, 4), (10, 5, 4)), ((10, 3, 5, 4, 1), (10, 5, 4)), ((10, 3, 5, 4, 1, 1), (10, 5, 4)) ]), chainer.testing.from_pytest_parameterize( 'in_dtypes,out_dtype', _in_out_eval_dtypes), chainer.testing.from_pytest_parameterize( 'ignore_label', [None, 0]) ]) )) class TestAccuracy(EvalBase): def forward_xp(self, inputs, xp): x, t = inputs out = xp.accuracy(x, t, self.ignore_label) return out,
import chainer from chainer import functions as F import numpy import chainerx from chainerx_tests import dtype_utils from chainerx_tests import op_utils _in_out_eval_dtypes = dtype_utils._permutate_dtype_mapping([ (('float16', 'float16'), 'float16'), (('float32', 'float32'), 'float32'), (('float64', 'float64'), 'float64'), (('float32', 'float16'), 'float32'), (('float64', 'float16'), 'float64'), (('float64', 'float32'), 'float64'), ]) class EvalBase(op_utils.ChainerOpTest): def generate_inputs(self): x_dtype, t_dtype = self.in_dtypes y = numpy.random.uniform(-1, 1, self.x_shape).astype(x_dtype) targ = numpy.random.randint( 3, size=self.t_shape).astype(t_dtype) return y, targ def forward_chainerx(self, inputs): return self.forward_xp(inputs, chainerx) def forward_chainer(self, inputs): return self.forward_xp(inputs, F) def forward_xp(self, inputs, xp): raise NotImplementedError( 'Op test implementation must override `forward_xp`.') @op_utils.op_test(['native:0', 'cuda:0']) @chainer.testing.parameterize(*( chainer.testing.product([ chainer.testing.from_pytest_parameterize( 'x_shape,t_shape', [ ((10, 3), (10,)), ((10, 3, 1), (10,)), ((10, 3, 1, 1), (10,)), ((10, 3, 5), (10, 5)), ((10, 3, 5, 4), (10, 5, 4)), ((10, 3, 5, 4, 1), (10, 5, 4)), ((10, 3, 5, 4, 1, 1), (10, 5, 4)) ]), chainer.testing.from_pytest_parameterize( 'in_dtypes,out_dtype', _in_out_eval_dtypes), chainer.testing.from_pytest_parameterize( 'ignore_label', [None, 0]) ]) )) class TestAccuracy(EvalBase): def forward_xp(self, inputs, xp): x, t = inputs t = t.astype(numpy.int64) if xp is chainerx: out = xp.accuracy(x, t, self.ignore_label) else: out = xp.accuracy(x, t, self.ignore_label) return out,
Python
0.000001
67adba196ed29a2a17911e154dc814dae89953ec
Correct log level choices
coalib/parsing/DefaultArgParser.py
coalib/parsing/DefaultArgParser.py
import argparse from coalib.misc.i18n import _ default_arg_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=_("coala is a simple COde AnaLysis Application. Its goal is " "to make static code analysis easy and convenient for all " "languages.")) default_arg_parser.add_argument('TARGETS', nargs='*', help=_("Sections to be executed exclusively.")) default_arg_parser.add_argument('-f', '--files', nargs='+', metavar='FILE', help=_('Files that should be checked')) default_arg_parser.add_argument('-b', '--bears', nargs='+', metavar='NAME', help=_('Names of bears to use')) BEAR_DIRS_HELP = _('Additional directories where bears may lie') default_arg_parser.add_argument('-d', '--bear-dirs', nargs='+', metavar='DIR', help=BEAR_DIRS_HELP) LOG_TYPE_HELP = _("Type of logging (console or any filename)") default_arg_parser.add_argument('-l', '--log-type', nargs=1, metavar='ENUM', help=LOG_TYPE_HELP) LOG_LEVEL_HELP = _("Enum('ERROR','WARNING','DEBUG') to set level of log " "output") default_arg_parser.add_argument('-L', '--log-level', nargs=1, choices=['ERROR', 'WARNING', 'DEBUG'], metavar='ENUM', help=LOG_LEVEL_HELP) OUTPUT_HELP = _('Type of output (console or none)') default_arg_parser.add_argument('-o', '--output', nargs=1, metavar='FILE', help=OUTPUT_HELP) CONFIG_HELP = _('Configuration file to be used, defaults to .coafile') default_arg_parser.add_argument('-c', '--config', nargs=1, metavar='FILE', help=CONFIG_HELP) SAVE_HELP = _('Filename of file to be saved to, if provided with no arguments,' ' settings will be stored back to the file given by -c') default_arg_parser.add_argument('-s', '--save', nargs='?', const=True, metavar='FILE', help=SAVE_HELP) SETTINGS_HELP = _('Arbitrary settings in the form of section.key=value') default_arg_parser.add_argument('-S', '--settings', nargs='+', metavar='SETTING', help=SETTINGS_HELP) JOB_COUNT_HELP = _('Number of processes to be allowed to run at once') default_arg_parser.add_argument('-j', '--job-count', nargs=1, type=int, metavar='INT', help=JOB_COUNT_HELP) APPLY_HELP = _("Enum('YES','NO','ASK') to set whether to apply changes") default_arg_parser.add_argument('-a', '--apply-changes', nargs=1, choices=['YES', 'NO', 'ASK'], metavar='ENUM', help=APPLY_HELP)
import argparse from coalib.misc.i18n import _ default_arg_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=_("coala is a simple COde AnaLysis Application. Its goal is " "to make static code analysis easy and convenient for all " "languages.")) default_arg_parser.add_argument('TARGETS', nargs='*', help=_("Sections to be executed exclusively.")) default_arg_parser.add_argument('-f', '--files', nargs='+', metavar='FILE', help=_('Files that should be checked')) default_arg_parser.add_argument('-b', '--bears', nargs='+', metavar='NAME', help=_('Names of bears to use')) BEAR_DIRS_HELP = _('Additional directories where bears may lie') default_arg_parser.add_argument('-d', '--bear-dirs', nargs='+', metavar='DIR', help=BEAR_DIRS_HELP) LOG_TYPE_HELP = _("Type of logging (console or any filename)") default_arg_parser.add_argument('-l', '--log-type', nargs=1, metavar='ENUM', help=LOG_TYPE_HELP) LOG_LEVEL_HELP = _("Enum('ERR','WARN','DEBUG') to set level of log output") default_arg_parser.add_argument('-L', '--log-level', nargs=1, choices=['ERR', 'WARN', 'DEBUG'], metavar='ENUM', help=LOG_LEVEL_HELP) OUTPUT_HELP = _('Type of output (console or none)') default_arg_parser.add_argument('-o', '--output', nargs=1, metavar='FILE', help=OUTPUT_HELP) CONFIG_HELP = _('Configuration file to be used, defaults to .coafile') default_arg_parser.add_argument('-c', '--config', nargs=1, metavar='FILE', help=CONFIG_HELP) SAVE_HELP = _('Filename of file to be saved to, if provided with no arguments,' ' settings will be stored back to the file given by -c') default_arg_parser.add_argument('-s', '--save', nargs='?', const=True, metavar='FILE', help=SAVE_HELP) SETTINGS_HELP = _('Arbitrary settings in the form of section.key=value') default_arg_parser.add_argument('-S', '--settings', nargs='+', metavar='SETTING', help=SETTINGS_HELP) JOB_COUNT_HELP = _('Number of processes to be allowed to run at once') default_arg_parser.add_argument('-j', '--job-count', nargs=1, type=int, metavar='INT', help=JOB_COUNT_HELP) APPLY_HELP = _("Enum('YES','NO','ASK') to set whether to apply changes") default_arg_parser.add_argument('-a', '--apply-changes', nargs=1, choices=['YES', 'NO', 'ASK'], metavar='ENUM', help=APPLY_HELP)
Python
0
8cf3e7a822517ba12abe72def6d4a2cd0180fb19
Fix autonomous mode merge
robot/robot/src/autonomous/main.py
robot/robot/src/autonomous/main.py
try: import wpilib except ImportError: from pyfrc import wpilib class main(object): '''autonomous program''' DEFAULT = True MODE_NAME = "Tim's Mode" def __init__ (self, components): ''' initialize''' super().__init__() self.drive = components['drive'] self.intake = components['intake'] self.catapult = components['catapult'] # number of seconds to drive forward, allow us to tune it via SmartDashboard wpilib.SmartDashboard.PutNumber('AutoDriveTime', 1.4) wpilib.SmartDashboard.PutNumber('AutoDriveSpeed', 0.5) def on_enable(self): '''these are called when autonomous starts''' self.drive_time = wpilib.SmartDashboard.GetNumber('AutoDriveTime') self.drive_speed = wpilib.SmartDashboard.GetNumber('AutoDriveSpeed') print("Team 1418 autonomous code for 2014") print("-> Drive time:", self.drive_time, "seconds") print("-> Drive speed:", self.drive_speed) #print("-> Battery voltage: %.02fv" % wpilib.DriverStation.GetInstance().GetBatteryVoltage()) def on_disable(self): '''This function is called when autonomous mode is disabled''' pass def update(self, time_elapsed): '''The actual autonomous program''' # always pulldown if time_elapsed > 0.3: self.catapult.pulldown() if time_elapsed < 0.3: # Get the arm down so that we can winch self.intake.armDown() elif time_elapsed < 1.4: # The arm is at least far enough down now that # the winch won't hit it, start winching self.intake.armDown() elif time_elapsed < 2.0: # We're letting the winch take its sweet time pass elif time_elapsed < 2.0 + self.drive_time: # Drive slowly forward for N seconds self.drive.move(0, self.drive_speed, 0) elif time_elapsed < 2.0 + self.drive_time + 1.0: # Finally, fire and keep firing for 1 seconds self.catapult.launchNoSensor()
try: import wpilib except ImportError: from pyfrc import wpilib class main(object): '''autonomous program''' DEFAULT = True MODE_NAME = "Tim's Mode" def __init__ (self, components): ''' initialize''' super().__init__() self.drive = components['drive'] self.intake = components['intake'] self.catapult = components['catapult'] # number of seconds to drive forward, allow us to tune it via SmartDashboard wpilib.SmartDashboard.PutNumber('AutoDriveTime', 1.4) wpilib.SmartDashboard.PutNumber('AutoDriveSpeed', 0.5) def on_enable(self): '''these are called when autonomous starts''' self.drive_time = wpilib.SmartDashboard.GetNumber('AutoDriveTime') self.drive_speed = wpilib.SmartDashboard.GetNumber('AutoDriveSpeed') print("Team 1418 autonomous code for 2014") print("-> Drive time:", self.drive_time, "seconds") print("-> Drive speed:", self.drive_speed) #print("-> Battery voltage: %.02fv" % wpilib.DriverStation.GetInstance().GetBatteryVoltage()) def on_disable(self): '''This function is called when autonomous mode is disabled''' pass def update(self, time_elapsed): '''The actual autonomous program''' # always pulldown if time_elapsed > 0.3: self.catapult.pulldown() if time_elapsed < 0.3: # Get the arm down so that we can winch self.intake.armDown() <<<<<<< HEAD if time_elapsed > 0.5: self.catapult.autowinch() elif time_elapsed < 1.5: ======= elif time_elapsed < 1.4: >>>>>>> branch 'master' of https://github.com/frc1418/2014.git # The arm is at least far enough down now that # the winch won't hit it, start winching self.intake.armDown() elif time_elapsed < 2.0: # We're letting the winch take its sweet time pass elif time_elapsed < 2.0 + self.drive_time: # Drive slowly forward for N seconds self.drive.move(0, self.drive_speed, 0) elif time_elapsed < 2.0 + self.drive_time + 1.0: # Finally, fire and keep firing for 1 seconds self.catapult.launchNoSensor() <<<<<<< HEAD ======= >>>>>>> 907e2ebf9b7991b9ebf2ee093eefd40c2ccb1b98
Python
0.000083
c435f6039b344829380db4bf92f80ff4d5de8972
fixes scrolling_benchmark.
tools/telemetry/telemetry/core/chrome/android_platform_backend.py
tools/telemetry/telemetry/core/chrome/android_platform_backend.py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core.chrome import platform from telemetry.core.chrome import platform_backend # Get build/android scripts into our path. sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../build/android'))) from pylib import perf_tests_helper # pylint: disable=F0401 from pylib import thermal_throttle # pylint: disable=F0401 try: from pylib import surface_stats_collector # pylint: disable=F0401 except Exception: surface_stats_collector = None class AndroidPlatformBackend(platform_backend.PlatformBackend): def __init__(self, adb, no_performance_mode): super(AndroidPlatformBackend, self).__init__() self._adb = adb self._surface_stats_collector = None self._perf_tests_setup = perf_tests_helper.PerfTestSetup(self._adb) self._thermal_throttle = thermal_throttle.ThermalThrottle(self._adb) self._no_performance_mode = no_performance_mode self._raw_display_frame_rate_measurements = [] if self._no_performance_mode: logging.warning('CPU governor will not be set!') def IsRawDisplayFrameRateSupported(self): return True def StartRawDisplayFrameRateMeasurement(self): assert not self._surface_stats_collector self._surface_stats_collector = \ surface_stats_collector.SurfaceStatsCollector(self._adb) self._surface_stats_collector.Start() def StopRawDisplayFrameRateMeasurement(self): self._surface_stats_collector.Stop() for r in self._surface_stats_collector.GetResults(): self._raw_display_frame_rate_measurements.append( platform.Platform.RawDisplayFrameRateMeasurement( r.name, r.value, r.unit)) self._surface_stats_collector = None def GetRawDisplayFrameRateMeasurements(self): ret = self._raw_display_frame_rate_measurements self._raw_display_frame_rate_measurements = [] return ret def SetFullPerformanceModeEnabled(self, enabled): if self._no_performance_mode: return if enabled: self._perf_tests_setup.SetUp() else: self._perf_tests_setup.TearDown() def CanMonitorThermalThrottling(self): return True def IsThermallyThrottled(self): return self._thermal_throttle.IsThrottled() def HasBeenThermallyThrottled(self): return self._thermal_throttle.HasBeenThrottled() def GetSystemCommitCharge(self): for line in self._adb.RunShellCommand('dumpsys meminfo', log_result=False): if line.startswith('Total PSS: '): return int(line.split()[2]) * 1024 return 0 def GetMemoryStats(self, pid): memory_usage = self._adb.GetMemoryUsageForPid(pid)[0] return {'ProportionalSetSize': memory_usage['Pss'] * 1024, 'PrivateDirty': memory_usage['Private_Dirty'] * 1024} def GetIOStats(self, pid): return {} def GetChildPids(self, pid): child_pids = [] ps = self._adb.RunShellCommand('ps', log_result=False)[1:] for line in ps: data = line.split() curr_pid = data[1] curr_name = data[-1] if int(curr_pid) == pid: name = curr_name for line in ps: data = line.split() curr_pid = data[1] curr_name = data[-1] if curr_name.startswith(name) and curr_name != name: child_pids.append(int(curr_pid)) break return child_pids
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core.chrome import platform from telemetry.core.chrome import platform_backend # Get build/android scripts into our path. sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../build/android'))) from pylib import perf_tests_helper # pylint: disable=F0401 from pylib import thermal_throttle # pylint: disable=F0401 try: from pylib import surface_stats_collector # pylint: disable=F0401 except Exception: surface_stats_collector = None class AndroidPlatformBackend(platform_backend.PlatformBackend): def __init__(self, adb, no_performance_mode): super(AndroidPlatformBackend, self).__init__() self._adb = adb self._surface_stats_collector = None self._perf_tests_setup = perf_tests_helper.PerfTestSetup(self._adb) self._thermal_throttle = thermal_throttle.ThermalThrottle(self._adb) self._no_performance_mode = no_performance_mode self._raw_display_frame_rate_measurements = [] if self._no_performance_mode: logging.warning('CPU governor will not be set!') def IsRawDisplayFrameRateSupported(self): return True def StartRawDisplayFrameRateMeasurement(self): assert not self._surface_stats_collector self._surface_stats_collector = \ surface_stats_collector.SurfaceStatsCollector(self._adb) self._surface_stats_collector.Start() def StopRawDisplayFrameRateMeasurement(self): self._surface_stats_collector.Stop() for r in self._surface_stats_collector.GetResults(): self._raw_display_frame_rate_measurements.append( platform.Platform.RawDisplayFrameRateMeasurement( r.name, r.value, r.unit)) self._surface_stats_collector = None def GetRawDisplayFrameRateMeasurements(self): return self._raw_display_frame_rate_measurements def SetFullPerformanceModeEnabled(self, enabled): if self._no_performance_mode: return if enabled: self._perf_tests_setup.SetUp() else: self._perf_tests_setup.TearDown() def CanMonitorThermalThrottling(self): return True def IsThermallyThrottled(self): return self._thermal_throttle.IsThrottled() def HasBeenThermallyThrottled(self): return self._thermal_throttle.HasBeenThrottled() def GetSystemCommitCharge(self): for line in self._adb.RunShellCommand('dumpsys meminfo', log_result=False): if line.startswith('Total PSS: '): return int(line.split()[2]) * 1024 return 0 def GetMemoryStats(self, pid): memory_usage = self._adb.GetMemoryUsageForPid(pid)[0] return {'ProportionalSetSize': memory_usage['Pss'] * 1024, 'PrivateDirty': memory_usage['Private_Dirty'] * 1024} def GetIOStats(self, pid): return {} def GetChildPids(self, pid): child_pids = [] ps = self._adb.RunShellCommand('ps', log_result=False)[1:] for line in ps: data = line.split() curr_pid = data[1] curr_name = data[-1] if int(curr_pid) == pid: name = curr_name for line in ps: data = line.split() curr_pid = data[1] curr_name = data[-1] if curr_name.startswith(name) and curr_name != name: child_pids.append(int(curr_pid)) break return child_pids
Python
0.999861
9963642c1cc05fb6d9dfe397b9ed811d4f7e3d26
add 4.6.1 and 3.10.1 (#24701)
var/spack/repos/builtin/packages/py-importlib-metadata/package.py
var/spack/repos/builtin/packages/py-importlib-metadata/package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyImportlibMetadata(PythonPackage): """Read metadata from Python packages.""" homepage = "https://importlib-metadata.readthedocs.io/" pypi = "importlib_metadata/importlib_metadata-1.2.0.tar.gz" version('4.6.1', sha256='079ada16b7fc30dfbb5d13399a5113110dab1aa7c2bc62f66af75f0b717c8cac') version('3.10.1', sha256='c9356b657de65c53744046fa8f7358afe0714a1af7d570c00c3835c2d724a7c1') version('3.10.0', sha256='c9db46394197244adf2f0b08ec5bc3cf16757e9590b02af1fca085c16c0d600a') version('2.0.0', sha256='77a540690e24b0305878c37ffd421785a6f7e53c8b5720d211b211de8d0e95da') version('1.2.0', sha256='41e688146d000891f32b1669e8573c57e39e5060e7f5f647aa617cd9a9568278') version('0.23', sha256='aa18d7378b00b40847790e7c27e11673d7fed219354109d0e7b9e5b25dc3ad26') version('0.19', sha256='23d3d873e008a513952355379d93cbcab874c58f4f034ff657c7a87422fa64e8') version('0.18', sha256='cb6ee23b46173539939964df59d3d72c3e0c1b5d54b84f1d8a7e912fe43612db') depends_on('python@3.6:', type=('build', 'run'), when='@3:') depends_on('python@2.7:2.8,3.5:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-setuptools-scm', type='build') depends_on('py-setuptools-scm@3.4.1:+toml', type='build', when='@3:') depends_on('py-zipp@0.5:', type=('build', 'run')) depends_on('py-pathlib2', when='^python@:2', type=('build', 'run')) depends_on('py-contextlib2', when='^python@:2', type=('build', 'run')) depends_on('py-configparser@3.5:', when='^python@:2', type=('build', 'run')) depends_on('py-typing-extensions@3.6.4:', type=('build', 'run'), when='@3: ^python@:3.7.999')
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyImportlibMetadata(PythonPackage): """Read metadata from Python packages.""" homepage = "https://importlib-metadata.readthedocs.io/" pypi = "importlib_metadata/importlib_metadata-1.2.0.tar.gz" version('3.10.0', sha256='c9db46394197244adf2f0b08ec5bc3cf16757e9590b02af1fca085c16c0d600a') version('2.0.0', sha256='77a540690e24b0305878c37ffd421785a6f7e53c8b5720d211b211de8d0e95da') version('1.2.0', sha256='41e688146d000891f32b1669e8573c57e39e5060e7f5f647aa617cd9a9568278') version('0.23', sha256='aa18d7378b00b40847790e7c27e11673d7fed219354109d0e7b9e5b25dc3ad26') version('0.19', sha256='23d3d873e008a513952355379d93cbcab874c58f4f034ff657c7a87422fa64e8') version('0.18', sha256='cb6ee23b46173539939964df59d3d72c3e0c1b5d54b84f1d8a7e912fe43612db') depends_on('python@3.6:', type=('build', 'run'), when='@3:') depends_on('python@2.7:2.8,3.5:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-setuptools-scm', type='build') depends_on('py-setuptools-scm@3.4.1:+toml', type='build', when='@3:') depends_on('py-zipp@0.5:', type=('build', 'run')) depends_on('py-pathlib2', when='^python@:2', type=('build', 'run')) depends_on('py-contextlib2', when='^python@:2', type=('build', 'run')) depends_on('py-configparser@3.5:', when='^python@:2', type=('build', 'run')) depends_on('py-typing-extensions@3.6.4:', type=('build', 'run'), when='@3: ^python@:3.7.999')
Python
0
a2749190545a6765a479777b1ea97d2f9090593f
clean up project config a bit
jailscraper/project_config.py
jailscraper/project_config.py
"""ProPublica specific configuration and utilities""" import boto3 import botocore import os ### Helpers def get_secrets(): """Get all environment variables associated with this project. Reads environment variables that start with PROJECT_SLUG, strips out the slug and adds them to a dictionary. """ secrets = {} for k, v in os.environ.items(): if k.startswith(PROJECT_SLUG): new_k = k[len(PROJECT_SLUG) + 1:] secrets[new_k] = v return secrets SECRETS = get_secrets() S3_BUCKET = SECRETS['S3_BUCKET'] TARGET = SECRETS['TARGET'] S3_URL = 's3://{0}/{1}'.format(SECRETS['S3_BUCKET'], SECRETS['TARGET'])
"""ProPublica specific configuration and utilities""" import os PROJECT_SLUG = 'cookcountyjail2' INMATE_URL_TEMPLATE = 'http://www2.cookcountysheriff.org/search2/details.asp?jailnumber={0}' """Sets the maximum jail number to scan for by default. If the subsequent jail number returns a 2xx status code, it will be incremented until an error code is sent. [@TODO: Not implemented, see https://github.com/propublica/cookcountyjail2/issues/9] """ MAX_DEFAULT_JAIL_NUMBER = 400 def get_secrets(): """Get all environment variables associated with this project. Reads environment variables that start with PROJECT_SLUG, strips out the slug and adds them to a dictionary. """ secrets = {} for k, v in os.environ.items(): if k.startswith(PROJECT_SLUG): new_k = k[len(PROJECT_SLUG) + 1:] secrets[new_k] = v return secrets SECRETS = get_secrets() S3_BUCKET = SECRETS['S3_BUCKET'] TARGET = SECRETS['TARGET'] S3_URL = 's3://{0}/{1}'.format(SECRETS['S3_BUCKET'], SECRETS['TARGET'])
Python
0
9f531eec31e141b458c4c7896bebb16611cc7b00
Refactor calories plugin (#503)
jarviscli/plugins/calories.py
jarviscli/plugins/calories.py
from plugin import plugin from colorama import Back, Fore, Style @plugin("calories") class calories: """ Tells the recommended daily calorie intake, also recommends calories for weight add and loss.(Source 1) It is based on gender, age, height and weight. Uses the Miffin-St Jeor Equation as it is considered the most accurate when we don't know our body fat percentage(Source 2). Add gender(man/woman), age(15 - 80 recommended), metric height(cm), weight(kg), workout level(1-4). No decimal weight for now. Workout Levels: [1] Little or no exercise [2] Light 1-3 per week [3] Moderate 4-5 per week [4] Active daily exercise or physical job #Example: health calories woman 27 164 60 3 ^Sources: 1) https://en.wikipedia.org/wiki/Basal_metabolic_rate 2) https://jandonline.org/article/S0002-8223(05)00149-5/fulltext """ def __call__(self, jarvis, s): jarvis.say("Welcome!") info = input("Please enter the information about you following this order(gender age height weight level): ") self.calories(jarvis, info) def calories(self, jarvis, info): strings = info.split() if len(strings) == 5: gender = strings[0] age = int(strings[1]) height = int(strings[2]) weight = float(strings[3]) level = int(strings[4]) else: jarvis.say("You wrote less or more arguments than it needed.") return None gender_no = 0 if(gender == 'man'): gender_no = 5 elif(gender == 'woman'): gender_no = -161 if gender_no != 0 and age > 14 and height > 0.0 and weight > 0.0 and level > 0 and level < 5: brm = float(10 * weight + 6.25 * height - 5 * age + gender_no) * self.exercise_level(level) brm_loss = brm - 500.0 brm_put_on = brm + 500.0 jarvis.say("Daily caloric intake : " + str(brm)) jarvis.say("Loss weight calories : " + str(brm_loss)) jarvis.say("Put on weight calories : " + str(brm_put_on)) else: jarvis.say("Please add correct input!") return None def exercise_level(self, level): multipliers = {1: 1.2, 2: 1.4, 3: 1.6, 4: 1.95} multiplier = multipliers.get(level, 1) return multiplier
from plugin import plugin @plugin("calories") def calories(jarvis, s): """ Tells the recommended daily calorie intake, also recommends calories for weight add and loss.(Source 1) It is based on gender, age, height and weight. Uses the Miffin-St Jeor Equation as it is considered the most accurate when we don't know our body fat percentage(Source 2). Add gender(man/woman), age(15 - 80 recommended), metric height(cm), weight(kg), workout level(1-4). No decimal weight for now. Workout Levels: [1] Little or no exercise [2] Light 1-3 per week [3] Moderate 4-5 per week [4] Active daily exercise or physical job #Example: health calories woman 27 164 60 3 ^Sources: 1) https://en.wikipedia.org/wiki/Basal_metabolic_rate 2) https://jandonline.org/article/S0002-8223(05)00149-5/fulltext """ strings = s.split() if len(strings) == 5: gender = strings[0] age = int(strings[1]) height = int(strings[2]) weight = float(strings[3]) level = int(strings[4]) else: jarvis.say("You wrote less or more arguments than it needed.") return None gender_no = 0 if(gender == 'man'): gender_no = 5 elif(gender == 'woman'): gender_no = -161 if gender_no != 0 and age > 14 and height > 0.0 and weight > 0.0 and level > 0 and level < 5: brm = float(10 * weight + 6.25 * height - 5 * age + gender_no) * exercise_level(level) brm_loss = brm - 500.0 brm_put_on = brm + 500.0 jarvis.say("Daily caloric intake : " + str(brm)) jarvis.say("Loss weight calories : " + str(brm_loss)) jarvis.say("Put on weight calories : " + str(brm_put_on)) else: jarvis.say("Please add correct input!") return None def exercise_level(level): multiplier = 1 if(level == 1): multiplier = 1.2 elif(level == 2): multiplier = 1.4 elif(level == 3): multiplier = 1.6 else: multiplier = 1.95 return multiplier
Python
0
dde62362955ca4b10f3c1fec4e3b7777b03141f5
remove ContextDict since std has ChainMap
jasily/collection/__init__.py
jasily/collection/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ----------
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- from collections import KeysView, ValuesView, ItemsView, MutableMapping _NO_VALUE = object() class ContextDict(MutableMapping): '''context dict can override base_dict.''' def __init__(self, base_dict: dict, *args, **kwargs): if base_dict is None: raise ValueError('base_dict cannot be None') self._base_dict = base_dict self._data = dict(*args, **kwargs) # data maybe not empty. def __setitem__(self, key, value): self._data[key] = value def __delitem__(self, key): del self._data[key] def __getitem__(self, key): value = self._data.get(key, _NO_VALUE) if value is _NO_VALUE: value = self._base_dict[key] return value def __iter__(self): for k in self._data: yield k for k in self._base_dict: if k not in self._data: yield k def __len__(self): # base dict may change, so we cannot cache the size. d1 = self._data d2 = self._base_dict d1_len = len(d1) d2_len = len(d2) if d1_len > d2_len: # ensure d1 < d2 d1, d2 = d2, d1 total_size = d1_len + d2_len for k in d1: if k in d2: total_size -= 1 return total_size def scope(self): '''create a scoped dict.''' return ContextDict(self) def __enter__(self): '''return a new context dict.''' return self.scope() def __exit__(self, *args): pass
Python
0.000013
bca2ea9c72669c4877d6c9be74a2c58f8341ce61
Update Portuguese lexical attributes
spacy/lang/pt/lex_attrs.py
spacy/lang/pt/lex_attrs.py
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze', 'quinze', 'dezasseis', 'dezassete', 'dezoito', 'dezanove', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa', 'cem', 'mil', 'milhão', 'bilião', 'trilião', 'quadrilião'] _ord_words = ['primeiro', 'segundo', 'terceiro', 'quarto', 'quinto', 'sexto', 'sétimo', 'oitavo', 'nono', 'décimo', 'vigésimo', 'trigésimo', 'quadragésimo', 'quinquagésimo', 'sexagésimo', 'septuagésimo', 'octogésimo', 'nonagésimo', 'centésimo', 'ducentésimo', 'trecentésimo', 'quadringentésimo', 'quingentésimo', 'sexcentésimo', 'septingentésimo', 'octingentésimo', 'nongentésimo', 'milésimo', 'milionésimo', 'bilionésimo'] def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
# coding: utf8 from __future__ import unicode_literals # Number words NUM_WORDS = set(""" zero um dois três quatro cinco seis sete oito nove dez onze doze treze catorze quinze dezasseis dezassete dezoito dezanove vinte trinta quarenta cinquenta sessenta setenta oitenta noventa cem mil milhão bilião trilião quadrilião """.split()) # Ordinal words ORDINAL_WORDS = set(""" primeiro segundo terceiro quarto quinto sexto sétimo oitavo nono décimo vigésimo trigésimo quadragésimo quinquagésimo sexagésimo septuagésimo octogésimo nonagésimo centésimo ducentésimo trecentésimo quadringentésimo quingentésimo sexcentésimo septingentésimo octingentésimo nongentésimo milésimo milionésimo bilionésimo """.split())
Python
0.000001
e635d6a1c4ca8c138a5bd288250f94bcd82bb8a8
Remove unnecessary imports.
vistrails/tests/resources/upgrades/init.py
vistrails/tests/resources/upgrades/init.py
from vistrails.core.modules.vistrails_module import Module from vistrails.core.modules.config import IPort, OPort from vistrails.core.upgradeworkflow import UpgradeModuleRemap class TestUpgradeA(Module): _input_ports = [IPort("aaa", "basic:String")] _output_ports = [OPort("zzz", "basic:Integer")] class TestUpgradeB(Module): _input_ports = [IPort("b", "basic:Integer")] _modules = [TestUpgradeA, TestUpgradeB] _upgrades = {"TestUpgradeA": [UpgradeModuleRemap('0.8', '0.9', '0.9', None, function_remap={'a': 'aa'}, src_port_remap={'z': 'zz'}), UpgradeModuleRemap('0.9', '1.0', '1.0', None, function_remap={'aa': 'aaa'}, src_port_remap={'zz': 'zzz'})]}
from vistrails.core.modules.vistrails_module import Module from vistrails.core.modules.config import IPort, OPort from vistrails.core.upgradeworkflow import UpgradeWorkflowHandler, \ UpgradePackageRemap, UpgradeModuleRemap class TestUpgradeA(Module): _input_ports = [IPort("aaa", "basic:String")] _output_ports = [OPort("zzz", "basic:Integer")] class TestUpgradeB(Module): _input_ports = [IPort("b", "basic:Integer")] _modules = [TestUpgradeA, TestUpgradeB] _upgrades = {"TestUpgradeA": [UpgradeModuleRemap('0.8', '0.9', '0.9', None, function_remap={'a': 'aa'}, src_port_remap={'z': 'zz'}), UpgradeModuleRemap('0.9', '1.0', '1.0', None, function_remap={'aa': 'aaa'}, src_port_remap={'zz': 'zzz'})]}
Python
0.000001
a2b19e7fd6b0004e4fa18b6d1b20f7347ca1964c
Fix wrong indentation
command/export.py
command/export.py
#!/usr/bin/env python2 # coding=utf-8 import json import urllib2 import logging import base64 from config import global_config from bddown_core import Pan, GetFilenameError def export(links): for link in links: pan = Pan(link) count = 1 while count != 0: link, filename, count = pan.info if not filename and not link: raise GetFilenameError("无法获取下载地址或文件名!") export_single(filename, link) def export_single(filename, link): jsonrpc_path = global_config.jsonrpc jsonrpc_user = global_config.jsonrpc_user jsonrpc_pass = global_config.jsonrpc_pass if not jsonrpc_path: print "请设置config.ini中的jsonrpc选项" exit(1) jsonreq = json.dumps( [{ "jsonrpc": "2.0", "method": "aria2.addUri", "id": "qwer", "params": [ [link], { "out": filename, "header": "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0" "\r\nReferer:http://pan.baidu.com/disk/home" }] }] ) logging.debug(jsonreq) try: request = urllib2.Request(jsonrpc_path) if jsonrpc_user and jsonrpc_pass: base64string = base64.encodestring('%s:%s' % (jsonrpc_user, jsonrpc_pass)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) request.add_data(jsonreq) req = urllib2.urlopen(request) except urllib2.URLError as urle: print urle raise JsonrpcError("jsonrpc无法连接,请检查jsonrpc地址是否有误!") if req.code == 200: print "已成功添加到jsonrpc\n" class JsonrpcError(Exception): pass
#!/usr/bin/env python2 # coding=utf-8 import json import urllib2 import logging import base64 from config import global_config from bddown_core import Pan, GetFilenameError def export(links): for link in links: pan = Pan(link) count = 1 while count != 0: link, filename, count = pan.info if not filename and not link: raise GetFilenameError("无法获取下载地址或文件名!") export_single(filename, link) def export_single(filename, link): jsonrpc_path = global_config.jsonrpc jsonrpc_user = global_config.jsonrpc_user jsonrpc_pass = global_config.jsonrpc_pass if not jsonrpc_path: print "请设置config.ini中的jsonrpc选项" exit(1) jsonreq = json.dumps( [{ "jsonrpc": "2.0", "method": "aria2.addUri", "id": "qwer", "params": [ [link], { "out": filename, "header": "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0" "\r\nReferer:http://pan.baidu.com/disk/home" }] }] ) logging.debug(jsonreq) try: request = urllib2.Request(jsonrpc_path) if jsonrpc_user and jsonrpc_pass: base64string = base64.encodestring('%s:%s' % (jsonrpc_user, jsonrpc_pass)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) request.add_data(jsonreq) req = urllib2.urlopen(request) except urllib2.URLError as urle: print urle raise JsonrpcError("jsonrpc无法连接,请检查jsonrpc地址是否有误!") if req.code == 200: print "已成功添加到jsonrpc\n" class JsonrpcError(Exception): pass
Python
0.810919
24b86c78a6420006eabf6c27535f946edc612385
Handle no tags in repository better
git_gutter_compare.py
git_gutter_compare.py
import sublime import sublime_plugin ST3 = int(sublime.version()) >= 3000 if ST3: from GitGutter.view_collection import ViewCollection else: from view_collection import ViewCollection class GitGutterCompareCommit(sublime_plugin.WindowCommand): def run(self): self.view = self.window.active_view() key = ViewCollection.get_key(self.view) self.handler = ViewCollection.views[key] self.results = self.commit_list() if self.results: self.window.show_quick_panel(self.results, self.on_select) def commit_list(self): result = self.handler.git_commits().decode("utf-8") return [r.split('\a', 2) for r in result.strip().split('\n')] def item_to_commit(self, item): return item[1].split(' ')[0] def on_select(self, selected): if 0 > selected < len(self.results): return item = self.results[selected] commit = self.item_to_commit(item) ViewCollection.set_compare(commit) ViewCollection.clear_git_time(self.view) ViewCollection.add(self.view) class GitGutterCompareBranch(GitGutterCompareCommit): def commit_list(self): result = self.handler.git_branches().decode("utf-8") return [self.parse_result(r) for r in result.strip().split('\n')] def parse_result(self, result): pieces = result.split('\a') message = pieces[0] branch = pieces[1].split("/")[2] commit = pieces[2][0:7] return [branch, commit + " " + message] class GitGutterCompareTag(GitGutterCompareCommit): def commit_list(self): result = self.handler.git_tags().decode("utf-8") if result: return [self.parse_result(r) for r in result.strip().split('\n')] else: sublime.message_dialog("No tags found in repository") def parse_result(self, result): pieces = result.split(' ') commit = pieces[0] tag = pieces[1].replace("refs/tags/", "") return [tag, commit] def item_to_commit(self, item): return item[1] class GitGutterCompareHead(sublime_plugin.WindowCommand): def run(self): self.view = self.window.active_view() ViewCollection.set_compare("HEAD") ViewCollection.clear_git_time(self.view) ViewCollection.add(self.view) class GitGutterShowCompare(sublime_plugin.WindowCommand): def run(self): comparing = ViewCollection.get_compare() sublime.message_dialog("GitGutter is comparing against: " + comparing)
import sublime import sublime_plugin ST3 = int(sublime.version()) >= 3000 if ST3: from GitGutter.view_collection import ViewCollection else: from view_collection import ViewCollection class GitGutterCompareCommit(sublime_plugin.WindowCommand): def run(self): self.view = self.window.active_view() key = ViewCollection.get_key(self.view) self.handler = ViewCollection.views[key] self.results = self.commit_list() self.window.show_quick_panel(self.results, self.on_select) def commit_list(self): result = self.handler.git_commits().decode("utf-8") return [r.split('\a', 2) for r in result.strip().split('\n')] def item_to_commit(self, item): return item[1].split(' ')[0] def on_select(self, selected): if 0 > selected < len(self.results): return item = self.results[selected] commit = self.item_to_commit(item) ViewCollection.set_compare(commit) ViewCollection.clear_git_time(self.view) ViewCollection.add(self.view) class GitGutterCompareBranch(GitGutterCompareCommit): def commit_list(self): result = self.handler.git_branches().decode("utf-8") return [self.parse_result(r) for r in result.strip().split('\n')] def parse_result(self, result): pieces = result.split('\a') message = pieces[0] branch = pieces[1].split("/")[2] commit = pieces[2][0:7] return [branch, commit + " " + message] class GitGutterCompareTag(GitGutterCompareCommit): def commit_list(self): result = self.handler.git_tags().decode("utf-8") return [self.parse_result(r) for r in result.strip().split('\n')] def parse_result(self, result): if not result: sublime.message_dialog("No tags found in repository") return pieces = result.split(' ') commit = pieces[0] tag = pieces[1].replace("refs/tags/", "") return [tag, commit] def item_to_commit(self, item): return item[1] class GitGutterCompareHead(sublime_plugin.WindowCommand): def run(self): self.view = self.window.active_view() ViewCollection.set_compare("HEAD") ViewCollection.clear_git_time(self.view) ViewCollection.add(self.view) class GitGutterShowCompare(sublime_plugin.WindowCommand): def run(self): comparing = ViewCollection.get_compare() sublime.message_dialog("GitGutter is comparing against: " + comparing)
Python
0
920872db456987e5bd5002b3bf3fc2168dcbdff4
fix name
django_extra_tools/conf/defaults.py
django_extra_tools/conf/defaults.py
"""Default configuration""" # auth.backends.ThroughSuperuserModelBackend username separator AUTH_BACKEND_USERNAME_SEPARATOR = ':' XHR_MIDDLEWARE_ALLOWED_ORIGINS = '*' XHR_MIDDLEWARE_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] XHR_MIDDLEWARE_ALLOWED_HEADERS = ['Content-Type', 'Authorization', 'Location', '*'] XHR_MIDDLEWARE_ALLOWED_CREDENTIALS = 'true' XHR_MIDDLEWARE_EXPOSE_HEADERS = ['Location'] PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )
"""Default configuration""" # auth.backends.SuperUserAuthenticateMixin username separator AUTH_BACKEND_USERNAME_SEPARATOR = ':' XHR_MIDDLEWARE_ALLOWED_ORIGINS = '*' XHR_MIDDLEWARE_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] XHR_MIDDLEWARE_ALLOWED_HEADERS = ['Content-Type', 'Authorization', 'Location', '*'] XHR_MIDDLEWARE_ALLOWED_CREDENTIALS = 'true' XHR_MIDDLEWARE_EXPOSE_HEADERS = ['Location'] PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )
Python
0.019891
ceac948c3c1e4fc59faf5d745af06516ec6c502e
Improve code quality
conda-envs.15m.py
conda-envs.15m.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # <bitbar.title>Anaconda Environments</bitbar.title> # <bitbar.version>v1.1</bitbar.version> # <bitbar.author>Darius Morawiec</bitbar.author> # <bitbar.author.github>nok</bitbar.author.github> # <bitbar.desc>Useful BitBar plugin to list all created conda environments and to open a new session with a chosen environment.</bitbar.desc> # <bitbar.image>https://github.com/nok/conda-envs/blob/master/themes/dark.png?raw=true</bitbar.image> # <bitbar.dependencies>conda</bitbar.dependencies> # <bitbar.abouturl>https://github.com/nok/conda-envs</bitbar.abouturl> import os import subprocess # User settings: CONDA_PATH = '~/anaconda/bin/conda' CHECK_VERSION = True # BitBar related constants: LINE = '---' # cutting line class Color: GREEN = '#3bb15c' BLUE = '#4a90f3' class Env: def __init__(self, name): conda = os.path.expanduser(CONDA_PATH) cmd = [conda, 'env', 'export', '-n', name] deps = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() version = None if CHECK_VERSION: for dep in deps.splitlines(): if '- python=' in dep: version = dep.split('=')[1] name += ' (%s)' % version break self.name = name self.version = version @property def color(self): """ Return the color to the used Python version. Python 2.X: #3bb15c Python 3.X: #4a90f3 :return: string: The color in hexadecimal format. """ return Color.GREEN if self.version.startswith('2') else Color.BLUE def __str__(self): """ Return the environment settings in BitBar format. :return: string: The environment settings in BitBar format. """ cmd = '{name} | bash=source param1=activate param2={name} ' + \ 'terminal=true refresh=false' meta = self.__dict__ if self.version is not None: cmd += ' color={color}' meta.update({'color': self.color}) return cmd.format(**meta) def is_conda_installed(): """ Check whether conda is installed locally. :return: bool: Check whether conda is installed locally. """ conda = os.path.expanduser(CONDA_PATH) try: subprocess.check_output([conda], stderr=subprocess.STDOUT).strip() except: print(LINE) print('Download Aanaconda | href=https://www.continuum.io/downloads') exit(-1) def get_conda_envs(): """ Create a list of all parsed environments. :return: list: The list of environment instances. """ conda = os.path.expanduser(CONDA_PATH) cmd = [conda, 'env', 'list'] out = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() envs = [] for env in out.splitlines(): if not env.strip().startswith('#'): tuple = env.split() name = tuple[0] try: env = Env(name) envs.append(env) except: pass return envs def print_menu(envs): """ Print the BitBar menu. :param envs: The parsed environment instances. """ if len(envs) > 0: print(LINE) for idx, env in enumerate(envs): print(env) if CHECK_VERSION: print(LINE) print('Python 2 | color=%s' % Color.GREEN) print('Python 3 | color=%s' % Color.BLUE) print(LINE) conda = os.path.expanduser(CONDA_PATH) cmd = [conda, '--version'] ver = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() print(ver) def main(): print('𝗔') # Print always the letter 'A' of 'Anaconda' is_conda_installed() envs = get_conda_envs() print_menu(envs) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # <bitbar.title>Anaconda Environments</bitbar.title> # <bitbar.version>v1.0</bitbar.version> # <bitbar.author>Darius Morawiec</bitbar.author> # <bitbar.author.github>nok</bitbar.author.github> # <bitbar.desc>Useful BitBar plugin to list all created conda environments and to open a new session with a chosen environment.</bitbar.desc> # <bitbar.image>https://github.com/nok/conda-envs/blob/master/themes/dark.png?raw=true</bitbar.image> # <bitbar.dependencies>conda</bitbar.dependencies> # <bitbar.abouturl>https://github.com/nok/conda-envs</bitbar.abouturl> import os import subprocess CONDA_PATH = '~/anaconda/bin/conda' CHECK_VERSION = True class Color: GREEN = '#3bb15c' BLUE = '#4a90f3' class Env: def __init__(self, env_name): conda = os.path.expanduser(CONDA_PATH) cmd = [conda, 'env', 'export', '-n', env_name] deps = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() version = None if CHECK_VERSION: for dep in deps.splitlines(): if '- python=' in dep: version = dep.split('=')[1] env_name += ' (%s)' % version break self.env_name = env_name self.version = version @property def color(self): if self.version is None: return Color.WHITE else: major = self.version.split('.')[0] if major.startswith('2'): return Color.GREEN return Color.BLUE def __str__(self): if self.version is None: return ('%s | bash=source param1=activate ' 'param2=%s terminal=true refresh=false') % ( self.env_name, self.env_name) return ('%s | color=%s bash=source param1=activate ' 'param2=%s terminal=true refresh=false') % ( self.env_name, self.color, self.env_name) def is_conda_installed(): conda = os.path.expanduser(CONDA_PATH) try: subprocess.check_output([conda], stderr=subprocess.STDOUT).strip() except: print('---') print('Download Aanaconda | href=https://www.continuum.io/downloads') exit(-1) def get_conda_envs(): conda = os.path.expanduser(CONDA_PATH) cmd = [conda, 'env', 'list'] out = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() envs = [] for env in out.splitlines(): if not env.strip().startswith('#'): tuple = env.split() name = tuple[0] # path = tuple[1] envs.append(Env(name)) return envs def print_menu(envs): if len(envs) > 0: print('---') for idx, env in enumerate(envs): print(env) if CHECK_VERSION: print('---') print('Python 2 | color=%s' % Color.GREEN) print('Python 3 | color=%s' % Color.BLUE) print('---') conda = os.path.expanduser(CONDA_PATH) cmd = [conda, '--version'] ver = subprocess.check_output(cmd, stderr=subprocess.STDOUT).strip() print(ver) def main(): print('𝗔') is_conda_installed() envs = get_conda_envs() print_menu(envs) if __name__ == "__main__": main()
Python
0.000063
a4a01c466c916f5c4ff44d40bc5e052e98951f1d
Bump version
sqlitebiter/__version__.py
sqlitebiter/__version__.py
__author__ = "Tsuyoshi Hombashi" __copyright__ = "Copyright 2016, {}".format(__author__) __license__ = "MIT License" __version__ = "0.29.1" __maintainer__ = __author__ __email__ = "tsuyoshi.hombashi@gmail.com"
__author__ = "Tsuyoshi Hombashi" __copyright__ = "Copyright 2016, {}".format(__author__) __license__ = "MIT License" __version__ = "0.29.0" __maintainer__ = __author__ __email__ = "tsuyoshi.hombashi@gmail.com"
Python
0
05458457f12618cc69970cd2bda87e25e29384a4
simplify the code (Thx Stefan)
doc/examples/plot_peak_local_max.py
doc/examples/plot_peak_local_max.py
""" ==================== Finding local maxima ==================== The ``peak_local_max`` function returns the coordinates of local peaks (maxima) in an image. A maximum filter is used for finding local maxima. This operation dilates the original image and merges neighboring local maxima closer than the size of the dilation. Locations where the original image is equal to the dilated image are returned as local maxima. """ from scipy import ndimage import matplotlib.pyplot as plt from skimage.feature import peak_local_max from skimage import data, img_as_float im = img_as_float(data.coins()) # image_max is the dilation of im with a 20*20 structuring element # It is used within peak_local_max function image_max = ndimage.maximum_filter(im, size=20, mode='constant') # Comparison between image_max and im to find the coordinates of local maxima coordinates = peak_local_max(im, min_distance=20) # display results fig, ax = plt.subplots(1, 3, figsize=(8, 3)) ax1, ax2, ax3 = ax.ravel() ax1.imshow(im, cmap=plt.cm.gray) ax1.axis('off') ax1.set_title('Original') ax2.imshow(image_max, cmap=plt.cm.gray) ax2.axis('off') ax2.set_title('Maximum filter') ax3.imshow(im, cmap=plt.cm.gray) ax3.autoscale(False) ax3.plot(coordinates[:, 1], coordinates[:, 0], 'r.') ax3.axis('off') ax3.set_title('Peak local max') fig.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0.02, left=0.02, right=0.98) plt.show()
""" ==================== Finding local maxima ==================== The ``peak_local_max`` function returns the coordinates of local peaks (maxima) in an image. A maximum filter is used for finding local maxima. This operation dilates the original image and merges neighboring local maxima closer than the size of the dilation. Locations where the original image is equal to the dilated image are returned as local maxima. """ from scipy import ndimage import matplotlib.pyplot as plt from skimage.feature import peak_local_max from skimage import data, img_as_float im = img_as_float(data.coins()) # image_max is the dilation of im with a 20*20 structuring element # It is used within peak_local_max function image_max = ndimage.maximum_filter(im, size=20, mode='constant') # Comparison between image_max and im to find the coordinates of local maxima coordinates = peak_local_max(im, min_distance=20) # display results fig, ax = plt.subplots(1, 3, figsize=(8, 3)) ax1, ax2, ax3 = ax.ravel() ax1.imshow(im, cmap=plt.cm.gray) ax1.axis('off') ax1.set_title('Original') ax2.imshow(image_max, cmap=plt.cm.gray) ax2.axis('off') ax2.set_title('Maximum filter') ax3.imshow(im, cmap=plt.cm.gray) ax3.autoscale(False) ax3.plot([p[1] for p in coordinates], [p[0] for p in coordinates], 'r.') ax3.axis('off') ax3.set_title('Peak local max') fig.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0.02, left=0.02, right=0.98) plt.show()
Python
0.000001
e00a82a31de820f28474cb5de47c5715dafd8d18
use the largest remainder method for distributing change in ratio_split()
hordak/utilities/money.py
hordak/utilities/money.py
from decimal import Decimal from hordak.defaults import DECIMAL_PLACES def ratio_split(amount, ratios): """ Split in_value according to the ratios specified in `ratios` This is special in that it ensures the returned values always sum to in_value (i.e. we avoid losses or gains due to rounding errors). As a result, this method returns a list of `Decimal` values with length equal to that of `ratios`. Examples: .. code-block:: python >>> from hordak.utilities.money import ratio_split >>> from decimal import Decimal >>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')]) [Decimal('3.33'), Decimal('6.67')] Note the returned values sum to the original input of ``10``. If we were to do this calculation in a naive fashion then the returned values would likely be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing ``0.01``. Args: amount (Decimal): The amount to be split ratios (list[Decimal]): The ratios that will determine the split Returns: list(Decimal) """ precision = Decimal(10) ** Decimal(-DECIMAL_PLACES) assert amount == amount.quantize(precision) # Distribute the amount according to the ratios: ratio_total = sum(ratios) values = [amount * ratio / ratio_total for ratio in ratios] # Now round the values to the desired number of decimal places: rounded = [v.quantize(precision) for v in values] # The rounded values may not add up to the exact amount. # Use the Largest Remainder algorithm to distribute the # difference between participants with non-zero ratios: participants = [i for i in range(len(ratios)) if ratios[i] != Decimal(0)] for p in sorted(participants, key=lambda i: rounded[i] - values[i]): total = sum(rounded) if total < amount: rounded[p] += precision elif total > amount: rounded[p] -= precision else: break assert sum(rounded) == amount return rounded
from decimal import Decimal def ratio_split(amount, ratios): """ Split in_value according to the ratios specified in `ratios` This is special in that it ensures the returned values always sum to in_value (i.e. we avoid losses or gains due to rounding errors). As a result, this method returns a list of `Decimal` values with length equal to that of `ratios`. Examples: .. code-block:: python >>> from hordak.utilities.money import ratio_split >>> from decimal import Decimal >>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')]) [Decimal('3.33'), Decimal('6.67')] Note the returned values sum to the original input of ``10``. If we were to do this calculation in a naive fashion then the returned values would likely be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing ``0.01``. Args: amount (Decimal): The amount to be split ratios (list[Decimal]): The ratios that will determine the split Returns: list(Decimal) """ ratio_total = sum(ratios) divided_value = amount / ratio_total values = [] for ratio in ratios: value = divided_value * ratio values.append(value) # Now round the values, keeping track of the bits we cut off rounded = [v.quantize(Decimal("0.01")) for v in values] remainders = [v - rounded[i] for i, v in enumerate(values)] remainder = sum(remainders) # Give the last person the (positive or negative) remainder rounded[-1] = (rounded[-1] + remainder).quantize(Decimal("0.01")) assert sum(rounded) == amount return rounded
Python
0
29d151366d186ed75da947f2861741ed87af902b
Add missing import to settings
website/addons/badges/settings/__init__.py
website/addons/badges/settings/__init__.py
# -*- coding: utf-8 -*- import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
Python
0.000001
6c64674447bd988eef80a4a927acde2eabe04236
Modify error messag
googkit/lib/plugin.py
googkit/lib/plugin.py
import os import googkit.lib.path from googkit.lib.error import GoogkitError INIT_FILE = '__init__.py' COMMAND_FILE = 'command.py' def load(tree): base_dir = googkit.lib.path.plugin() for filename in os.listdir(base_dir): plugin_dir = os.path.join(base_dir, filename) if not os.path.isdir(plugin_dir): continue init_path = os.path.join(plugin_dir, INIT_FILE) if not os.path.exists(init_path): raise GoogkitError('{init_path} is not found.'.format(init_path=init_path)) command_path = os.path.join(plugin_dir, COMMAND_FILE) if not os.path.exists(command_path): continue module_name = 'plugins.{filename}.command'.format(filename=filename) module = __import__(module_name, fromlist=['command']) if not hasattr(module, 'register'): raise GoogkitError('No register method found for plugin: ' + module_name) module.register(tree)
import os import googkit.lib.path from googkit.lib.error import GoogkitError INIT_FILE = '__init__.py' COMMAND_FILE = 'command.py' def load(tree): base_dir = googkit.lib.path.plugin() for filename in os.listdir(base_dir): plugin_dir = os.path.join(base_dir, filename) if not os.path.isdir(plugin_dir): continue init_path = os.path.join(plugin_dir, INIT_FILE) if not os.path.exists(init_path): raise GoogkitError('{init_path} is not found.'.format(init_path=init_path)) command_path = os.path.join(plugin_dir, COMMAND_FILE) if not os.path.exists(command_path): continue module_name = 'plugins.{filename}.command'.format(filename=filename) module = __import__(module_name, fromlist=['command']) if not hasattr(module, 'register'): msg = 'Invalid plugin {module_name} do not have register method.'.format( module_name=module_name) raise GoogkitError(msg) module.register(tree)
Python
0.000001
1b84cc660848fdee7ed68c17772542956f47e89d
Add `lower` parameter to grab.tools.russian::slugify method
grab/tools/russian.py
grab/tools/russian.py
# coding: utf-8 from __future__ import absolute_import from ..tools.encoding import smart_unicode from pytils.translit import translify import re MONTH_NAMES = u'января февраля марта апреля мая июня июля августа '\ u'сентября октября ноября декабря'.split() RE_NOT_ENCHAR = re.compile(u'[^-a-zA-Z0-9]', re.U) RE_NOT_ENRUCHAR = re.compile(u'[^-a-zA-Zа-яА-ЯёЁ0-9]', re.U) RE_RUSSIAN_CHAR = re.compile(u'[а-яА-ЯёЁ]', re.U) RE_DASH = re.compile(r'-+') def slugify(value, limit=None, default='', lower=True): value = smart_unicode(value) # Replace all non russian/english chars with "-" char # to help pytils not to crash value = RE_NOT_ENRUCHAR.sub('-', value) # Do transliteration value = translify(value) # Replace trash with safe "-" char value = RE_NOT_ENCHAR.sub('-', value).strip('-') if lower: value = value.lower() # Replace sequences of dashes value = RE_DASH.sub('-', value) if limit is not None: value = value[:limit] if value != "": return value else: return default def get_month_number(name): return MONTH_NAMES.index(name) + 1
# coding: utf-8 from __future__ import absolute_import from ..tools.encoding import smart_unicode from pytils.translit import translify import re MONTH_NAMES = u'января февраля марта апреля мая июня июля августа '\ u'сентября октября ноября декабря'.split() RE_NOT_ENCHAR = re.compile(u'[^-a-zA-Z0-9]', re.U) RE_NOT_ENRUCHAR = re.compile(u'[^-a-zA-Zа-яА-ЯёЁ0-9]', re.U) RE_RUSSIAN_CHAR = re.compile(u'[а-яА-ЯёЁ]', re.U) RE_DASH = re.compile(r'-+') def slugify(value, limit=None, default=''): value = smart_unicode(value) # Replace all non russian/english chars with "-" char # to help pytils not to crash value = RE_NOT_ENRUCHAR.sub('-', value) # Do transliteration value = translify(value) # Replace trash with safe "-" char value = RE_NOT_ENCHAR.sub('-', value).strip('-').lower() # Replace sequences of dashes value = RE_DASH.sub('-', value) if limit is not None: value = value[:limit] if value != "": return value else: return default def get_month_number(name): return MONTH_NAMES.index(name) + 1
Python
0.000001
88f0faa73beeafc30248210c4c6b99b7a9ccbdba
Add AUTOMATIC_REVERSE_PTR option to cfg
config_template.py
config_template.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) # BASIC APP CONFIG WTF_CSRF_ENABLED = True SECRET_KEY = 'We are the world' BIND_ADDRESS = '127.0.0.1' PORT = 9393 LOGIN_TITLE = "PDNS" # TIMEOUT - for large zones TIMEOUT = 10 # LOG CONFIG LOG_LEVEL = 'DEBUG' LOG_FILE = 'logfile.log' # For Docker, leave empty string #LOG_FILE = '' # Upload UPLOAD_DIR = os.path.join(basedir, 'upload') # DATABASE CONFIG #You'll need MySQL-python SQLA_DB_USER = 'powerdnsadmin' SQLA_DB_PASSWORD = 'powerdnsadminpassword' SQLA_DB_HOST = 'mysqlhostorip' SQLA_DB_NAME = 'powerdnsadmin' #MySQL SQLALCHEMY_DATABASE_URI = 'mysql://'+SQLA_DB_USER+':'\ +SQLA_DB_PASSWORD+'@'+SQLA_DB_HOST+'/'+SQLA_DB_NAME #SQLite #SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/your/pdns.db' SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = True # LDAP CONFIG LDAP_TYPE = 'ldap' LDAP_URI = 'ldaps://your-ldap-server:636' LDAP_USERNAME = 'cn=dnsuser,ou=users,ou=services,dc=duykhanh,dc=me' LDAP_PASSWORD = 'dnsuser' LDAP_SEARCH_BASE = 'ou=System Admins,ou=People,dc=duykhanh,dc=me' # Additional options only if LDAP_TYPE=ldap LDAP_USERNAMEFIELD = 'uid' LDAP_FILTER = '(objectClass=inetorgperson)' ## AD CONFIG #LDAP_TYPE = 'ad' #LDAP_URI = 'ldaps://your-ad-server:636' #LDAP_USERNAME = 'cn=dnsuser,ou=Users,dc=domain,dc=local' #LDAP_PASSWORD = 'dnsuser' #LDAP_SEARCH_BASE = 'dc=domain,dc=local' ## You may prefer 'userPrincipalName' instead #LDAP_USERNAMEFIELD = 'sAMAccountName' ## AD Group that you would like to have accesss to web app #LDAP_FILTER = 'memberof=cn=DNS_users,ou=Groups,dc=domain,dc=local' # Github Oauth GITHUB_OAUTH_ENABLE = False GITHUB_OAUTH_KEY = 'G0j1Q15aRsn36B3aD6nwKLiYbeirrUPU8nDd1wOC' GITHUB_OAUTH_SECRET = '0WYrKWePeBDkxlezzhFbDn1PBnCwEa0vCwVFvy6iLtgePlpT7WfUlAa9sZgm' GITHUB_OAUTH_SCOPE = 'email' GITHUB_OAUTH_URL = 'http://127.0.0.1:5000/api/v3/' GITHUB_OAUTH_TOKEN = 'http://127.0.0.1:5000/oauth/token' GITHUB_OAUTH_AUTHORIZE = 'http://127.0.0.1:5000/oauth/authorize' #Default Auth BASIC_ENABLED = True SIGNUP_ENABLED = True # POWERDNS CONFIG PDNS_STATS_URL = 'http://172.16.214.131:8081/' PDNS_API_KEY = 'you never know' PDNS_VERSION = '3.4.7' # RECORDS ALLOWED TO EDIT RECORDS_ALLOW_EDIT = ['A', 'AAAA', 'CNAME', 'SPF', 'PTR', 'MX', 'TXT'] # EXPERIMENTAL FEATURES PRETTY_IPV6_PTR = False # Create reverse lookup domain if not exists and PTR record from # A and AAAA records AUTOMATIC_REVERSE_PTR = False
import os basedir = os.path.abspath(os.path.dirname(__file__)) # BASIC APP CONFIG WTF_CSRF_ENABLED = True SECRET_KEY = 'We are the world' BIND_ADDRESS = '127.0.0.1' PORT = 9393 LOGIN_TITLE = "PDNS" # TIMEOUT - for large zones TIMEOUT = 10 # LOG CONFIG LOG_LEVEL = 'DEBUG' LOG_FILE = 'logfile.log' # For Docker, leave empty string #LOG_FILE = '' # Upload UPLOAD_DIR = os.path.join(basedir, 'upload') # DATABASE CONFIG #You'll need MySQL-python SQLA_DB_USER = 'powerdnsadmin' SQLA_DB_PASSWORD = 'powerdnsadminpassword' SQLA_DB_HOST = 'mysqlhostorip' SQLA_DB_NAME = 'powerdnsadmin' #MySQL SQLALCHEMY_DATABASE_URI = 'mysql://'+SQLA_DB_USER+':'\ +SQLA_DB_PASSWORD+'@'+SQLA_DB_HOST+'/'+SQLA_DB_NAME #SQLite #SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/your/pdns.db' SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = True # LDAP CONFIG LDAP_TYPE = 'ldap' LDAP_URI = 'ldaps://your-ldap-server:636' LDAP_USERNAME = 'cn=dnsuser,ou=users,ou=services,dc=duykhanh,dc=me' LDAP_PASSWORD = 'dnsuser' LDAP_SEARCH_BASE = 'ou=System Admins,ou=People,dc=duykhanh,dc=me' # Additional options only if LDAP_TYPE=ldap LDAP_USERNAMEFIELD = 'uid' LDAP_FILTER = '(objectClass=inetorgperson)' ## AD CONFIG #LDAP_TYPE = 'ad' #LDAP_URI = 'ldaps://your-ad-server:636' #LDAP_USERNAME = 'cn=dnsuser,ou=Users,dc=domain,dc=local' #LDAP_PASSWORD = 'dnsuser' #LDAP_SEARCH_BASE = 'dc=domain,dc=local' ## You may prefer 'userPrincipalName' instead #LDAP_USERNAMEFIELD = 'sAMAccountName' ## AD Group that you would like to have accesss to web app #LDAP_FILTER = 'memberof=cn=DNS_users,ou=Groups,dc=domain,dc=local' # Github Oauth GITHUB_OAUTH_ENABLE = False GITHUB_OAUTH_KEY = 'G0j1Q15aRsn36B3aD6nwKLiYbeirrUPU8nDd1wOC' GITHUB_OAUTH_SECRET = '0WYrKWePeBDkxlezzhFbDn1PBnCwEa0vCwVFvy6iLtgePlpT7WfUlAa9sZgm' GITHUB_OAUTH_SCOPE = 'email' GITHUB_OAUTH_URL = 'http://127.0.0.1:5000/api/v3/' GITHUB_OAUTH_TOKEN = 'http://127.0.0.1:5000/oauth/token' GITHUB_OAUTH_AUTHORIZE = 'http://127.0.0.1:5000/oauth/authorize' #Default Auth BASIC_ENABLED = True SIGNUP_ENABLED = True # POWERDNS CONFIG PDNS_STATS_URL = 'http://172.16.214.131:8081/' PDNS_API_KEY = 'you never know' PDNS_VERSION = '3.4.7' # RECORDS ALLOWED TO EDIT RECORDS_ALLOW_EDIT = ['A', 'AAAA', 'CNAME', 'SPF', 'PTR', 'MX', 'TXT'] # EXPERIMENTAL FEATURES PRETTY_IPV6_PTR = False
Python
0
0cc0d4a5ddf938f176c2384503ef88bb31c91898
Transform new schema to old schema, to keep share_v1 up to date
scrapi/processing/elasticsearch.py
scrapi/processing/elasticsearch.py
from __future__ import absolute_import import logging from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import ConnectionError from scrapi import settings from scrapi.processing.base import BaseProcessor from scrapi.base.transformer import JSONTransformer logger = logging.getLogger(__name__) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) logging.getLogger('elasticsearch').setLevel(logging.FATAL) logging.getLogger('elasticsearch.trace').setLevel(logging.FATAL) try: # If we cant connect to elastic search dont define this class es = Elasticsearch(settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT) # body = { # 'mappings': { # harvester: settings.ES_SEARCH_MAPPING # for harvester in registry.keys() # } # } # es.cluster.health(wait_for_status='yellow') es.indices.create(index=settings.ELASTIC_INDEX, body={}, ignore=400) es.indices.create(index='share_v1', ignore=400) except ConnectionError: # pragma: no cover logger.error('Could not connect to Elasticsearch, expect errors.') if 'elasticsearch' in settings.NORMALIZED_PROCESSING or 'elasticsearch' in settings.RAW_PROCESSING: raise class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized, index=settings.ELASTIC_INDEX): normalized['releaseDate'] = self.version(raw_doc, normalized) data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } es.index( body=data, refresh=True, index=index, doc_type=raw_doc['source'], id=raw_doc['docID'], ) self.process_normalized_v1(raw_doc, normalized) def version(self, raw, normalized): try: old_doc = es.get_source( index=settings.ELASTIC_INDEX, doc_type=raw['source'], id=raw['docID'] ) except NotFoundError: # pragma: no cover # Normally I don't like exception-driven logic, # but this was the best way to handle missing # types, indices and documents together date = normalized['releaseDate'] else: date = old_doc.get('releaseDate') or normalized['releaseDate'] return date def process_normalized_v1(self, raw_doc, normalized): index = 'share_v1' transformer = PreserveOldSchema() data = transformer.transform(normalized.attributes) es.index( body=data, refresh=True, index=index, doc_type=raw_doc['source'], id=raw_doc['docID'] ) class PreserveOldContributors(JSONTransformer): schema = { 'given': '/givenName', 'family': '/familyName', 'middle': '/additionalName', 'email': '/email' } def process_contributors(self, contributors): return [self.transform(contributor) for contributor in contributors] class PreserveOldSchema(JSONTransformer): schema = { 'title': '/title', 'description': '/description', 'tags': '/otherProperties/tags', 'contributors': ('/contributor', PreserveOldContributors().process_contributors), 'dateUpdated': '/releaseDate', 'source': '/source', 'id': { 'url': '/directLink' } }
from __future__ import absolute_import import logging from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from elasticsearch.exceptions import ConnectionError from scrapi import settings from scrapi.processing.base import BaseProcessor logger = logging.getLogger(__name__) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) logging.getLogger('elasticsearch').setLevel(logging.FATAL) logging.getLogger('elasticsearch.trace').setLevel(logging.FATAL) try: # If we cant connect to elastic search dont define this class es = Elasticsearch(settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT) # body = { # 'mappings': { # harvester: settings.ES_SEARCH_MAPPING # for harvester in registry.keys() # } # } # es.cluster.health(wait_for_status='yellow') es.indices.create(index=settings.ELASTIC_INDEX, body={}, ignore=400) except ConnectionError: # pragma: no cover logger.error('Could not connect to Elasticsearch, expect errors.') if 'elasticsearch' in settings.NORMALIZED_PROCESSING or 'elasticsearch' in settings.RAW_PROCESSING: raise class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized, index=settings.ELASTIC_INDEX): normalized['releaseDate'] = self.version(raw_doc, normalized) data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } es.index( body=data, refresh=True, index=index, doc_type=raw_doc['source'], id=raw_doc['docID'], ) def version(self, raw, normalized): try: old_doc = es.get_source( index=settings.ELASTIC_INDEX, doc_type=raw['source'], id=raw['docID'] ) except NotFoundError: # pragma: no cover # Normally I don't like exception-driven logic, # but this was the best way to handle missing # types, indices and documents together date = normalized['releaseDate'] else: date = old_doc.get('releaseDate') or normalized['releaseDate'] return date
Python
0
959897478bbda18f02aa6e38f2ebdd837581f1f0
Fix test for changed SctVerificationResult
tests/test_sct_verify_signature.py
tests/test_sct_verify_signature.py
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() assert verify_signature(signature_input, signature, pubkey) is True signature_input = b'some invalid signature input' assert verify_signature(signature_input, signature, pubkey) is False
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signature = open(flo('{basedir}/signature.der'), 'rb').read() pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read() got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is True assert got_output == 'Verified OK\n' assert got_cmd_res.exitcode == 0 signature_input = b'some invalid signature input' got_verified, got_output, got_cmd_res = \ verify_signature(signature_input, signature, pubkey) assert got_verified is False assert got_output == 'Verification Failure\n' assert got_cmd_res.exitcode == 1
Python
0.000001
f72277113ce8155a1725bb69929c83cb95183bd8
order events by room
pyconca2017/pycon_schedule/models.py
pyconca2017/pycon_schedule/models.py
from datetime import datetime from django.db import models """ Presentation """ class Speaker(models.Model): """ Who """ email = models.EmailField(unique=True) full_name = models.CharField(max_length=255) bio = models.TextField(default='') twitter_username = models.CharField(max_length=255, null=True, blank=True) company_name = models.CharField(max_length=255, null=True, blank=True) url = models.URLField(max_length=2048, null=True, blank=True) shirt_size = models.CharField(max_length=255) location = models.CharField(max_length=255, null=True, blank=True) is_keynote = models.BooleanField(default=False) def __str__(self): return self.full_name @property def twitter_url(self): if not self.twitter_username: return None return 'https://twitter.com/{}'.format(self.twitter_username) class Presentation(models.Model): """ What """ papercall_id = models.IntegerField(null=True, blank=True, unique=True) title = models.CharField(max_length=255) description = models.TextField(default='') notes = models.TextField(default='') abstract = models.TextField(default='') audience_level = models.CharField(max_length=255) presentation_format = models.CharField(max_length=255) speaker = models.ForeignKey(Speaker) def __str__(self): return self.title class Meta: ordering = ('title',) """ Schedule """ class Schedule(models.Model): """ When (what day) """ day = models.DateField(unique=True) def __str__(self): return self.day.strftime('%b %d') class Location(models.Model): """ Where """ name = models.CharField(max_length=255) order = models.PositiveIntegerField(default=0) capacity = models.PositiveIntegerField(default=0) notes = models.TextField(default='', blank=True) def __str__(self): return self.name class ScheduleSlot(models.Model): """ When (what time) """ schedule = models.ForeignKey(Schedule, related_name='slots') start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return '{} - {} ({})'.format(self.start_time, self.end_time, self.schedule) class Meta: unique_together = (('schedule', 'start_time', 'end_time'),) ordering = ('schedule', 'start_time', 'end_time') @property def duration(self): return datetime.combine(self.schedule.day, self.end_time) - datetime.combine(self.schedule.day, self.start_time) @property def start_events(self): return SlotEvent.objects.filter(slot__schedule=self.schedule, slot__start_time=self.start_time) class SlotEvent(models.Model): """ Glue what with when and where """ slot = models.ForeignKey(ScheduleSlot, related_name='events') location = models.ForeignKey(Location, null=True, blank=True) content = models.TextField(blank=True) presentation = models.OneToOneField(Presentation, null=True, blank=True) def __str__(self): return self.title class Meta: unique_together = ( ('slot', 'location'), ) ordering = ('location__name',) @property def title(self): if self.presentation: return self.presentation.title return self.content @property def is_presentation(self): return bool(self.presentation) @property def duration(self): return self.slot.duration @property def duration_str(self): return ':'.join(str(self.duration).split(':')[:2]) @property def presenter(self): if self.presentation: return self.presentation.speaker
from datetime import datetime from django.db import models """ Presentation """ class Speaker(models.Model): """ Who """ email = models.EmailField(unique=True) full_name = models.CharField(max_length=255) bio = models.TextField(default='') twitter_username = models.CharField(max_length=255, null=True, blank=True) company_name = models.CharField(max_length=255, null=True, blank=True) url = models.URLField(max_length=2048, null=True, blank=True) shirt_size = models.CharField(max_length=255) location = models.CharField(max_length=255, null=True, blank=True) is_keynote = models.BooleanField(default=False) def __str__(self): return self.full_name @property def twitter_url(self): if not self.twitter_username: return None return 'https://twitter.com/{}'.format(self.twitter_username) class Presentation(models.Model): """ What """ papercall_id = models.IntegerField(null=True, blank=True, unique=True) title = models.CharField(max_length=255) description = models.TextField(default='') notes = models.TextField(default='') abstract = models.TextField(default='') audience_level = models.CharField(max_length=255) presentation_format = models.CharField(max_length=255) speaker = models.ForeignKey(Speaker) def __str__(self): return self.title class Meta: ordering = ('title',) """ Schedule """ class Schedule(models.Model): """ When (what day) """ day = models.DateField(unique=True) def __str__(self): return self.day.strftime('%b %d') class Location(models.Model): """ Where """ name = models.CharField(max_length=255) order = models.PositiveIntegerField(default=0) capacity = models.PositiveIntegerField(default=0) notes = models.TextField(default='', blank=True) def __str__(self): return self.name class ScheduleSlot(models.Model): """ When (what time) """ schedule = models.ForeignKey(Schedule, related_name='slots') start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return '{} - {} ({})'.format(self.start_time, self.end_time, self.schedule) class Meta: unique_together = (('schedule', 'start_time', 'end_time'),) ordering = ('schedule', 'start_time', 'end_time') @property def duration(self): return datetime.combine(self.schedule.day, self.end_time) - datetime.combine(self.schedule.day, self.start_time) @property def start_events(self): return SlotEvent.objects.filter(slot__schedule=self.schedule, slot__start_time=self.start_time) class SlotEvent(models.Model): """ Glue what with when and where """ slot = models.ForeignKey(ScheduleSlot, related_name='events') location = models.ForeignKey(Location, null=True, blank=True) content = models.TextField(blank=True) presentation = models.OneToOneField(Presentation, null=True, blank=True) def __str__(self): return self.title class Meta: unique_together = ( ('slot', 'location'), ) @property def title(self): if self.presentation: return self.presentation.title return self.content @property def is_presentation(self): return bool(self.presentation) @property def duration(self): return self.slot.duration @property def duration_str(self): return ':'.join(str(self.duration).split(':')[:2]) @property def presenter(self): if self.presentation: return self.presentation.speaker
Python
0.998462
9cb554c13ae3cec85fd2a3bf0afd9ae2b6cca96a
Refactor target.py
construi/target.py
construi/target.py
import construi.console as console from compose.project import Project from compose.cli.docker_client import docker_client import dockerpty import sys class Target(object): def __init__(self, config): self.config = config self.project = Project.from_dicts( 'construi', config.services, docker_client()) @property def client(self): return self.project.client @property def commands(self): return self.config.construi['run'] @property def name(self): return self.config.construi['name'] @property def service(self): return self.project.get_service(self.name) def run(self): try: self.setup() for command in self.commands: self.run_command(command) console.progress('Done.') except KeyboardInterrupt: console.warn("\nBuild Interrupted.") sys.exit(1) finally: self.cleanup() def run_command(self, command): console.progress("> %s" % command) container = self.service.create_container( one_off=True, command=command, tty=False, stdin_open=True, detach=False ) try: dockerpty.start(self.client, container.id, interactive=False) if container.wait() != 0: console.error("\nBuild Failed.") sys.exit(1) finally: self.client.remove_container(container.id, force=True) def setup(self): console.progress('Building Images...') self.project.build() console.progress('Pulling Images...') self.project.pull() def cleanup(self): console.progress('Cleaning up...') self.project.kill() self.project.remove_stopped(None, v=True)
import construi.console as console from compose.project import Project from compose.cli.docker_client import docker_client import dockerpty import sys class Target(object): def __init__(self, config): self.config = config self.project = Project.from_dicts( 'construi', config.services, docker_client()) def run(self): try: self.setup() service = self.project.get_service(self.config.construi['name']) for cmd in self.config.construi['run']: console.progress("> %s" % cmd) container = service.create_container( one_off=True, command=cmd, tty=False, stdin_open=True, detach=False ) dockerpty.start( self.project.client, container.id, interactive=False) exit_code = container.wait() self.project.client.remove_container(container.id, force=True) if exit_code != 0: console.error("\nBuild Failed.") sys.exit(1) console.progress('Done.') except KeyboardInterrupt: console.warn("\nBuild Interrupted.") sys.exit(1) finally: self.cleanup() def setup(self): console.progress('Building Images...') self.project.build() console.progress('Pulling Images...') self.project.pull() def cleanup(self): console.progress('Cleaning up...') self.project.kill() self.project.remove_stopped(None, v=True)
Python
0.000002
b6a5dcef6a612098dc6abddec831980792c23ddf
Allow API key to be set in config for rottentomatoes_list
flexget/plugins/input/rottentomatoes_list.py
flexget/plugins/input/rottentomatoes_list.py
from __future__ import unicode_literals, division, absolute_import import logging from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.utils.cached_input import cached try: from flexget.plugins.api_rottentomatoes import lists except ImportError: raise plugin.DependencyError(issued_by='rottentomatoes_lookup', missing='api_rottentomatoes', message='rottentomatoes_lookup requires the `api_rottentomatoes` plugin') log = logging.getLogger('rottentomatoes_list') class RottenTomatoesList(object): """ Emits an entry for each movie in a Rotten Tomatoes list. Configuration: dvds: - top_rentals - upcoming movies: - box_office Possible lists are * dvds: top_rentals, current_releases, new_releases, upcoming * movies: box_office, in_theaters, opening, upcoming """ def __init__(self): # We could pull these from the API through lists.json but that's extra web/API key usage self.dvd_lists = ['top_rentals', 'current_releases', 'new_releases', 'upcoming'] self.movie_lists = ['box_office', 'in_theaters', 'opening', 'upcoming'] def validator(self): from flexget import validator root = validator.factory('dict') root.accept('list', key='dvds').accept('choice').accept_choices(self.dvd_lists) root.accept('list', key='movies').accept('choice').accept_choices(self.movie_lists) root.accept('text', key='api_key') return root @cached('rottentomatoes_list', persist='2 hours') def on_task_input(self, task, config): entries = [] api_key = config.get('api_key', None) for l_type, l_names in config.items(): if type(l_names) is not list: continue for l_name in l_names: results = lists(list_type=l_type, list_name=l_name, api_key=api_key) if results: for movie in results['movies']: if [entry for entry in entries if movie['title'] == entry.get('title')]: continue imdb_id = movie.get('alternate_ids', {}).get('imdb') if imdb_id: imdb_id = 'tt' + str(imdb_id) entries.append(Entry(title=movie['title'], rt_id=movie['id'], imdb_id=imdb_id, rt_name=movie['title'], url=movie['links']['alternate'])) else: log.critical('Failed to fetch Rotten tomatoes %s list: %s. List doesn\'t exist?' % (l_type, l_name)) return entries @event('plugin.register') def register_plugin(): plugin.register(RottenTomatoesList, 'rottentomatoes_list', api_ver=2)
from __future__ import unicode_literals, division, absolute_import import logging from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.utils.cached_input import cached try: from flexget.plugins.api_rottentomatoes import lists except ImportError: raise plugin.DependencyError(issued_by='rottentomatoes_lookup', missing='api_rottentomatoes', message='rottentomatoes_lookup requires the `api_rottentomatoes` plugin') log = logging.getLogger('rottentomatoes_list') class RottenTomatoesList(object): """ Emits an entry for each movie in a Rotten Tomatoes list. Configuration: dvds: - top_rentals - upcoming movies: - box_office Possible lists are * dvds: top_rentals, current_releases, new_releases, upcoming * movies: box_office, in_theaters, opening, upcoming """ def __init__(self): # We could pull these from the API through lists.json but that's extra web/API key usage self.dvd_lists = ['top_rentals', 'current_releases', 'new_releases', 'upcoming'] self.movie_lists = ['box_office', 'in_theaters', 'opening', 'upcoming'] def validator(self): from flexget import validator root = validator.factory('dict') root.accept('list', key='dvds').accept('choice').accept_choices(self.dvd_lists) root.accept('list', key='movies').accept('choice').accept_choices(self.movie_lists) return root @cached('rottentomatoes_list', persist='2 hours') def on_task_input(self, task, config): entries = [] for l_type, l_names in config.items(): for l_name in l_names: results = lists(list_type=l_type, list_name=l_name) if results: for movie in results['movies']: if [entry for entry in entries if movie['title'] == entry.get('title')]: continue imdb_id = movie.get('alternate_ids', {}).get('imdb') if imdb_id: imdb_id = 'tt' + str(imdb_id) entries.append(Entry(title=movie['title'], rt_id=movie['id'], imdb_id=imdb_id, rt_name=movie['title'], url=movie['links']['alternate'])) else: log.critical('Failed to fetch Rotten tomatoes %s list: %s. List doesn\'t exist?' % (l_type, l_name)) return entries @event('plugin.register') def register_plugin(): plugin.register(RottenTomatoesList, 'rottentomatoes_list', api_ver=2)
Python
0
e73d69d258ab595ee8353efd85a6f37829b47b2b
update docstring
pysat/instruments/methods/general.py
pysat/instruments/methods/general.py
# -*- coding: utf-8 -*- """Provides generalized routines for integrating instruments into pysat. """ from __future__ import absolute_import, division, print_function import pandas as pds import pysat import logging logger = logging.getLogger(__name__) def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): """Return a Pandas Series of every file for chosen satellite data. This routine provides a standard interfacefor pysat instrument modules. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>. (default=None) sat_id : (string or NoneType) Specifies the satellite ID for a constellation. Not used. (default=None) data_path : (string or NoneType) Path to data directory. If None is specified, the value previously set in Instrument.files.data_path is used. (default=None) format_str : (string or NoneType) User specified file format. If None is specified, the default formats associated with the supplied tags are used. (default=None) supported_tags : (dict or NoneType) keys are sat_id, each containing a dict keyed by tag where the values file format template strings. (default=None) fake_daily_files_from_monthly : bool Some CDAWeb instrument data files are stored by month, interfering with pysat's functionality of loading by day. This flag, when true, appends daily dates to monthly files internally. These dates are used by load routine in this module to provide data by day. two_digit_year_break : int If filenames only store two digits for the year, then '1900' will be added for years >= two_digit_year_break and '2000' will be added for years < two_digit_year_break. Returns -------- pysat.Files.from_os : (pysat._files.Files) A class containing the verified available files Examples -------- :: fname = 'cnofs_vefi_bfield_1sec_{year:04d}{month:02d}{day:02d}_v05.cdf' supported_tags = {'dc_b': fname} list_files = functools.partial(nasa_cdaweb.list_files, supported_tags=supported_tags) fname = 'cnofs_cindi_ivm_500ms_{year:4d}{month:02d}{day:02d}_v01.cdf' supported_tags = {'': fname} list_files = functools.partial(mm_gen.list_files, supported_tags=supported_tags) """ if data_path is not None: if format_str is None: try: format_str = supported_tags[sat_id][tag] except KeyError as estr: raise ValueError('Unknown sat_id or tag: ' + estr) out = pysat.Files.from_os(data_path=data_path, format_str=format_str) if (not out.empty) and fake_daily_files_from_monthly: out.loc[out.index[-1] + pds.DateOffset(months=1) - pds.DateOffset(days=1)] = out.iloc[-1] out = out.asfreq('D', 'pad') out = out + '_' + out.index.strftime('%Y-%m-%d') return out return out else: estr = ''.join(('A directory must be passed to the loading routine ', 'for <Instrument Code>')) raise ValueError(estr)
# -*- coding: utf-8 -*- """Provides generalized routines for integrating instruments into pysat. """ from __future__ import absolute_import, division, print_function import pandas as pds import pysat import logging logger = logging.getLogger(__name__) def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): """Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>. (default=None) sat_id : (string or NoneType) Specifies the satellite ID for a constellation. Not used. (default=None) data_path : (string or NoneType) Path to data directory. If None is specified, the value previously set in Instrument.files.data_path is used. (default=None) format_str : (string or NoneType) User specified file format. If None is specified, the default formats associated with the supplied tags are used. (default=None) supported_tags : (dict or NoneType) keys are sat_id, each containing a dict keyed by tag where the values file format template strings. (default=None) fake_daily_files_from_monthly : bool Some CDAWeb instrument data files are stored by month, interfering with pysat's functionality of loading by day. This flag, when true, appends daily dates to monthly files internally. These dates are used by load routine in this module to provide data by day. two_digit_year_break : int If filenames only store two digits for the year, then '1900' will be added for years >= two_digit_year_break and '2000' will be added for years < two_digit_year_break. Returns -------- pysat.Files.from_os : (pysat._files.Files) A class containing the verified available files Examples -------- :: fname = 'cnofs_vefi_bfield_1sec_{year:04d}{month:02d}{day:02d}_v05.cdf' supported_tags = {'dc_b': fname} list_files = functools.partial(nasa_cdaweb.list_files, supported_tags=supported_tags) fname = 'cnofs_cindi_ivm_500ms_{year:4d}{month:02d}{day:02d}_v01.cdf' supported_tags = {'': fname} list_files = functools.partial(mm_gen.list_files, supported_tags=supported_tags) """ if data_path is not None: if format_str is None: try: format_str = supported_tags[sat_id][tag] except KeyError as estr: raise ValueError('Unknown sat_id or tag: ' + estr) out = pysat.Files.from_os(data_path=data_path, format_str=format_str) if (not out.empty) and fake_daily_files_from_monthly: out.loc[out.index[-1] + pds.DateOffset(months=1) - pds.DateOffset(days=1)] = out.iloc[-1] out = out.asfreq('D', 'pad') out = out + '_' + out.index.strftime('%Y-%m-%d') return out return out else: estr = ''.join(('A directory must be passed to the loading routine ', 'for <Instrument Code>')) raise ValueError(estr)
Python
0
6b6d3779cd23c188c808387b9f4095ea75da3284
Add a way to get the resources depended on by an output
heat/engine/output.py
heat/engine/output.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import six from heat.common import exception from heat.engine import function class OutputDefinition(object): """A definition of a stack output, independent of any template format.""" def __init__(self, name, value, description=None): self.name = name self._value = value self._resolved_value = None self._description = description self._deps = None def validate(self, path=''): """Validate the output value without resolving it.""" function.validate(self._value, path) def required_resource_names(self): if self._deps is None: try: required_resources = function.dependencies(self._value) self._deps = set(six.moves.map(lambda rp: rp.name, required_resources)) except (exception.InvalidTemplateAttribute, exception.InvalidTemplateReference): # This output ain't gonna work anyway self._deps = set() return self._deps def dep_attrs(self, resource_name): """Iterate over attributes of a given resource that this references. Return an iterator over dependent attributes for specified resource_name in the output's value field. """ return function.dep_attrs(self._value, resource_name) def get_value(self): """Resolve the value of the output.""" if self._resolved_value is None: self._resolved_value = function.resolve(self._value) return self._resolved_value def description(self): """Return a description of the output.""" if self._description is None: return 'No description given' return six.text_type(self._description) def render_hot(self): def items(): if self._description is not None: yield 'description', self._description yield 'value', copy.deepcopy(self._value) return dict(items())
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import six from heat.engine import function class OutputDefinition(object): """A definition of a stack output, independent of any template format.""" def __init__(self, name, value, description=None): self.name = name self._value = value self._resolved_value = None self._description = description def validate(self, path=''): """Validate the output value without resolving it.""" function.validate(self._value, path) def dep_attrs(self, resource_name): """Iterate over attributes of a given resource that this references. Return an iterator over dependent attributes for specified resource_name in the output's value field. """ return function.dep_attrs(self._value, resource_name) def get_value(self): """Resolve the value of the output.""" if self._resolved_value is None: self._resolved_value = function.resolve(self._value) return self._resolved_value def description(self): """Return a description of the output.""" if self._description is None: return 'No description given' return six.text_type(self._description) def render_hot(self): def items(): if self._description is not None: yield 'description', self._description yield 'value', copy.deepcopy(self._value) return dict(items())
Python
0.99996
0f43efc9c611f4b8bd93a42f85db3e14106915ba
fix burst not work bug
pyspider/database/local/projectdb.py
pyspider/database/local/projectdb.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<roy@binux.me> # http://binux.me # Created on 2015-01-17 12:32:17 import os import re import six import logging from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB class ProjectDB(BaseProjectDB): """ProjectDB loading scripts from local file.""" def __init__(self, files): self.projects = {} for filename in files: project = self._build_project(filename) if not project: continue self.projects[project['name']] = project rate_re = re.compile(r'^\s*#\s*rate.*?(\d+(\.\d+)?)', re.I | re.M) burst_re = re.compile(r'^\s*#\s*burst.*?(\d+(\.\d+)?)', re.I | re.M) def _build_project(self, filename): try: with open(filename) as fp: script = fp.read() m = self.rate_re.search(script) if m: rate = float(m.group(1)) else: rate = 1 m = self.burst_re.search(script) if m: burst = float(m.group(1)) else: burst = 3 return { 'name': os.path.splitext(os.path.basename(filename))[0], 'group': None, 'status': 'RUNNING', 'script': script, 'comments': None, 'rate': rate, 'burst': burst, 'updatetime': os.path.getmtime(filename), } except OSError as e: logging.error('loading project script error: %s', e) return None def get_all(self, fields=None): for projectname in self.projects: yield self.get(projectname, fields) def get(self, name, fields=None): if name not in self.projects: return None project = self.projects[name] result = {} for f in fields or project: if f in project: result[f] = project[f] else: result[f] = None return result def check_update(self, timestamp, fields=None): for projectname, project in six.iteritems(self.projects): if project['updatetime'] > timestamp: yield self.get(projectname, fields)
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<roy@binux.me> # http://binux.me # Created on 2015-01-17 12:32:17 import os import re import six import logging from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB class ProjectDB(BaseProjectDB): """ProjectDB loading scripts from local file.""" def __init__(self, files): self.projects = {} for filename in files: project = self._build_project(filename) if not project: continue self.projects[project['name']] = project rate_re = re.compile(r'^\s*#\s*rate.*(\d+(\.\d+)?)', re.I) burst_re = re.compile(r'^\s*#\s*burst.*(\d+(\.\d+)?)', re.I) def _build_project(self, filename): try: with open(filename) as fp: script = fp.read() m = self.rate_re.match(script) if m: rate = float(m.group(1)) else: rate = 1 m = self.burst_re.match(script) if m: burst = float(m.group(1)) else: burst = 3 return { 'name': os.path.splitext(os.path.basename(filename))[0], 'group': None, 'status': 'RUNNING', 'script': script, 'comments': None, 'rate': rate, 'burst': burst, 'updatetime': os.path.getmtime(filename), } except OSError as e: logging.error('loading project script error: %s', e) return None def get_all(self, fields=None): for projectname in self.projects: yield self.get(projectname, fields) def get(self, name, fields=None): if name not in self.projects: return None project = self.projects[name] result = {} for f in fields or project: if f in project: result[f] = project[f] else: result[f] = None return result def check_update(self, timestamp, fields=None): for projectname, project in six.iteritems(self.projects): if project['updatetime'] > timestamp: yield self.get(projectname, fields)
Python
0.000001
74e4d69a6ab501e11ff266d1ad77992d0203729f
Include os stuff
thumbor_rackspace/loaders/cloudfiles_loader.py
thumbor_rackspace/loaders/cloudfiles_loader.py
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2013 theiconic.com.au development@theiconic.com.au from os.path import join, expanduser import pyrax def load(context, path, callback): if(context.config.RACKSPACE_PYRAX_REGION): pyrax.set_default_region(context.config.RACKSPACE_PYRAX_REGION) pyrax.set_credential_file(expanduser(context.config.RACKSPACE_PYRAX_CFG)) cf = pyrax.connect_to_cloudfiles(public=context.config.RACKSPACE_PYRAX_PUBLIC) cont = cf.get_container(context.config.RACKSPACE_LOADER_CONTAINER) file_abspath = normalize_path(context) try: logger.debug("[LOADER] getting from %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath)) obj = cont.get_object(file_abspath) if obj: logger.debug("[LOADER] Found object at %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath)) else: logger.warning("[LOADER] Unable to find object %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath )) except: callback(None) callback(obj.get()) def normalize_path(context): path = join(context.config.RACKSPACE_LOADER_CONTAINER_ROOT.rstrip('/'), contenxt.request.url.lstrip('/')) path = path.replace('http://', '') return path
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/globocom/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2013 theiconic.com.au development@theiconic.com.au import pyrax def load(context, path, callback): if(context.config.RACKSPACE_PYRAX_REGION): pyrax.set_default_region(context.config.RACKSPACE_PYRAX_REGION) pyrax.set_credential_file(expanduser(context.config.RACKSPACE_PYRAX_CFG)) cf = pyrax.connect_to_cloudfiles(public=context.config.RACKSPACE_PYRAX_PUBLIC) cont = cf.get_container(context.config.RACKSPACE_LOADER_CONTAINER) file_abspath = normalize_path(context) try: logger.debug("[LOADER] getting from %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath)) obj = cont.get_object(file_abspath) if obj: logger.debug("[LOADER] Found object at %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath)) else: logger.warning("[LOADER] Unable to find object %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath )) except: callback(None) callback(obj.get()) def normalize_path(context): path = join(context.config.RACKSPACE_LOADER_CONTAINER_ROOT.rstrip('/'), contenxt.request.url.lstrip('/')) path = path.replace('http://', '') return path
Python
0
d55210495fde133b8b76ee1f55e593dd43389e0e
Update to use new HTTP APIs.
src/livestreamer/plugins/ongamenet.py
src/livestreamer/plugins/ongamenet.py
from livestreamer.exceptions import NoStreamsError from livestreamer.plugin import Plugin from livestreamer.plugin.api import http from livestreamer.stream import RTMPStream import re class Ongamenet(Plugin): StreamURL = "http://dostream.lab.so/stream.php" SWFURL = "http://www.ongamenet.com/front/ongame/live/CJPlayer.swf" PageURL = "http://www.ongamenet.com" @classmethod def can_handle_url(self, url): return "ongamenet.com" in url def _get_streams(self): res = http.get(self.StreamURL, data={"from": "ongamenet"}) match = re.search("var stream = \"(.+?)\";", res.text) if not match: raise NoStreamsError(self.url) stream = match.group(1) match = re.search("var server = \"(.+?)\";", res.text) if not match: raise NoStreamsError(self.url) server = match.group(1) streams = {} streams["live"] = RTMPStream(self.session, { "rtmp": server, "playpath": stream, "swfUrl": self.SWFURL, "pageUrl": self.PageURL, "live": True, }) return streams __plugin__ = Ongamenet
from livestreamer.compat import str, bytes from livestreamer.exceptions import PluginError, NoStreamsError from livestreamer.plugin import Plugin from livestreamer.stream import RTMPStream from livestreamer.utils import urlget import re class Ongamenet(Plugin): StreamURL = "http://dostream.lab.so/stream.php" SWFURL = "http://www.ongamenet.com/front/ongame/live/CJPlayer.swf" PageURL = "http://www.ongamenet.com" @classmethod def can_handle_url(self, url): return "ongamenet.com" in url def _get_streams(self): res = urlget(self.StreamURL, data={"from": "ongamenet"}) match = re.search("var stream = \"(.+?)\";", res.text) if not match: raise NoStreamsError(self.url) stream = match.group(1) match = re.search("var server = \"(.+?)\";", res.text) if not match: raise NoStreamsError(self.url) server = match.group(1) streams = {} streams["live"] = RTMPStream(self.session, { "rtmp": server, "playpath": stream, "swfUrl": self.SWFURL, "pageUrl": self.PageURL, "live": True, }) return streams __plugin__ = Ongamenet
Python
0
e78d613f66df5f10b59e47b6cfce619182d1297f
Update run.py
src/main/app-resources/py-ndvi/run.py
src/main/app-resources/py-ndvi/run.py
#!/usr/bin/env python import site import os import sys site.addsitedir('/application/share/python/lib/python2.6/site-packages') #print sys.path #os.environ['PYTHONUSERBASE'] = '/application/share/python' #print 'Base:', site.USER_BASE #print 'Site:', site.USER_SITE import ndvi sys.path.append('/usr/lib/ciop/python/') import cioppy as ciop ciop.log('INFO', 'Calculating NDVI') # create an output folder for the results output.path = os.environ['TMPDIR'] + '/output' os.makedirs(output.path) # input comes from STDIN (standard input) for line in sys.stdin: ciop.log('INFO', 'input: ' + line) res = ciop.copy(line, os.environ['TMPDIR']) ciop.log('DEBUG', 'local path:' + res[0].rstrip('\n')) obj = ndvi.GDALCalcNDVI() obj.calc_ndvi(res[0].rstrip(), '/tmp/pippo.tif') pub = ciop.publish('/tmp/pippo.tif') metadata = [ "ical:dtstart=2001-01-10T14:00:00", "ical:dtend=2001-01-10T14:05:00", "dc:identifier=mydataset", "dct:spatial=MULTIPOLYGON(((25.55215 36.97701,24.740512 37.091395,24.496927 35.950137,25.284346 35.839142,25.55215 36.97701)))", "dclite4g:onlineResource=" + pub[0].rstrip()] metadata = [ "ical:dtstart=2001-01-10T14:00:00", "ical:dtend=2001-01-10T14:05:00", "dc:identifier=mydataset", "dct:spatial=MULTIPOLYGON(((25.55215 36.97701,24.740512 37.091395,24.496927 35.950137,25.284346 35.839142,25.55215 36.97701)))", "dclite4g:onlineResource=http://some.host.com/myproduct.tif"] ciop.log('DEBUG', 'Going to register') ciop.register('http://localhost/catalogue/sandbox/rdf', 'file:///application/py-ndvi/etc/series.rdf', metadata) ciop.publish('/tmp/pippo.tif', metalink = True) ciop.log('INFO', 'Done my share of the work!')
#!/usr/bin/env python import site import os import sys site.addsitedir('/application/share/python/lib/python2.6/site-packages') #print sys.path #os.environ['PYTHONUSERBASE'] = '/application/share/python' #print 'Base:', site.USER_BASE #print 'Site:', site.USER_SITE import ndvi sys.path.append('/usr/lib/ciop/python/') import cioppy as ciop ciop.log('INFO', 'Hello World') #myvar = ciop.getparam('param1') #ciop.log('DEBUG', 'value is: ' + myvar) # input comes from STDIN (standard input) for line in sys.stdin: ciop.log('INFO', 'input: ' + line) res = ciop.copy(line, os.environ['TMPDIR']) ciop.log('DEBUG', 'local path:' + res[0].rstrip('\n')) obj = ndvi.GDALCalcNDVI() obj.calc_ndvi(res[0].rstrip(), '/tmp/pippo.tif') pub = ciop.publish('/tmp/pippo.tif') metadata = [ "ical:dtstart=2001-01-10T14:00:00", "ical:dtend=2001-01-10T14:05:00", "dc:identifier=mydataset", "dct:spatial=MULTIPOLYGON(((25.55215 36.97701,24.740512 37.091395,24.496927 35.950137,25.284346 35.839142,25.55215 36.97701)))", "dclite4g:onlineResource=" + pub[0].rstrip()] metadata = [ "ical:dtstart=2001-01-10T14:00:00", "ical:dtend=2001-01-10T14:05:00", "dc:identifier=mydataset", "dct:spatial=MULTIPOLYGON(((25.55215 36.97701,24.740512 37.091395,24.496927 35.950137,25.284346 35.839142,25.55215 36.97701)))", "dclite4g:onlineResource=http://some.host.com/myproduct.tif"] ciop.log('DEBUG', 'Going to register') ciop.register('http://localhost/catalogue/sandbox/rdf', 'file:///application/py-ndvi/etc/series.rdf', metadata) ciop.publish('/tmp/pippo.tif', metalink = True) ciop.log('INFO', 'Done my share of the work!')
Python
0.000001
0048794fd6e71f58bf88d84ddefb1e9a0194efca
Fix the mock-image used in test-steps unittests.
tests/test_steps/test_source_extraction.py
tests/test_steps/test_source_extraction.py
import unittest import numpy as np from tkp.testutil import db_subs, data from ConfigParser import SafeConfigParser from tkp.config import parse_to_dict from tkp.testutil.data import default_job_config from tkp.testutil import Mock import tkp.steps.source_extraction import tkp.accessors class MockImage(Mock): def extract(self, *args, **kwargs): return self.__call__(*args, **kwargs) @property def rmsmap(self, *args, **kwargs): return np.zeros((1)) class TestSourceExtraction(unittest.TestCase): @classmethod def setUpClass(cls): cls.dataset_id = db_subs.create_dataset_8images() config = SafeConfigParser() config.read(default_job_config) config = parse_to_dict(config) cls.parset = config['source_extraction'] def test_extract_sources(self): image_path = data.fits_file tkp.steps.source_extraction.extract_sources(image_path, self.parset) def test_for_appropriate_arguments(self): # sourcefinder_image_from_accessor() should get a single positional # argument, which is the accessor, and four kwargs: back_sizex, # back_sizey, margin and radius. # The object it returns has an extract() method, which should have # been called with det, anl, force_beam and deblend_nthresh kwargs. image_path = data.fits_file mock_method = Mock(MockImage([])) orig_method = tkp.steps.source_extraction.sourcefinder_image_from_accessor tkp.steps.source_extraction.sourcefinder_image_from_accessor = mock_method tkp.steps.source_extraction.extract_sources(image_path, self.parset) tkp.steps.source_extraction.sourcefinder_image_from_accessor = orig_method # Arguments to sourcefinder_image_from_accessor() self.assertIn('radius', mock_method.callvalues[0][1]) self.assertIn('margin', mock_method.callvalues[0][1]) self.assertIn('back_size_x', mock_method.callvalues[0][1]) self.assertIn('back_size_y', mock_method.callvalues[0][1]) # Arguments to extract() self.assertIn('det', mock_method.returnvalue.callvalues[0][1]) self.assertIn('anl', mock_method.returnvalue.callvalues[0][1]) self.assertIn('force_beam', mock_method.returnvalue.callvalues[0][1]) self.assertIn('deblend_nthresh', mock_method.returnvalue.callvalues[0][1])
import unittest from tkp.testutil import db_subs, data from ConfigParser import SafeConfigParser from tkp.config import parse_to_dict from tkp.testutil.data import default_job_config from tkp.testutil import Mock import tkp.steps.source_extraction import tkp.accessors class MockImage(Mock): def extract(self, *args, **kwargs): return self.__call__(*args, **kwargs) class TestSourceExtraction(unittest.TestCase): @classmethod def setUpClass(cls): cls.dataset_id = db_subs.create_dataset_8images() config = SafeConfigParser() config.read(default_job_config) config = parse_to_dict(config) cls.parset = config['source_extraction'] def test_extract_sources(self): image_path = data.fits_file tkp.steps.source_extraction.extract_sources(image_path, self.parset) def test_for_appropriate_arguments(self): # sourcefinder_image_from_accessor() should get a single positional # argument, which is the accessor, and four kwargs: back_sizex, # back_sizey, margin and radius. # The object it returns has an extract() method, which should have # been called with det, anl, force_beam and deblend_nthresh kwargs. image_path = data.fits_file mock_method = Mock(MockImage([])) orig_method = tkp.steps.source_extraction.sourcefinder_image_from_accessor tkp.steps.source_extraction.sourcefinder_image_from_accessor = mock_method tkp.steps.source_extraction.extract_sources(image_path, self.parset) tkp.steps.source_extraction.sourcefinder_image_from_accessor = orig_method # Arguments to sourcefinder_image_from_accessor() self.assertIn('radius', mock_method.callvalues[0][1]) self.assertIn('margin', mock_method.callvalues[0][1]) self.assertIn('back_size_x', mock_method.callvalues[0][1]) self.assertIn('back_size_y', mock_method.callvalues[0][1]) # Arguments to extract() self.assertIn('det', mock_method.returnvalue.callvalues[0][1]) self.assertIn('anl', mock_method.returnvalue.callvalues[0][1]) self.assertIn('force_beam', mock_method.returnvalue.callvalues[0][1]) self.assertIn('deblend_nthresh', mock_method.returnvalue.callvalues[0][1])
Python
0
edf1e96e56272a10ad767f13e6e8cc886f98055c
Test consecutive Coordinator.heartbeat calls #17
tests/unit/test_stream/test_coordinator.py
tests/unit/test_stream/test_coordinator.py
import functools from bloop.stream.shard import Shard from . import build_get_records_responses def test_coordinator_repr(coordinator): coordinator.stream_arn = "repr-stream-arn" assert repr(coordinator) == "<Coordinator[repr-stream-arn]>" def test_heartbeat(coordinator, session): find_records_id = "id-find-records" no_records_id = "id-no-records" has_sequence_id = "id-has-sequence" # When "id-finds-records" gets a response, it should only advance once and return 3 records. records = build_get_records_responses(3, 1)[0] def mock_get_records(iterator_id): return { find_records_id: records, no_records_id: {}, has_sequence_id: {} }[iterator_id] session.get_stream_records.side_effect = mock_get_records make_shard = functools.partial(Shard, stream_arn=coordinator.stream_arn, shard_id="shard-id", session=session) coordinator.active.extend([ # Has a sequence number, should not be called during a heartbeat make_shard(iterator_id=has_sequence_id, iterator_type="at_sequence", sequence_number="sequence-number"), # No sequence number, should find records during a heartbeat make_shard(iterator_id=find_records_id, iterator_type="trim_horizon"), # No sequence number, should not find records during a heartbeat make_shard(iterator_id=no_records_id, iterator_type="latest"), ]) coordinator.heartbeat() assert session.get_stream_records.call_count == 2 session.get_stream_records.assert_any_call(find_records_id) session.get_stream_records.assert_any_call(no_records_id) assert len(coordinator.buffer) == 3 pairs = [coordinator.buffer.pop() for _ in range(len(coordinator.buffer))] sequence_numbers = [record["meta"]["sequence_number"] for (record, _) in pairs] assert sequence_numbers == [0, 1, 2] def test_heartbeat_until_sequence_number(coordinator, session): """After heartbeat() finds records for a shard, the shard doens't check during the next heartbeat.""" shard = Shard(stream_arn=coordinator.stream_arn, shard_id="shard-id", session=session, iterator_id="iterator-id", iterator_type="latest") coordinator.active.append(shard) session.get_stream_records.side_effect = build_get_records_responses(1) # First call fetches records from DynamoDB coordinator.heartbeat() assert coordinator.buffer assert shard.sequence_number is not None session.get_stream_records.assert_called_once_with("iterator-id") # Second call ships the shard, since it now has a sequence_number. coordinator.heartbeat() assert session.get_stream_records.call_count == 1
import functools from bloop.stream.shard import Shard from . import build_get_records_responses def test_coordinator_repr(coordinator): coordinator.stream_arn = "repr-stream-arn" assert repr(coordinator) == "<Coordinator[repr-stream-arn]>" def test_heartbeat_latest(coordinator, session): find_records_id = "id-find-records" no_records_id = "id-no-records" has_sequence_id = "id-has-sequence" # When "id-finds-records" gets a response, it should only advance once and return 3 records. records = build_get_records_responses(3, 1)[0] def mock_get_records(iterator_id): return { find_records_id: records, no_records_id: {}, has_sequence_id: {} }[iterator_id] session.get_stream_records.side_effect = mock_get_records make_shard = functools.partial(Shard, stream_arn=coordinator.stream_arn, shard_id="shard-id", session=session) coordinator.active.extend([ # Has a sequence number, should not be called during a heartbeat make_shard(iterator_id=has_sequence_id, iterator_type="at_sequence", sequence_number="sequence-number"), # No sequence number, should find records during a heartbeat make_shard(iterator_id=find_records_id, iterator_type="trim_horizon"), # No sequence number, should not find records during a heartbeat make_shard(iterator_id=no_records_id, iterator_type="latest"), ]) coordinator.heartbeat() assert session.get_stream_records.call_count == 2 session.get_stream_records.assert_any_call(find_records_id) session.get_stream_records.assert_any_call(no_records_id) assert len(coordinator.buffer) == 3 pairs = [coordinator.buffer.pop() for _ in range(len(coordinator.buffer))] sequence_numbers = [record["meta"]["sequence_number"] for (record, _) in pairs] assert sequence_numbers == [0, 1, 2]
Python
0
213d6a42d505fb7ca320873cafdc187cf65d10ed
add unit tests for escaping curlies
tests/unit/pypyr/format/string_test.py
tests/unit/pypyr/format/string_test.py
""""string.py unit tests.""" import pypyr.format.string import pytest def test_string_interpolate_works(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping {key1} the {key2} wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping down the valleys wild', ( "string interpolation incorrect") def test_string_interpolate_works_with_no_swaps(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping down the valleys wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping down the valleys wild', ( "string interpolation incorrect") def test_string_interpolate_escapes_double_curly(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping {{ down the valleys wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping { down the valleys wild', ( "string interpolation incorrect") def test_string_interpolate_escapes_double_curly_pair(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping {{down}} the valleys wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping {down} the valleys wild', ( "string interpolation incorrect") def test_single_curly_should_throw(): """pycode error should raise up to caller.""" with pytest.raises(ValueError): context = {'key1': 'value1'} input_string = '{key1} this { is {key2} string' pypyr.format.string.get_interpolated_string(input_string, context) def test_tag_not_in_context_should_throw(): """pycode error should raise up to caller.""" with pytest.raises(KeyError): context = {'key1': 'value1'} input_string = '{key1} this is {key2} string' pypyr.format.string.get_interpolated_string(input_string, context)
""""string.py unit tests.""" import pypyr.format.string import pytest def test_string_interpolate_works(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping {key1} the {key2} wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping down the valleys wild', ( "string interpolation incorrect") def test_string_interpolate_works_with_no_swaps(): context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'} input_string = 'Piping down the valleys wild' output = pypyr.format.string.get_interpolated_string(input_string, context) assert output == 'Piping down the valleys wild', ( "string interpolation incorrect") def test_tag_not_in_context_should_throw(): """pycode error should raise up to caller.""" with pytest.raises(KeyError): context = {'key1': 'value1'} input_string = '{key1} this is {key2} string' pypyr.format.string.get_interpolated_string(input_string, context)
Python
0
e84b2e11088878d44433bfc767b8abba79eca0a7
use environment variable for config folder
litleSdkPython/Configuration.py
litleSdkPython/Configuration.py
#Copyright (c) 2011-2012 Litle & Co. # #Permission is hereby granted, free of charge, to any person #obtaining a copy of this software and associated documentation #files (the "Software"), to deal in the Software without #restriction, including without limitation the rights to use, #copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the #Software is furnished to do so, subject to the following #conditions: # #The above copyright notice and this permission notice shall be #included in all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, #EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES #OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND #NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, #WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR #OTHER DEALINGS IN THE SOFTWARE. import os class Configuration(object): def __init__(self): self.version = 8.25 self.reportGroup = 'Default Report Group' self._url = 'Sandbox' self.proxy = None self.timeout = 65 self.printXml = False self.configFolder = os.environ['LITLE_SDK_CONFIG']\ if 'LITLE_SDK_CONFIG' in os.environ else os.path.expanduser('~') self.__LITLE_SDK_CONFIG = '.litle_Python_SDK_config' @property def url(self): return self._urlMapper(self._url) @url.setter def url(self, value): self._url = value def getConfigFileName(self): return self.__LITLE_SDK_CONFIG def _urlMapper(self,target): if (target == "Cert"): return 'https://cert.litle.com/vap/communicator/online' elif(target == "Sandbox"): return 'https://www.testlitle.com/sandbox/communicator/online' elif(target == "Precert"): return 'https://precert.litle.com/vap/communicator/online' elif(target == "Prod"): return 'https://production.litle.com/vap/communicator/online' else: return target
#Copyright (c) 2011-2012 Litle & Co. # #Permission is hereby granted, free of charge, to any person #obtaining a copy of this software and associated documentation #files (the "Software"), to deal in the Software without #restriction, including without limitation the rights to use, #copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the #Software is furnished to do so, subject to the following #conditions: # #The above copyright notice and this permission notice shall be #included in all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, #EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES #OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND #NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT #HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, #WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR #OTHER DEALINGS IN THE SOFTWARE. import os class Configuration(object): def __init__(self): self.version = 8.25 self.reportGroup = 'Default Report Group' self._url = 'Sandbox' self.proxy = None self.timeout = 65 self.printXml = False self.configFolder = os.path.expanduser('~') self.__LITLE_SDK_CONFIG = '.litle_Python_SDK_config' @property def url(self): return self._urlMapper(self._url) @url.setter def url(self, value): self._url = value def getConfigFileName(self): return self.__LITLE_SDK_CONFIG def _urlMapper(self,target): if (target == "Cert"): return 'https://cert.litle.com/vap/communicator/online' elif(target == "Sandbox"): return 'https://www.testlitle.com/sandbox/communicator/online' elif(target == "Precert"): return 'https://precert.litle.com/vap/communicator/online' elif(target == "Prod"): return 'https://production.litle.com/vap/communicator/online' else: return target
Python
0.000001
24e42d5d4a21c1f3ffd36a163b89ee7f39375945
Update P05_trafficLight add assertion to check for red light
books/AutomateTheBoringStuffWithPython/Chapter10/P05_trafficLight.py
books/AutomateTheBoringStuffWithPython/Chapter10/P05_trafficLight.py
# This program emulates traffic lights at intersections with assertions market_2nd = {"ns": "green", "ew": "red"} mission_16th = {"ns": "red", "ew": "green"} def switchLights(stoplight): for key in stoplight.keys(): if stoplight[key] == "green": stoplight[key] = "yellow" elif stoplight[key] == "yellow": stoplight[key] = "red" elif stoplight[key] == "red": stoplight[key] = "green" assert "red" in stoplight.values(), "Neither light is red! " + str(stoplight) switchLights(market_2nd)
# This program emulates traffic lights at intersections with assertions market_2nd = {"ns": "green", "ew": "red"} mission_16th = {"ns": "red", "ew": "green"} def switchLights(stoplight): for key in stoplight.keys(): if stoplight[key] == "green": stoplight[key] = "yellow" elif stoplight[key] == "yellow": stoplight[key] = "red" elif stoplight[key] == "red": stoplight[key] = "green" switchLights(market_2nd)
Python
0
36db4fe3efad221618684547f9e12ca31a9614fd
Update (un)mapping columns set
src/ggrc/utils/rules.py
src/ggrc/utils/rules.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mapping rules for Relationship validation and map:model import columns.""" import copy def get_mapping_rules(): """ Get mappings rules as defined in business_object.js Special cases: Aduit has direct mapping to Program with program_id Section has a direct mapping to Standard/Regulation/Poicy with directive_id """ from ggrc import snapshotter all_rules = set(['AccessGroup', 'Clause', 'Contract', 'Control', 'CycleTaskGroupObjectTask', 'DataAsset', 'Facility', 'Market', 'Objective', 'OrgGroup', 'Person', 'Policy', 'Process', 'Product', 'Program', 'Project', 'Regulation', 'Risk', 'Section', 'Standard', 'System', 'Threat', 'Vendor']) snapshots = snapshotter.rules.Types.all business_object_rules = { "AccessGroup": all_rules - set(['AccessGroup']), "Clause": all_rules - set(['Clause']), "Contract": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Control": all_rules, "CycleTaskGroupObjectTask": (all_rules - set(['CycleTaskGroupObjectTask'])), "DataAsset": all_rules, "Facility": all_rules, "Market": all_rules, "Objective": all_rules, "OrgGroup": all_rules, "Person": all_rules - set(['Person']), "Policy": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Process": all_rules, "Product": all_rules, "Program": all_rules - set(['Program']), "Project": all_rules, "Regulation": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Risk": all_rules - set(['Risk']), "Section": all_rules, "Standard": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "System": all_rules, "Threat": all_rules - set(['Threat']), "Vendor": all_rules, } # Audit and Audit-scope objects # Assessment and Issue have a special Audit field instead of map:audit business_object_rules.update({ "Audit": set(), "Assessment": snapshots | {"Issue"}, "Issue": snapshots | {"Assessment"}, }) return business_object_rules def get_unmapping_rules(): """Get unmapping rules from mapping dict.""" unmapping_rules = copy.deepcopy(get_mapping_rules()) # Audit and Audit-scope objects unmapping_rules["Audit"] = set() unmapping_rules["Assessment"] = {"Issue"} unmapping_rules["Issue"] = {"Assessment"} return unmapping_rules __all__ = [ "get_mapping_rules", "get_unmapping_rules", ]
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mapping rules for Relationship validation and map:model import columns.""" def get_mapping_rules(): """ Get mappings rules as defined in business_object.js Special cases: Aduit has direct mapping to Program with program_id Section has a direct mapping to Standard/Regulation/Poicy with directive_id """ # these rules are copy pasted from # src/ggrc/assets/javascripts/apps/base_widgets.js line: 9 # WARNING ######################################################## # Manually added Risks and threats to the list from base_widgets # ################################################################## # TODO: Read these rules from different modules and combine them here. all_rules = set(['AccessGroup', 'Assessment', 'Audit', 'Clause', 'Contract', 'Control', 'CycleTaskGroupObjectTask', 'DataAsset', 'Facility', 'Issue', 'Market', 'Objective', 'OrgGroup', 'Person', 'Policy', 'Process', 'Product', 'Program', 'Project', 'Regulation', 'Risk', 'Section', 'Standard', 'System', 'Threat', 'Vendor']) business_object_rules = { "AccessGroup": all_rules - set(['AccessGroup']), "Assessment": all_rules - set(['Assessment']), "Audit": all_rules - set(['CycleTaskGroupObjectTask', 'Audit', 'Risk', 'Threat']), "Clause": all_rules - set(['Clause']), "Contract": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Control": all_rules, "CycleTaskGroupObjectTask": all_rules - set(['CycleTaskGroupObjectTask', 'Audit']), "DataAsset": all_rules, "Facility": all_rules, "Issue": all_rules, "Market": all_rules, "Objective": all_rules, "OrgGroup": all_rules, "Person": all_rules - set(['Person']), "Policy": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Process": all_rules, "Product": all_rules, "Program": all_rules - set(['Program']), "Project": all_rules, "Regulation": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "Risk": all_rules - set(['Audit', 'Risk']), "Section": all_rules, "Standard": all_rules - set(['Policy', 'Regulation', 'Contract', 'Standard']), "System": all_rules, "Threat": all_rules - set(['Audit', 'Threat']), "Vendor": all_rules, } return business_object_rules def get_unmapping_rules(): """Get unmapping rules from mapping dict.""" return get_mapping_rules() __all__ = [ "get_mapping_rules", "get_unmapping_rules", ]
Python
0.000001
304a220e99694ec6b41a31db8150c7f4604f6ef5
Remove old logging import
flexget/components/notify/notifiers/gotify.py
flexget/components/notify/notifiers/gotify.py
from http import HTTPStatus from requests.exceptions import RequestException from urllib.parse import urljoin from flexget import plugin from flexget.event import event from flexget.plugin import PluginWarning from flexget.utils.requests import Session as RequestSession, TimedLimiter plugin_name = 'gotify' requests = RequestSession(max_retries=3) class GotifyNotifier(object): """ Example:: notify: entries: via: - gotify: url: <GOTIFY_SERVER_URL> token: <GOTIFY_TOKEN> priority: <PRIORITY> Configuration parameters are also supported from entries (eg. through set). """ schema = { 'type': 'object', 'properties': { 'url': {'format': 'url'}, 'token': {'type': 'string'}, 'priority': {'type': 'integer', 'default': 4}, }, 'required': [ 'token', 'url', ], 'additionalProperties': False, } def notify(self, title, message, config): """ Send a Gotify notification """ base_url = config['url'] api_endpoint = '/message' url = urljoin(base_url, api_endpoint) params = {'token': config['token']} priority = config['priority'] notification = {'title': title, 'message': message, 'priority': priority} # Make the request try: response = requests.post(url, params=params, json=notification) except RequestException as e: if e.response is not None: if e.response.status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): message = 'Invalid Gotify access token' else: message = e.response.json()['error']['message'] else: message = str(e) raise PluginWarning(message) @event('plugin.register') def register_plugin(): plugin.register(GotifyNotifier, plugin_name, api_ver=2, interfaces=['notifiers'])
import logging from http import HTTPStatus from requests.exceptions import RequestException from urllib.parse import urljoin from flexget import plugin from flexget.event import event from flexget.plugin import PluginWarning from flexget.utils.requests import Session as RequestSession, TimedLimiter plugin_name = 'gotify' log = logging.getLogger(plugin_name) requests = RequestSession(max_retries=3) class GotifyNotifier(object): """ Example:: notify: entries: via: - gotify: url: <GOTIFY_SERVER_URL> token: <GOTIFY_TOKEN> priority: <PRIORITY> Configuration parameters are also supported from entries (eg. through set). """ schema = { 'type': 'object', 'properties': { 'url': {'format': 'url'}, 'token': {'type': 'string'}, 'priority': {'type': 'integer', 'default': 4}, }, 'required': [ 'token', 'url', ], 'additionalProperties': False, } def notify(self, title, message, config): """ Send a Gotify notification """ base_url = config['url'] api_endpoint = '/message' url = urljoin(base_url, api_endpoint) params = {'token': config['token']} priority = config['priority'] notification = {'title': title, 'message': message, 'priority': priority} # Make the request try: response = requests.post(url, params=params, json=notification) except RequestException as e: if e.response is not None: if e.response.status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): message = 'Invalid Gotify access token' else: message = e.response.json()['error']['message'] else: message = str(e) raise PluginWarning(message) @event('plugin.register') def register_plugin(): plugin.register(GotifyNotifier, plugin_name, api_ver=2, interfaces=['notifiers'])
Python
0.000001
77ac4b3cc97731c0fcb387a10fadd1509e057a6d
update with main function and header
controller/test.py
controller/test.py
#!/usr/bin/python2.7 """ created_by: Micah Halter created_date: 2/28/2015 last_modified_by: Micah Halter last_modified_date: 3/2/2015 """ #imports import constants import sys sys.path.insert(0, "./view/") import viewAssessment import viewQuestion import viewTopic import viewSection import viewCourse import viewUser sys.path.insert(0, "./edit/") import editAssessment import editQuestion import editTopic import editSection import editCourse sys.path.insert(0, "./objects/") from assessment import Assessment from question import Question from topic import Topic from section import Section from course import Course from user import User # functions def main(): print(viewAssessment.byID(1).sortByTopic()) # running code if __name__ == "__main__": main()
#!/usr/bin/python2.7 import constants import sys sys.path.insert(0, "./view/") import viewAssessment import viewQuestion import viewTopic import viewSection import viewCourse import viewUser sys.path.insert(0, "./edit/") import editAssessment import editQuestion import editTopic import editSection import editCourse sys.path.insert(0, "./objects/") from assessment import Assessment from question import Question from topic import Topic from section import Section from course import Course from user import User print(viewAssessment.byID(1).sortByTopic())
Python
0
b8cec88e733237b94fafb2aa978dcb6b758c954f
Add string representation of Log
irclogview/models.py
irclogview/models.py
from django.db import models from django.core.urlresolvers import reverse from picklefield.fields import PickledObjectField from . import utils class Channel(models.Model): name = models.SlugField(max_length=50, unique=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __unicode__(self): return u'#%s' % self.name def get_absolute_url(self): return reverse('irclogview_channel', args=[self.name]) class Log(models.Model): channel = models.ForeignKey(Channel, db_index=True) date = models.DateField(db_index=True) mtime = models.DateTimeField() updated = models.DateTimeField(auto_now=True) content = PickledObjectField() class Meta: ordering = ['-date'] unique_together = ('channel', 'date') def __unicode__(self): return u'#%s - %s' % (self.channel.name, self.date.strftime('%Y-%m-%d')) def get_absolute_url(self): date = self.date return reverse('irclogview_show', args=[self.channel.name, '%04d' % date.year, '%02d' % date.month, '%02d' % date.day]) def content_dict(self): colors = utils.RainbowColor() for data in self.content: item = dict(zip(['time', 'type', 'name', 'text'], data)) item['name_color'] = item['type'] == 'act' \ and 'inherit' \ or colors.get_color(item['name']) yield item
from django.db import models from django.core.urlresolvers import reverse from picklefield.fields import PickledObjectField from . import utils class Channel(models.Model): name = models.SlugField(max_length=50, unique=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __unicode__(self): return u'#%s' % self.name def get_absolute_url(self): return reverse('irclogview_channel', args=[self.name]) class Log(models.Model): channel = models.ForeignKey(Channel, db_index=True) date = models.DateField(db_index=True) mtime = models.DateTimeField() updated = models.DateTimeField(auto_now=True) content = PickledObjectField() class Meta: ordering = ['-date'] unique_together = ('channel', 'date') def get_absolute_url(self): date = self.date return reverse('irclogview_show', args=[self.channel.name, '%04d' % date.year, '%02d' % date.month, '%02d' % date.day]) def content_dict(self): colors = utils.RainbowColor() for data in self.content: item = dict(zip(['time', 'type', 'name', 'text'], data)) item['name_color'] = item['type'] == 'act' \ and 'inherit' \ or colors.get_color(item['name']) yield item
Python
0.999989
28fd64565ea2e7b1e40e88e6121936d03a77b444
Fix task set generator.
generic-8-link/generated/generate_task_set.py
generic-8-link/generated/generate_task_set.py
#!/usr/bin/python template = ''' environment {{ robot_filename: "../robot/setup.robot" environment_filename: "../environment/obstacles_{1_difficulty}.stl" max_underestimate: 20.0 }} generator {{ type: {2_generator_type} seed: {6_seed} keys: 2 keys: 3 keys: 5 keys: 7 keys: 11 keys: 13 keys: 17 keys: 19 }} index {{ type: {3_index_type} index_params {{ trees: 8 }} search_params {{ checks: 128 use_heap: false }} }} tree {{ type: {4_tree_type} attempt_connect: {5_attempt_connect} }} source {{ {source_q_string} }} destination {{ {destination_q_string} }} ''' src_q_string = { 'trivial': ''' q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 ''', 'easy': ''' q: 20 q: 20 q: 20 q: 20 q: 20 q: 20 q: 20 q: 20 ''', 'hard': ''' q: 0 q: 0 q: 0 q: 90 q: 0 q: 0 q: 90 q: 0 ''', } dst_q_string = { 'trivial': ''' q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 ''', 'easy': ''' q: -20 q: -20 q: -20 q: -20 q: -20 q: -20 q: -20 q: -20 ''', 'hard': ''' q: 0 q: 0 q: 0 q: -90 q: 0 q: 0 q: -90 q: 0 ''', } def parameter_provider(): for difficulty in ['trivial', 'easy', 'hard']: for generator_type in ['SIMPLE', 'HALTON']: #for index_type in ['LINEAR', 'KD_TREE', 'AUTOTUNED']: for index_type in ['KD_TREE']: for tree_type in ['BUBBLE', 'CLASSIC']: # for attempt_connect in ['true', 'false']: for attempt_connect in ['true']: for seed in range(0, 100): yield { '1_difficulty': difficulty, '2_generator_type': generator_type, '6_seed': str(400 * seed), '3_index_type': index_type, '4_tree_type': tree_type, '5_attempt_connect': attempt_connect, } counter = 0 for mapping in parameter_provider(): counter += 1 print 'At: {}'.format(counter) with open('generated_' + ('_'.join(zip(*sorted(mapping.items()))[1])) + '.task', 'w') as f: mapping['source_q_string'] = src_q_string[mapping['1_difficulty']] mapping['destination_q_string'] = dst_q_string[mapping['1_difficulty']] f.write(template.format(**mapping))
#!/usr/bin/python template = ''' environment {{ robot_filename: "../robot/setup.robot" environment_filename: "../environment/obstacles_{1_difficulty}.stl" max_underestimate: 20.0 }} generator {{ type: {2_generator_type} seed: {6_seed} keys: 2 keys: 3 keys: 5 keys: 7 keys: 11 keys: 13 }} index {{ type: {3_index_type} index_params {{ trees: 8 }} search_params {{ checks: 128 use_heap: false }} }} tree {{ type: {4_tree_type} attempt_connect: {5_attempt_connect} }} source {{ {source_q_string} }} destination {{ {destination_q_string} }} ''' src_q_string = { 'trivial': ''' q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 ''', 'easy': ''' q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 q: 10 ''', 'hard': ''' q: 0 q: 0 q: 0 q: 90 q: 0 q: 0 q: 90 q: 0 ''', } dst_q_string = { 'trivial': ''' q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 ''', 'easy': ''' q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 q: -10 ''', 'hard': ''' q: 0 q: 0 q: 0 q: -90 q: 0 q: 0 q: -90 q: 0 ''', } def parameter_provider(): for difficulty in ['trivial', 'easy', 'hard']: for generator_type in ['SIMPLE', 'HALTON']: #for index_type in ['LINEAR', 'KD_TREE', 'AUTOTUNED']: for index_type in ['KD_TREE']: for tree_type in ['BUBBLE', 'CLASSIC']: # for attempt_connect in ['true', 'false']: for attempt_connect in ['true']: for seed in range(0, 100): yield { '1_difficulty': difficulty, '2_generator_type': generator_type, '6_seed': str(400 * seed), '3_index_type': index_type, '4_tree_type': tree_type, '5_attempt_connect': attempt_connect, } counter = 0 for mapping in parameter_provider(): counter += 1 print 'At: {}'.format(counter) with open('generated_' + ('_'.join(zip(*sorted(mapping.items()))[1])) + '.task', 'w') as f: mapping['source_q_string'] = src_q_string[mapping['1_difficulty']] mapping['destination_q_string'] = dst_q_string[mapping['1_difficulty']] f.write(template.format(**mapping))
Python
0.000006
c62a658eb469e449372207f146f60375d7497f63
update dataset api
ismrmrdpy/dataset.py
ismrmrdpy/dataset.py
# Copyright (c) 2014-2015 Ghislain Antony Vaillant. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. from __future__ import absolute_import, division, print_function class Dataset(object): """ """ def __init__(self, *args, **kwargs): pass def open(self): pass def close(self): pass def read_header(self): pass def write_header(self, xmlstring): pass def append_acquisition(self, acq): pass def read_acquisition(self, index): pass def number_of_acquisitions(self): pass def append_image(self, img): pass def read_image(self, index): pass def number_of_images(self): pass def append_array(self, arr): pass def read_array(self, index): pass def number_of_arrays(self): pass
# Copyright (c) 2014-2015 Ghislain Antony Vaillant. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. from __future__ import absolute_import, division, print_function class Dataset(object): """ """ def __init__(self, *args, **kwargs): pass def open(self): pass def close(self): pass def read_header(self): pass def write_header(self, xmlstring): pass def append_acquisition(self, acq): pass def read_acquisition(self, index): pass def append_image(self, img): pass def read_image(self, index): pass def append_array(self, arr): pass def read_array(self, index): pass
Python
0.000001
3effb540220f4ce1918d0210e882d926e268473f
Bump P4Runtime to v1.2.0
tools/build/bazel/p4lang_workspace.bzl
tools/build/bazel/p4lang_workspace.bzl
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") P4RUNTIME_VER = "1.2.0" P4RUNTIME_SHA = "0fce7e06c63e60a8cddfe56f3db3d341953560c054d4c09ffda0e84476124f5a" def generate_p4lang(): http_archive( name = "com_github_p4lang_p4runtime", urls = ["https://github.com/p4lang/p4runtime/archive/v%s.zip" % P4RUNTIME_VER], sha256 = P4RUNTIME_SHA, strip_prefix = "p4runtime-%s/proto" % P4RUNTIME_VER, build_file = "//tools/build/bazel:p4runtime_BUILD", )
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") P4RUNTIME_VER = "1.0.0" P4RUNTIME_SHA = "667464bd369b40b58dc9552be2c84e190a160b6e77137b735bd86e5b81c6adc0" def generate_p4lang(): http_archive( name = "com_github_p4lang_p4runtime", urls = ["https://github.com/p4lang/p4runtime/archive/v%s.zip" % P4RUNTIME_VER], sha256 = P4RUNTIME_SHA, strip_prefix = "p4runtime-%s/proto" % P4RUNTIME_VER, build_file = "//tools/build/bazel:p4runtime_BUILD", )
Python
0.000001
64e902fae3117c246272cbde943d013da1345b7b
Fix RenameField alteration
gravity/migrations/0003_tiltbridge_mdns_id.py
gravity/migrations/0003_tiltbridge_mdns_id.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2019-03-18 23:46 from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('gravity', '0002_tilt_refactor'), ] operations = [ # Converting from AlterField to RemoveField/AddField because of issues with Django 2.0+ migration: # https://docs.djangoproject.com/en/3.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite migrations.RemoveField( model_name='tiltbridge', name='api_key', ), migrations.AddField( model_name='tiltbridge', name='mdns_id', field=models.CharField(help_text="mDNS ID used by the TiltBridge to identify itself both on your network and to Fermentrack. NOTE - Prefix only - do not include '.local'", max_length=64, primary_key=True, serialize=False, validators=[django.core.validators.RegexValidator(regex='^[a-zA-Z0-9]+$')]), ), migrations.AlterField( model_name='tiltbridge', name='mdns_id', field=models.CharField(default='tiltbridge', help_text="mDNS ID used by the TiltBridge to identify itself both on your network and to Fermentrack. NOTE - Prefix only - do not include '.local'", max_length=64, primary_key=True, serialize=False), preserve_default=False, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2019-03-18 23:46 from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('gravity', '0002_tilt_refactor'), ] operations = [ # Converting from AlterField to RemoveField/AddField because of issues with Django 2.0+ migration: # https://docs.djangoproject.com/en/3.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite migrations.RemoveField( model_name='tiltbridge', name='api_key', ), migrations.AddField( model_name='tiltbridge', name='mdns_id', field=models.CharField(help_text="mDNS ID used by the TiltBridge to identify itself both on your network and to Fermentrack. NOTE - Prefix only - do not include '.local'", max_length=64, primary_key=True, serialize=False, validators=[django.core.validators.RegexValidator(regex='^[a-zA-Z0-9]+$')]), ), migrations.RenameField( model_name='tiltbridge', old_name='api_key', new_name='mdns_id', ), migrations.AlterField( model_name='tiltbridge', name='mdns_id', field=models.CharField(default='tiltbridge', help_text="mDNS ID used by the TiltBridge to identify itself both on your network and to Fermentrack. NOTE - Prefix only - do not include '.local'", max_length=64, primary_key=True, serialize=False), preserve_default=False, ), ]
Python
0
fc4aada050fd995ecf5375871fa1e6ed1884293f
fix hail-apiserver.py module path (#4850)
hail/python/hail-apiserver/hail-apiserver.py
hail/python/hail-apiserver/hail-apiserver.py
import hail as hl from hail.utils.java import Env, info import logging import flask hl.init() app = flask.Flask('hail-apiserver') @app.route('/execute', methods=['POST']) def execute(): code = flask.request.json info(f'execute: {code}') jir = Env.hail().expr.ir.IRParser.parse_value_ir(code, {}, {}) typ = hl.HailType._from_java(jir.typ()) value = Env.hail().expr.ir.Interpret.interpretPyIR(code, {}, {}) result = { 'type': str(typ), 'value': value } info(f'result: {result}') return flask.jsonify(result) app.run(threaded=False, host='0.0.0.0')
import hail as hl from hail.utils.java import Env, info import logging import flask hl.init() app = flask.Flask('hail-apiserver') @app.route('/execute', methods=['POST']) def execute(): code = flask.request.json info(f'execute: {code}') jir = Env.hail().expr.Parser.parse_value_ir(code, {}, {}) typ = hl.HailType._from_java(jir.typ()) value = Env.hail().expr.ir.Interpret.interpretPyIR(code, {}, {}) result = { 'type': str(typ), 'value': value } info(f'result: {result}') return flask.jsonify(result) app.run(threaded=False, host='0.0.0.0')
Python
0
1d10582d622ce6867a85d9e4e8c279ab7e4ab5ab
Revert "Don't complain about \r when core.autocrlf is on in Git"
src/etc/tidy.py
src/etc/tidy.py
#!/usr/bin/python import sys, fileinput err=0 cols=78 def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if line.find('\r') != -1: report_err("CR character") if len(line)-1 > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
#!/usr/bin/python import sys, fileinput, subprocess err=0 cols=78 config_proc=subprocess.Popen([ "git", "config", "core.autocrlf" ], stdout=subprocess.PIPE) result=config_proc.communicate()[0] autocrlf=result.strip() == b"true" if result is not None else False def report_err(s): global err print("%s:%d: %s" % (fileinput.filename(), fileinput.filelineno(), s)) err=1 for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): if line.find('\t') != -1 and fileinput.filename().find("Makefile") == -1: report_err("tab character") if not autocrlf and line.find('\r') != -1: report_err("CR character") line_len = len(line)-2 if autocrlf else len(line)-1 if line_len > cols: report_err("line longer than %d chars" % cols) sys.exit(err)
Python
0
9dcf5e0b30141641a0e182257b34720bcf07d730
Fix typo in S3_Bucket_With_Versioning_And_Lifecycle_Rules.py (#693)
examples/S3_Bucket_With_Versioning_And_Lifecycle_Rules.py
examples/S3_Bucket_With_Versioning_And_Lifecycle_Rules.py
# Converted from S3_Bucket.template located at: # http://aws.amazon.com/cloudformation/aws-cloudformation-templates/ from troposphere import Output, Ref, Template from troposphere.s3 import Bucket, PublicRead, VersioningConfiguration, \ LifecycleConfiguration, LifecycleRule, NoncurrentVersionTransition, \ LifecycleRuleTransition t = Template() t.add_description( "AWS CloudFormation Sample Template S3_Bucket: Sample template showing :" "How to create a publicly accessible S3 bucket. " "How to enable bucket object versions. " "How to archive and delete current objects. " "How to archive and delete non current (versioned) objects. " "**WARNING** This template creates an Amazon S3 Bucket. " "You will be billed for the AWS resources used if you create " "a stack from this template.") s3bucket = t.add_resource(Bucket( "S3Bucket", # Make public Read AccessControl=PublicRead, # Turn on Versioning to the whole S3 Bucket VersioningConfiguration=VersioningConfiguration( Status="Enabled", ), # Attach a LifeCycle Configuration LifecycleConfiguration=LifecycleConfiguration(Rules=[ # Add a rule to LifecycleRule( # Rule attributes Id="S3BucketRule001", Prefix="/only-this-sub-dir", Status="Enabled", # Applies to current objects ExpirationInDays=3650, Transitions=[ LifecycleRuleTransition( StorageClass="STANDARD_IA", TransitionInDays=60, ), ], # Applies to Non Current objects NoncurrentVersionExpirationInDays=365, NoncurrentVersionTransitions=[ NoncurrentVersionTransition( StorageClass="STANDARD_IA", TransitionInDays=30, ), NoncurrentVersionTransition( StorageClass="GLACIER", TransitionInDays=120, ), ], ), ]), )) t.add_output(Output( "BucketName", Value=Ref(s3bucket), Description="Name of S3 bucket to hold website content" )) print(t.to_json())
# Converted from S3_Bucket.template located at: # http://aws.amazon.com/cloudformation/aws-cloudformation-templates/ from troposphere import Output, Ref, Template from troposphere.s3 import Bucket, PublicRead, VersioningConfiguration, \ LifecycleConfiguration, LifecycleRule, NoncurrentVersionTransition, \ LifecycleRuleTransition t = Template() t.add_description( "AWS CloudFormation Sample Template S3_Bucket: Sample template showing :" "How to create a publicly accessible S3 bucket. " "How to enable bucket object versions. " "How to archive and delete current objects. " "How to archive and delete non current (versioned) objects. " "**WARNING** This template creates an Amazon S3 Bucket. " "You will be billed for the AWS resources used if you create " "a stack from this template.") s3bucket = t.add_resource(Bucket( "S3Bucket", # Make public Read AccessControl=PublicRead, # Turn on Versioning to the whole S3 Bucket VersioningConfiguration=VersioningConfiguration( Status="Enabled", ), # Attach a LifeCycle Confiragtion LifecycleConfiguration=LifecycleConfiguration(Rules=[ # Add a rule to LifecycleRule( # Rule attributes Id="S3BucketRule001", Prefix="/only-this-sub-dir", Status="Enabled", # Applies to current objects ExpirationInDays=3650, Transitions=[ LifecycleRuleTransition( StorageClass="STANDARD_IA", TransitionInDays=60, ), ], # Applies to Non Current objects NoncurrentVersionExpirationInDays=365, NoncurrentVersionTransitions=[ NoncurrentVersionTransition( StorageClass="STANDARD_IA", TransitionInDays=30, ), NoncurrentVersionTransition( StorageClass="GLACIER", TransitionInDays=120, ), ], ), ]), )) t.add_output(Output( "BucketName", Value=Ref(s3bucket), Description="Name of S3 bucket to hold website content" )) print(t.to_json())
Python
0.998464
a378649f85f0bc55060ad0238e426f587bc2ff1a
Send location only when printing exception (Avoid leaking ID/UUID)
core/exceptions.py
core/exceptions.py
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider: %s" \ % (provider.location,) pass
""" exceptions - Core exceptions """ class InvalidMembership(Exception): """ The membership provided is not valid """ pass class SourceNotFound(Exception): """ InstanceSource doesn't have an associated source. """ pass class RequestLimitExceeded(Exception): """ A limit was exceeded for the specific request """ pass class ProviderLimitExceeded(Exception): """ A limit was exceeded for the specific provider """ pass class ProviderNotActive(Exception): """ The provider that was requested is not active """ def __init__(self, provider, *args, **kwargs): self.message = "Cannot create driver on an inactive provider:%s" \ % (provider,) pass
Python
0
93323426c22a08965544b19c818e53c8f2b29e8c
clean select_channel widget
ldk/gui/select_channel_widget.py
ldk/gui/select_channel_widget.py
# -*- coding: utf-8 -*- from pyqtgraph.Qt import QtGui, QtCore class SelectChannelWidget(QtGui.QWidget): def __init__(self, plot_widget): super(SelectChannelWidget, self).__init__() self.plot_widget = plot_widget self.layout = QtGui.QGridLayout() self.adc_checkbox = [] self.add_checkbox(self.adc_checkbox, 0, 'ADC') self.dac_checkbox = [] self.add_checkbox(self.dac_checkbox, 1, 'DAC') # Connections for i in range(2): self.adc_checkbox[i].stateChanged.connect(lambda: self.show_adc(i)) self.dac_checkbox[i].stateChanged.connect(lambda: self.show_dac(i)) def add_checkbox(self, checkbox, y_pos, text): for i in range(2): checkbox.append(QtGui.QCheckBox(text +' '+str(i+1), self)) checkbox[i].setCheckState(QtCore.Qt.Checked) self.layout.addWidget(checkbox[i], y_pos, i, QtCore.Qt.AlignCenter) def show_adc(self, index): self.plot_widget.show_adc[index] = self.adc_checkbox[index].isChecked() self.plot_widget.dataItem[index].setVisible(self.plot_widget.show_adc[index]) self.plot_widget.enableAutoRange() def show_dac(self, index): self.plot_widget.show_dac[index] = self.dac_checkbox[index].isChecked() self.plot_widget.dataItem[2+index].setVisible(self.plot_widget.show_dac[index]) self.plot_widget.enableAutoRange() def uncheck_all(self): for i in range(2): self.adc_checkbox[i].setCheckState(QtCore.Qt.Unchecked) self.dac_checkbox[i].setCheckState(QtCore.Qt.Unchecked)
# -*- coding: utf-8 -*- from pyqtgraph.Qt import QtGui, QtCore class SelectChannelWidget(QtGui.QWidget): def __init__(self, plot_widget): super(SelectChannelWidget, self).__init__() self.plot_widget = plot_widget self.layout = QtGui.QGridLayout() self.adc_checkbox = [] for i in range(2): self.adc_checkbox.append(QtGui.QCheckBox('ADC '+str(i+1), self)) self.adc_checkbox[i].setCheckState(QtCore.Qt.Checked) self.layout.addWidget(self.adc_checkbox[i],0,i,QtCore.Qt.AlignCenter) self.dac_checkbox = [] for i in range(2): self.dac_checkbox.append(QtGui.QCheckBox('DAC '+str(i+1), self)) self.dac_checkbox[i].setCheckState(QtCore.Qt.Unchecked) self.layout.addWidget(self.dac_checkbox[i],1,i,QtCore.Qt.AlignCenter) # Connections self.adc_checkbox[0].stateChanged.connect(lambda: self.show_adc(0)) self.adc_checkbox[1].stateChanged.connect(lambda: self.show_adc(1)) self.dac_checkbox[0].stateChanged.connect(lambda: self.show_dac(0)) self.dac_checkbox[1].stateChanged.connect(lambda: self.show_dac(1)) def show_adc(self, index): if self.adc_checkbox[index].isChecked(): self.plot_widget.show_adc[index] = True else: self.plot_widget.show_adc[index] = False self.plot_widget.dataItem[index].setVisible(self.plot_widget.show_adc[index]) self.plot_widget.enableAutoRange() def show_dac(self, index): if self.dac_checkbox[index].isChecked(): self.plot_widget.show_dac[index] = True else: self.plot_widget.show_dac[index] = False self.plot_widget.dataItem[2+index].setVisible(self.plot_widget.show_dac[index]) self.plot_widget.enableAutoRange() def uncheck_all(self): for i in range(2): self.adc_checkbox[i].setCheckState(QtCore.Qt.Unchecked) self.dac_checkbox[i].setCheckState(QtCore.Qt.Unchecked)
Python
0