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
87656428f02134c36c052fe60cfaa25536291cfe
Fix syntax error
upcloud_api/cloud_manager/storage_mixin.py
upcloud_api/cloud_manager/storage_mixin.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from upcloud_api import Storage class StorageManager(object): """ Functions for managing Storage disks. Intended to be used as a mixin for CloudManager. """ def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite """ res = self.get_request('/storage/' + storage_type) return Storage._create_storage_objs(res['storages'], cloud_manager=self) def get_storage(self, storage): """ Return a Storage object from the API. """ res = self.get_request('/storage/' + str(storage)) return Storage(cloud_manager=self, **res['storage']) def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, 'title': title, 'zone': zone, 'backup_rule': backup_rule } } res = self.post_request('/storage', body) return Storage(cloud_manager=self, **res['storage']) def _modify_storage(self, storage, size, title, backup_rule={}): body = {'storage': {}} if size: body['storage']['size'] = size if title: body['storage']['title'] = title if backup_rule: body['storage']['backup_rule'] = backup_rule return self.request('PUT', '/storage/' + str(storage), body) def modify_storage(self, storage, size, title, backup_rule={}): """ Modify a Storage object. Returns an object based on the API's response. """ res = self._modify_storage(str(storage), size, title, backup_rule) return Storage(cloud_manager=self, **res['storage']) def delete_storage(self, UUID): """ Destroy a Storage object. """ return self.request('DELETE', '/storage/' + UUID) def attach_storage(self, server, storage, storage_type, address): """ Attach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {}} if storage: body['storage_device']['storage'] = str(storage) if storage_type: body['storage_device']['type'] = storage_type if address: body['storage_device']['address'] = address url = '/server/{0}/storage/attach'.format(server) res = self.post_request(url, body) return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self) def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self)
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from upcloud_api import Storage class StorageManager(object): """ Functions for managing Storage disks. Intended to be used as a mixin for CloudManager. """ def get_storages(self, storage_type='normal'): """ Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite """ res = self.get_request('/storage/' + storage_type) return Storage._create_storage_objs(res['storages'], cloud_manager=self) def get_storage(self, storage): """ Return a Storage object from the API. """ res = self.get_request('/storage/' + str(storage)) return Storage(cloud_manager=self, **res['storage']) def create_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}): """ Create a Storage object. Returns an object based on the API's response. """ body = { 'storage': { 'size': size, 'tier': tier, 'title': title, 'zone': zone 'backup_rule': backup_rule } } res = self.post_request('/storage', body) return Storage(cloud_manager=self, **res['storage']) def _modify_storage(self, storage, size, title, backup_rule={}): body = {'storage': {}} if size: body['storage']['size'] = size if title: body['storage']['title'] = title if backup_rule: body['storage']['backup_rule'] = backup_rule return self.request('PUT', '/storage/' + str(storage), body) def modify_storage(self, storage, size, title, backup_rule={}): """ Modify a Storage object. Returns an object based on the API's response. """ res = self._modify_storage(str(storage), size, title, backup_rule) return Storage(cloud_manager=self, **res['storage']) def delete_storage(self, UUID): """ Destroy a Storage object. """ return self.request('DELETE', '/storage/' + UUID) def attach_storage(self, server, storage, storage_type, address): """ Attach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {}} if storage: body['storage_device']['storage'] = str(storage) if storage_type: body['storage_device']['type'] = storage_type if address: body['storage_device']['address'] = address url = '/server/{0}/storage/attach'.format(server) res = self.post_request(url, body) return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self) def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self)
Python
0.000004
9a6c74bdb8c7b386f75100ab2fafabae3a5a9997
Add utility functions to stix.Entity
stix/__init__.py
stix/__init__.py
# Copyright (c) 2014, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. __version__ = "1.0.1.0" import json from StringIO import StringIO class Entity(object): """Base class for all classes in the STIX API.""" def to_obj(self, return_obj=None): """Export an object as a binding object representation""" pass def from_obj(self, obj): """Create an object from a binding object""" pass def _get_namespaces(self, ns_dict): import stix.utils.nsparser as nsparser import cybox.utils.nsparser as cybox_nsparser import stix.utils.idgen as idgen if not ns_dict: ns_dict = {} xml_ns_dict = {'http://www.w3.org/2001/XMLSchema-instance': 'xsi', 'http://stix.mitre.org/stix-1': 'stix', 'http://stix.mitre.org/common-1': 'stixCommon', 'http://stix.mitre.org/default_vocabularies-1': 'stixVocabs', idgen.get_id_namespace() : idgen.get_id_namespace_alias()} namespace_parser = nsparser.NamespaceParser() all_ns_dict = dict(xml_ns_dict) ns_set = namespace_parser.get_namespaces(self) for ns in ns_set: if ns in ns_dict: all_ns_dict[ns] = ns_dict[ns] elif ns.startswith("http://cybox.mitre.org"): for cybox_ns_tup in cybox_nsparser.NS_LIST: if ns == cybox_ns_tup[0]: all_ns_dict[ns] = cybox_ns_tup[1] elif ns in nsparser.DEFAULT_EXT_TO_PREFIX: all_ns_dict[ns] = nsparser.DEFAULT_EXT_TO_PREFIX[ns] else: all_ns_dict[ns] = nsparser.DEFAULT_STIX_NS_TO_PREFIX[ns] return all_ns_dict def _get_schema_locations(self): import stix.utils.nsparser as nsparser schemaloc_dict = nsparser.NamespaceParser().get_namespace_schemalocation_dict(self) return schemaloc_dict def to_xml(self, include_namespaces=True, ns_dict=None, pretty=True): """Export an object as an XML String""" s = StringIO() namespace_def = "" if include_namespaces: if not ns_dict: ns_dict = {} all_ns_dict = self._get_namespaces(ns_dict) schemaloc_dict = self._get_schema_locations() import stix.utils.nsparser as nsparser namespace_def = nsparser.NamespaceParser().get_namespace_def_str(all_ns_dict, schemaloc_dict) if not pretty: namespace_def = namespace_def.replace('\n\t', ' ') self.to_obj().export(s, 0, all_ns_dict, pretty_print=pretty, namespacedef_=namespace_def) return s.getvalue() def to_json(self): return json.dumps(self.to_dict()) @staticmethod def from_dict(dict_repr, return_obj=None): """Convert from dict representation to object representation.""" return return_obj @classmethod def object_from_dict(cls, entity_dict): """Convert from dict representation to object representation.""" return cls.from_dict(entity_dict).to_obj() @classmethod def dict_from_object(cls, entity_obj): """Convert from object representation to dict representation.""" return cls.from_obj(entity_obj).to_dict()
# Copyright (c) 2014, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. __version__ = "1.0.1.0" import json from StringIO import StringIO class Entity(object): """Base class for all classes in the STIX API.""" def to_obj(self, return_obj=None): """Export an object as a binding object representation""" pass def from_obj(self, obj): """Create an object from a binding object""" pass def _get_namespaces(self, ns_dict): import stix.utils.nsparser as nsparser import cybox.utils.nsparser as cybox_nsparser import stix.utils.idgen as idgen if not ns_dict: ns_dict = {} xml_ns_dict = {'http://www.w3.org/2001/XMLSchema-instance': 'xsi', 'http://stix.mitre.org/stix-1': 'stix', 'http://stix.mitre.org/common-1': 'stixCommon', 'http://stix.mitre.org/default_vocabularies-1': 'stixVocabs', idgen.get_id_namespace() : idgen.get_id_namespace_alias()} namespace_parser = nsparser.NamespaceParser() all_ns_dict = dict(xml_ns_dict) ns_set = namespace_parser.get_namespaces(self) for ns in ns_set: if ns in ns_dict: all_ns_dict[ns] = ns_dict[ns] elif ns.startswith("http://cybox.mitre.org"): for cybox_ns_tup in cybox_nsparser.NS_LIST: if ns == cybox_ns_tup[0]: all_ns_dict[ns] = cybox_ns_tup[1] elif ns in nsparser.DEFAULT_EXT_TO_PREFIX: all_ns_dict[ns] = nsparser.DEFAULT_EXT_TO_PREFIX[ns] else: all_ns_dict[ns] = nsparser.DEFAULT_STIX_NS_TO_PREFIX[ns] return all_ns_dict def _get_schema_locations(self): import stix.utils.nsparser as nsparser schemaloc_dict = nsparser.NamespaceParser().get_namespace_schemalocation_dict(self) return schemaloc_dict def to_xml(self, include_namespaces=True, ns_dict=None, pretty=True): """Export an object as an XML String""" s = StringIO() namespace_def = "" if include_namespaces: if not ns_dict: ns_dict = {} all_ns_dict = self._get_namespaces(ns_dict) schemaloc_dict = self._get_schema_locations() import stix.utils.nsparser as nsparser namespace_def = nsparser.NamespaceParser().get_namespace_def_str(all_ns_dict, schemaloc_dict) if not pretty: namespace_def = namespace_def.replace('\n\t', ' ') self.to_obj().export(s, 0, all_ns_dict, pretty_print=pretty, namespacedef_=namespace_def) return s.getvalue() def to_json(self): return json.dumps(self.to_dict()) @staticmethod def from_dict(dict_repr, return_obj=None): """Convert from dict representation to object representation.""" return return_obj
Python
0.000002
0efe8e9cfbd3a5d3319553aabf4f0dd17fa53d33
fix license test
awx/main/tests/functional/api/test_settings.py
awx/main/tests/functional/api/test_settings.py
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. # Python import pytest import os # Django from django.core.urlresolvers import reverse # AWX from awx.conf.models import Setting ''' Ensures that tests don't pick up dev container license file ''' @pytest.fixture def mock_no_license_file(mocker): os.environ['AWX_LICENSE_FILE'] = '/does_not_exist' return None @pytest.mark.django_db def test_license_cannot_be_removed_via_system_settings(mock_no_license_file, get, put, patch, delete, admin, enterprise_license): url = reverse('api:setting_singleton_detail', args=('system',)) response = get(url, user=admin, expect=200) assert not response.data['LICENSE'] Setting.objects.create(key='LICENSE', value=enterprise_license) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] put(url, user=admin, data=response.data, expect=200) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] patch(url, user=admin, data={}, expect=200) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] delete(url, user=admin, expect=204) response = get(url, user=admin, expect=200) assert response.data['LICENSE']
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. # Python import pytest # Django from django.core.urlresolvers import reverse # AWX from awx.conf.models import Setting @pytest.mark.django_db def test_license_cannot_be_removed_via_system_settings(get, put, patch, delete, admin, enterprise_license): url = reverse('api:setting_singleton_detail', args=('system',)) response = get(url, user=admin, expect=200) assert not response.data['LICENSE'] Setting.objects.create(key='LICENSE', value=enterprise_license) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] put(url, user=admin, data=response.data, expect=200) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] patch(url, user=admin, data={}, expect=200) response = get(url, user=admin, expect=200) assert response.data['LICENSE'] delete(url, user=admin, expect=204) response = get(url, user=admin, expect=200) assert response.data['LICENSE']
Python
0
c91e7dcc969485644d8e26c459c894925b3f0720
add in fasta format
scripts/dump_biodatabase.py
scripts/dump_biodatabase.py
#!/usr/bin/env python import sys from getpass import getpass from BioSQL import BioSeqDatabase from common import standard_options, generate_placeholders, chunks, extract_feature_sql def get_seqfeature_for_db(server, biodb): ''' find all seqfeatures that have the given value for the qualifier returns a list of seqfeature_id ''' sql = "SELECT qv.seqfeature_id FROM seqfeature_qualifier_value qv join seqfeature s using(seqfeature_id) join bioentry b using(bioentry_id) join biodatabase bd using(biodatabase_id) WHERE bd.name = %s" return server.adaptor.execute_and_fetchall(sql, (biodb,)) def main(args): server = BioSeqDatabase.open_database(driver=args.driver, db=args.database, user=args.user, host=args.host, passwd=args.password) if args.output_format == 'fasta': from Bio import SeqIO db = server[args.database_name] for rec in db.values(): SeqIO.write(rec, sys.stdout, args.output_format) else: seqfeature_ids = get_seqfeature_for_db(server, args.database_name) if args.output_format == 'feat-prot': extract_feature_sql(server, seqfeature_ids, type=['CDS'], translate=True ) elif args.output_format == 'feat-nucl': extract_feature_sql(server, seqfeature_ids ) if __name__ == "__main__": parser = standard_options() parser.add_argument('-D', '--database-name', help='namespace of the database that you want to add into', dest='database_name', required=True) parser.add_argument('-o', '--output_format', help='output format of the selected sequences', choices=['feat-prot', 'feat-nucl', 'fasta'], default='feat-prot') args = parser.parse_args() if args.password is None: args.password = getpass("Please enter the password for user " + \ args.user + " on database " + args.database) main(args)
#!/usr/bin/env python from getpass import getpass from BioSQL import BioSeqDatabase from common import standard_options, generate_placeholders, chunks, extract_feature_sql def get_seqfeature_for_db(server, biodb): ''' find all seqfeatures that have the given value for the qualifier returns a list of seqfeature_id ''' sql = "SELECT qv.seqfeature_id FROM seqfeature_qualifier_value qv join seqfeature s using(seqfeature_id) join bioentry b using(bioentry_id) join biodatabase bd using(biodatabase_id) WHERE bd.name = %s" return server.adaptor.execute_and_fetchall(sql, (biodb,)) def main(args): server = BioSeqDatabase.open_database(driver=args.driver, db=args.database, user=args.user, host=args.host, passwd=args.password) seqfeature_ids = get_seqfeature_for_db(server, args.database_name) if args.output_format == 'feat-prot': extract_feature_sql(server, seqfeature_ids, type=['CDS'], translate=True ) elif args.output_format == 'feat-nucl': extract_feature_sql(server, seqfeature_ids ) if __name__ == "__main__": parser = standard_options() parser.add_argument('-D', '--database-name', help='namespace of the database that you want to add into', dest='database_name', required=True) parser.add_argument('-o', '--output_format', help='output format of the selected sequences', choices=['feat-prot', 'feat-nucl'], default='feat-prot') args = parser.parse_args() if args.password is None: args.password = getpass("Please enter the password for user " + \ args.user + " on database " + args.database) main(args)
Python
0.999986
4a9e34a57476c92a4147f9ecafc357a681f1a19a
Add wrapper for testing fixing functionality
scripts/flaskext_migrate.py
scripts/flaskext_migrate.py
# Script which modifies source code away from the deprecated "flask.ext" # format. Does not yet fully support imports in the style: # # "import flask.ext.foo" # # these are converted to "import flask_foo" in the # main import statement, but does not handle function calls in the source. # # Run in the terminal by typing: `python flaskext_migrate.py <source_file.py>` # # Author: Keyan Pishdadian 2015 from redbaron import RedBaron import sys def read_source(input_file): """Parses the input_file into a RedBaron FST.""" with open(input_file, "r") as source_code: red = RedBaron(source_code.read()) return red def write_source(red, input_file): """Overwrites the input_file once the FST has been modified.""" with open(input_file, "w") as source_code: source_code.write(red.dumps()) def fix_imports(red): """Wrapper which fixes "from" style imports and then "import" style.""" red = fix_standard_imports(red) red = fix_from_imports(red) return red def fix_from_imports(red): """ Converts "from" style imports to not use "flask.ext". Handles: Case 1: from flask.ext.foo import bam --> from flask_foo import bam Case 2: from flask.ext import foo --> import flask_foo as foo """ from_imports = red.find_all("FromImport") for x in range(len(from_imports)): values = from_imports[x].value if (values[0].value == 'flask') and (values[1].value == 'ext'): # Case 1 if len(from_imports[x].value) == 3: package = values[2].value modules = from_imports[x].modules() r = "{}," * len(modules) from_imports[x].replace("from flask_%s import %s" % (package, r.format(*modules)[:-1])) # Case 2 else: module = from_imports[x].modules()[0] from_imports[x].replace("import flask_%s as %s" % (module, module)) return red def fix_standard_imports(red): """ Handles import modification in the form: import flask.ext.foo" --> import flask_foo Does not modify function calls elsewhere in the source outside of the original import statement. """ imports = red.find_all("ImportNode") for x in range(len(imports)): values = imports[x].value try: if (values[x].value[0].value == 'flask' and values[x].value[1].value == 'ext'): package = values[x].value[2].value imports[x].replace("import flask_%s" % package) except IndexError: pass return red def fix(input_file): ast = read_source(input_file) new_ast = fix_imports(ast) write_source(new_ast, input_file) if __name__ == "__main__": input_file = sys.argv[1] fix(input_file)
# Script which modifies source code away from the deprecated "flask.ext" # format. Does not yet fully support imports in the style: # # "import flask.ext.foo" # # these are converted to "import flask_foo" in the # main import statement, but does not handle function calls in the source. # # Run in the terminal by typing: `python flaskext_migrate.py <source_file.py>` # # Author: Keyan Pishdadian 2015 from redbaron import RedBaron import sys def read_source(input_file): """Parses the input_file into a RedBaron FST.""" with open(input_file, "r") as source_code: red = RedBaron(source_code.read()) return red def write_source(red, input_file): """Overwrites the input_file once the FST has been modified.""" with open(input_file, "w") as source_code: source_code.write(red.dumps()) def fix_imports(red): """Wrapper which fixes "from" style imports and then "import" style.""" red = fix_standard_imports(red) red = fix_from_imports(red) return red def fix_from_imports(red): """ Converts "from" style imports to not use "flask.ext". Handles: Case 1: from flask.ext.foo import bam --> from flask_foo import bam Case 2: from flask.ext import foo --> import flask_foo as foo """ from_imports = red.find_all("FromImport") for x in range(len(from_imports)): values = from_imports[x].value if (values[0].value == 'flask') and (values[1].value == 'ext'): # Case 1 if len(from_imports[x].value) == 3: package = values[2].value modules = from_imports[x].modules() r = "{}," * len(modules) from_imports[x].replace("from flask_%s import %s" % (package, r.format(*modules)[:-1])) # Case 2 else: module = from_imports[x].modules()[0] from_imports[x].replace("import flask_%s as %s" % (module, module)) return red def fix_standard_imports(red): """ Handles import modification in the form: import flask.ext.foo" --> import flask_foo Does not modify function calls elsewhere in the source outside of the original import statement. """ imports = red.find_all("ImportNode") for x in range(len(imports)): values = imports[x].value try: if (values[x].value[0].value == 'flask' and values[x].value[1].value == 'ext'): package = values[x].value[2].value imports[x].replace("import flask_%s" % package) except IndexError: pass return red if __name__ == "__main__": input_file = sys.argv[1] ast = read_source(input_file) new_ast = fix_imports(ast) write_source(new_ast, input_file)
Python
0
95d8f915e4aee6fbab4ca741197a3563eb3a5ff2
bump version to 0.4
aldryn_bootstrap3/__init__.py
aldryn_bootstrap3/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import __version__ = '0.4'
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import __version__ = '0.3'
Python
0
de0fd677d94b7fb8b044fa597b687dba0f3e1c0e
Test coercions for generic type constructors
blaze/datashape/tests/test_type_constructor.py
blaze/datashape/tests/test_type_constructor.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import unittest from blaze import error from blaze.datashape import unify_simple, promote, coerce, dshapes, coretypes as T #------------------------------------------------------------------------ # Test data #------------------------------------------------------------------------ Complex = T.TypeConstructor('Complex', 1, [{'coercible': True}]) t1 = Complex(T.int64) t2 = Complex(T.int64) t3 = Complex(T.int32) RigidComplex = T.TypeConstructor('Complex', 1, [{'coercible': False}]) rt1 = RigidComplex(T.int64) rt2 = RigidComplex(T.int64) rt3 = RigidComplex(T.int32) #------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------ class TestTypeConstructors(unittest.TestCase): def test_equality(self): self.assertEqual(t1, t2) self.assertNotEqual(t1, t3) def test_unification_concrete(self): self.assertEqual(unify_simple(t1, t2), t1) def test_unification_typevar(self): tvar = Complex(T.TypeVar('A')) self.assertEqual(unify_simple(t1, tvar), t1) def test_promotion(self): self.assertEqual(promote(t1, t2), t1) self.assertEqual(promote(t1, t3), t1) self.assertEqual(promote(t3, t2), t1) self.assertEqual(promote(rt1, rt2), rt1) def test_coercion(self): self.assertEqual(coerce(t1, t2), 0) self.assertGreater(coerce(t3, t2), 0) self.assertEqual(coerce(rt1, rt2), 0) class TestErrors(unittest.TestCase): def test_promotion_error(self): self.assertRaises(error.UnificationError, promote, rt1, rt3) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import unittest from blaze import error from blaze.datashape import unify_simple, promote, coerce, dshapes, coretypes as T #------------------------------------------------------------------------ # Test data #------------------------------------------------------------------------ Complex = T.TypeConstructor('Complex', 1, [{'coercible': True}]) t1 = Complex(T.int64) t2 = Complex(T.int64) t3 = Complex(T.int32) RigidComplex = T.TypeConstructor('Complex', 1, [{'coercible': False}]) rt1 = RigidComplex(T.int64) rt2 = RigidComplex(T.int64) rt3 = RigidComplex(T.int32) #------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------ class TestTypeConstructors(unittest.TestCase): def test_equality(self): self.assertEqual(t1, t2) self.assertNotEqual(t1, t3) def test_unification_concrete(self): self.assertEqual(unify_simple(t1, t2), t1) def test_unification_typevar(self): tvar = Complex(T.TypeVar('A')) self.assertEqual(unify_simple(t1, tvar), t1) def test_promotion(self): self.assertEqual(promote(t1, t2), t1) self.assertEqual(promote(t1, t3), t1) self.assertEqual(promote(t3, t2), t1) self.assertEqual(promote(rt1, rt2), rt1) class TestErrors(unittest.TestCase): def test_promotion_error(self): self.assertRaises(error.UnificationError, promote, rt1, rt3) if __name__ == '__main__': # TestTypeConstructors('test_unification').debug() unittest.main()
Python
0
7da15f2e16c95a4be179a1cc1efd108dbaaa3be9
Update forward_ZMQ_Angle.py
ProBot_BeagleBone/forward_ZMQ_Angle.py
ProBot_BeagleBone/forward_ZMQ_Angle.py
#!/usr/bin/python import zmq def main(): try: context = zmq.Context(1) # Socket facing clients frontend = context.socket(zmq.SUB) frontend.bind("tcp://*:5583") frontend.setsockopt(zmq.SUBSCRIBE, "") # Socket facing services backend = context.socket(zmq.PUB) backend.bind("tcp://*:5584") zmq.device(zmq.FORWARDER, frontend, backend) except Exception, e: print e print "bringing down zmq device" finally: pass frontend.close() backend.close() context.term() if __name__ == "__main__": main()
import zmq def main(): try: context = zmq.Context(1) # Socket facing clients frontend = context.socket(zmq.SUB) frontend.bind("tcp://*:5583") frontend.setsockopt(zmq.SUBSCRIBE, "") # Socket facing services backend = context.socket(zmq.PUB) backend.bind("tcp://*:5584") zmq.device(zmq.FORWARDER, frontend, backend) except Exception, e: print e print "bringing down zmq device" finally: pass frontend.close() backend.close() context.term() if __name__ == "__main__": main()
Python
0.000001
c01f7fb0c9bda24efbd1d1597350a77d03047027
Add Grid and Align support
wytch/builder.py
wytch/builder.py
# The MIT License (MIT) # # Copyright (c) 2015 Josef Gajdusek # # 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. from wytch import view, colors class Builder: def __init__(self, view, parent = None): self.view = view self.parent = parent self.nested = [] def add(self, c): self.nested.append(Builder(c, parent = self)) return self def labels(self, strs, fg = colors.WHITE, bg = colors.BLACK): for s in strs: self.add(view.Label(s, fg = fg, bg = bg)) return self def spacer(self, width = 0, height = 0): return self.add(view.Spacer(width = width, height = height)) def hline(self, title = None): return self.add(view.HLine(title = title)) def nest(self, cont): #self.view.add_child(cont) ret = Builder(cont, parent = self) self.nested.append(ret) return ret def align(self, halign = view.HOR_MID, valign = view.VER_MID): return self.nest(view.Align(halign = halign, valign = valign)) def grid(self, width, height): ret = GridBuilder(view.Grid(width, height), parent = self) self.nested.append(ret) return ret def vertical(self, width = 0): return self.nest(view.Vertical(width = width)) def horizontal(self, height = 0): return self.nest(view.Horizontal(height = height)) def box(self, title = None): return self.nest(view.Box(title = title)) def endall(self): self.end() if self.parent: self.parent.endall() def end(self): return self.parent def __enter__(self): return self def __exit__(self, extype, exval, trace): for b in self.nested: b.__exit__(extype, exval, trace) if self.parent: self.parent.view.add_child(self.view) return self.parent class GridBuilder(Builder): def __init__(self, view, parent = None): super(GridBuilder, self).__init__(view, parent = parent) self.atx = 0 self.aty = 0 def add(self, c = None, rowspan = 1, colspan = 1): if c: self.view.set(self.atx, self.aty, c, rowspan = rowspan, colspan = colspan) self.atx += 1 if self.atx >= self.view.width: self.atx = 0 self.aty += 1 return self
# The MIT License (MIT) # # Copyright (c) 2015 Josef Gajdusek # # 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. from wytch import view, colors class Builder: def __init__(self, view, parent = None): self.view = view self.parent = parent self.nested = [] def add(self, c): self.nested.append(Builder(c, parent = self)) return self def labels(self, strs, fg = colors.WHITE, bg = colors.BLACK): for s in strs: self.add(view.Label(s, fg = fg, bg = bg)) return self def spacer(self, width = 0, height = 0): return self.add(view.Spacer(width = width, height = height)) def hline(self, title = None): return self.add(view.HLine(title = title)) def nest(self, cont): #self.view.add_child(cont) ret = Builder(cont, parent = self) self.nested.append(ret) return ret def vertical(self, width = 0): return self.nest(view.Vertical(width = width)) def horizontal(self, height = 0): return self.nest(view.Horizontal(height = height)) def box(self, title = None): return self.nest(view.Box(title = title)) def endall(self): self.end() if self.parent: self.parent.endall() def end(self): return self.parent def __enter__(self): return self def __exit__(self, extype, exval, trace): for b in self.nested: b.__exit__(extype, exval, trace) if self.parent: self.parent.view.add_child(self.view) return self.parent
Python
0
a7ac41830ac0472442069deead739ddd4c137be3
add future import for print
examples/receive_notify.py
examples/receive_notify.py
#!/usr/bin/env python3 # This is just a toy, real code would check that the received message # really was a NOTIFY, and otherwise handle errors. from __future__ import print_function import socket import dns.flags import dns.message import dns.rdataclass import dns.rdatatype address = '127.0.0.1' port = 53535 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((address, port)) while True: (wire, address) = s.recvfrom(512) notify = dns.message.from_wire(wire) soa = notify.find_rrset(notify.answer, notify.question[0].name, dns.rdataclass.IN, dns.rdatatype.SOA) # Do something with the SOA RR here print('The serial number for', soa.name, 'is', soa[0].serial) response = dns.message.make_response(notify) response.flags |= dns.flags.AA wire = response.to_wire(response) s.sendto(wire, address)
#!/usr/bin/env python3 # This is just a toy, real code would check that the received message # really was a NOTIFY, and otherwise handle errors. import socket import dns.flags import dns.message import dns.rdataclass import dns.rdatatype address = '127.0.0.1' port = 53535 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((address, port)) while True: (wire, address) = s.recvfrom(512) notify = dns.message.from_wire(wire) soa = notify.find_rrset(notify.answer, notify.question[0].name, dns.rdataclass.IN, dns.rdatatype.SOA) # Do something with the SOA RR here print('The serial number for', soa.name, 'is', soa[0].serial) response = dns.message.make_response(notify) response.flags |= dns.flags.AA wire = response.to_wire(response) s.sendto(wire, address)
Python
0
a68c026e9eb7d801a2f86fb52a02a1f67fd22f7d
Update visualise.py
visualise.py
visualise.py
# visualise.py # Imports import argparse import json import numpy as np import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from uniform_bspline import Contour # generate_figure def generate_figure(z, num_samples, verbose=True): degree, num_control_points, dim, is_closed = ( z['degree'], z['num_control_points'], z['dim'], z['is_closed']) if verbose: print ' degree:', degree print ' num_control_points:', num_control_points print ' dim:', dim print ' is_closed:', is_closed c = Contour(degree, num_control_points, dim, is_closed=is_closed) Y, w, u, X = map(lambda k: np.array(z[k]), 'YwuX') if verbose: print ' num_data_points:', Y.shape[0] kw = {} if Y.shape[1] == 3: kw['projection'] = '3d' f = plt.figure() ax = f.add_subplot(111, **kw) ax.set_aspect('equal') def plot(X, *args, **kwargs): ax.plot(*(tuple(X.T) + args), **kwargs) plot(Y, 'ro') for m, y in zip(c.M(u, X), Y): plot(np.r_['0,2', m, y], 'k-') plot(X, 'bo--', ms=8.0) plot(c.M(c.uniform_parameterisation(num_samples), X), 'b-', lw=2.0) e = z.get('e') if e is not None: ax.set_title('Energy: {:.7e}'.format(e)) return f # main def main(): parser = argparse.ArgumentParser() parser.add_argument('input_path') parser.add_argument('output_path', nargs='?') parser.add_argument('--num-samples', type=int, default=1024) parser.add_argument('--width', type=float, default=6.0) parser.add_argument('--height', type=float, default=4.0) parser.add_argument('--dpi', type=int, default=100) args = parser.parse_args() if os.path.isfile(args.input_path): print 'Input:', args.input_path with open(args.input_path, 'rb') as fp: z = json.load(fp) f = generate_figure(z, args.num_samples) if args.output_path is None: plt.show() else: print 'Output:', args.output_path f.set_size_inches((args.width, args.height)) f.savefig(args.output_path, dpi=args.dpi, bbox_inches=0.0, pad_inches='tight') else: if args.output_path is None: raise ValueError('`output_path` required') if not os.path.exists(args.output_path): os.makedirs(args.output_path) input_files = sorted(os.listdir(args.input_path), key=lambda f: int(os.path.splitext(f)[0])) input_paths = map(lambda f: os.path.join(args.input_path, f), input_files) print 'Input:' states = [] for input_path in input_paths: print ' ', input_path with open(input_path, 'rb') as fp: states.append(json.load(fp)) bounds = sum(map(lambda k: map(lambda z: (np.min(z[k], axis=0), np.max(z[k], axis=0)), states), 'XY'), []) min_, max_ = zip(*bounds) min_, max_ = np.min(min_, axis=0), np.max(max_, axis=0) d = 0.01 * (max_ - min_) xlim, ylim = np.c_[min_ - d, max_ + d] print 'Output:' for input_file, z in zip(input_files, states): f = generate_figure(z, args.num_samples, verbose=False) (ax,) = f.axes ax.set_xlim(*xlim) ax.set_ylim(*ylim) input_stem, _ = os.path.splitext(input_file) output_path = os.path.join(args.output_path, '{}.png'.format(input_stem)) print ' ', output_path f.set_size_inches((args.width, args.height)) f.savefig(output_path, dpi=args.dpi, bbox_inches=0.0, pad_inches='tight') plt.close(f) if __name__ == '__main__': main()
# visualise.py # Imports import argparse import json import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from uniform_bspline import Contour # main def main(): parser = argparse.ArgumentParser() parser.add_argument('input_path') parser.add_argument('--num-samples', type=int, default=1024) args = parser.parse_args() print 'Input:', args.input_path with open(args.input_path, 'rb') as fp: z = json.load(fp) degree, num_control_points, dim, is_closed = ( z['degree'], z['num_control_points'], z['dim'], z['is_closed']) print ' degree:', degree print ' num_control_points:', num_control_points print ' dim:', dim print ' is_closed:', is_closed c = Contour(degree, num_control_points, dim, is_closed=is_closed) Y, w, u, X = map(np.array, [z['Y'], z['w'], z['u'], z['X']]) print ' num_data_points:', Y.shape[0] kw = {} if Y.shape[1] == 3: kw['projection'] = '3d' f = plt.figure() ax = f.add_subplot(111, **kw) ax.set_aspect('equal') def plot(X, *args, **kwargs): ax.plot(*(tuple(X.T) + args), **kwargs) plot(Y, 'ro') for m, y in zip(c.M(u, X), Y): plot(np.r_['0,2', m, y], 'k-') plot(X, 'bo--', ms=8.0) plot(c.M(c.uniform_parameterisation(args.num_samples), X), 'b-', lw=2.0) plt.show() if __name__ == '__main__': main()
Python
0.000001
9bbe8057a627ba81282a76de94e57ca0b0e02b89
change default port
backend/src/gosa/backend/plugins/foreman/gosa_integration.py
backend/src/gosa/backend/plugins/foreman/gosa_integration.py
#!/usr/bin/env python3 """ Foreman / GOsa3 integration to send hook events data to GOsa3 """ import hmac import sys import requests import json #. /etc/sysconfig/foreman-gosa # Gosa settings GOSA_SERVER = "http://localhost" GOSA_PORT = 8050 HTTP_X_HUB_SENDER = "foreman-hook" SECRET = "e540f417-4c36-4e5d-b78a-4d36f51727ec" HOOK_TEMP_DIR = "/usr/share/foreman/tmp" # HOOK_EVENT = update, create, before_destroy etc. # HOOK_OBJECT = to_s representation of the object, e.g. host's fqdn HOOK_EVENT, HOOK_OBJECT = (sys.argv[1], sys.argv[2]) payload = json.loads(sys.stdin.read()) # add event + object to payload payload = json.dumps({ "event": HOOK_EVENT, "object": HOOK_OBJECT, "data": payload }).encode('utf-8') signature_hash = hmac.new(bytes(SECRET, 'ascii'), msg=payload, digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers = { 'Content-Type': 'application/vnd.foreman.hookevent+json', 'HTTP_X_HUB_SENDER': HTTP_X_HUB_SENDER, 'HTTP_X_HUB_SIGNATURE': signature } requests.post("%s:%s/hooks" % (GOSA_SERVER, GOSA_PORT), data=payload, headers=headers)
#!/usr/bin/env python3 """ Foreman / GOsa3 integration to send hook events data to GOsa3 """ import hmac import sys import requests import json #. /etc/sysconfig/foreman-gosa # Gosa settings GOSA_SERVER = "http://localhost" GOSA_PORT = 8000 HTTP_X_HUB_SENDER = "foreman-hook" SECRET = "e540f417-4c36-4e5d-b78a-4d36f51727ec" HOOK_TEMP_DIR = "/usr/share/foreman/tmp" # HOOK_EVENT = update, create, before_destroy etc. # HOOK_OBJECT = to_s representation of the object, e.g. host's fqdn HOOK_EVENT, HOOK_OBJECT = (sys.argv[1], sys.argv[2]) payload = json.loads(sys.stdin.read()) # add event + object to payload payload = json.dumps({ "event": HOOK_EVENT, "object": HOOK_OBJECT, "data": payload }).encode('utf-8') signature_hash = hmac.new(bytes(SECRET, 'ascii'), msg=payload, digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers = { 'Content-Type': 'application/vnd.foreman.hookevent+json', 'HTTP_X_HUB_SENDER': HTTP_X_HUB_SENDER, 'HTTP_X_HUB_SIGNATURE': signature } requests.post("%s:%s/hooks" % (GOSA_SERVER, GOSA_PORT), data=payload, headers=headers)
Python
0.000001
94b216fb8c15db7228e54e35058c7143b02d103f
prepare 1.1.1 bugfix release, from now on tests for new features..
cmsplugin_blog/__init__.py
cmsplugin_blog/__init__.py
# -*- coding: utf-8 -*- VERSION = (1, 1, 1, 'post', 0) def get_version(): # pragma: no cover version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) return version
# -*- coding: utf-8 -*- VERSION = (1, 1, 0, 'post', 0) def get_version(): # pragma: no cover version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) return version
Python
0
d03513e41ee1cc0edcd696c5ed08274db4f782bd
add editor for page icons
cmsplugin_cascade/admin.py
cmsplugin_cascade/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from django.contrib import admin from django.db.models import Q from django.http import JsonResponse, HttpResponseForbidden from django.utils.translation import get_language_from_request from cms.models.pagemodel import Page from cms.extensions import PageExtensionAdmin from cmsplugin_cascade.models import CascadePage from cmsplugin_cascade.link.forms import format_page_link @admin.register(CascadePage) class CascadePageAdmin(PageExtensionAdmin): def get_fields(self, request, obj=None): return ['icon_font'] def get_urls(self): urls = [ url(r'^get_page_sections/$', lambda: None, name='get_page_sections'), # just to reverse url(r'^get_page_sections/(?P<page_pk>\d+)$', self.admin_site.admin_view(self.get_page_sections)), url(r'^published_pages/$', self.get_published_pagelist, name='get_published_pagelist'), ] urls.extend(super(CascadePageAdmin, self).get_urls()) return urls def get_page_sections(self, request, page_pk=None): choices = [] try: for key, val in self.model.objects.get(extended_object_id=page_pk).glossary['element_ids'].items(): choices.append((key, val)) except (self.model.DoesNotExist, KeyError): pass return JsonResponse({'element_ids': choices}) def get_published_pagelist(self, request, *args, **kwargs): """ This view is used by the SearchLinkField as the user types to feed the autocomplete drop-down. """ if not request.is_ajax(): return HttpResponseForbidden() query_term = request.GET.get('term','').strip('/') language = get_language_from_request(request) matching_published_pages = Page.objects.published().public().filter( Q(title_set__title__icontains=query_term, title_set__language=language) | Q(title_set__path__icontains=query_term, title_set__language=language) | Q(title_set__menu_title__icontains=query_term, title_set__language=language) | Q(title_set__page_title__icontains=query_term, title_set__language=language) ).distinct().order_by('title_set__title').iterator() data = {'results': []} for page in matching_published_pages: title = page.get_title(language=language) path = page.get_absolute_url(language=language) data['results'].append({ 'id': page.pk, 'text': format_page_link(title, path), }) if len(data['results']) > 15: break return JsonResponse(data)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from django.contrib import admin from django.db.models import Q from django.http import JsonResponse, HttpResponseForbidden from django.utils.translation import get_language_from_request from cms.models.pagemodel import Page from cms.extensions import PageExtensionAdmin from cmsplugin_cascade.models import CascadePage from cmsplugin_cascade.link.forms import format_page_link @admin.register(CascadePage) class CascadePageAdmin(PageExtensionAdmin): def get_urls(self): urls = [ url(r'^get_page_sections/$', lambda: None, name='get_page_sections'), # just to reverse url(r'^get_page_sections/(?P<page_pk>\d+)$', self.admin_site.admin_view(self.get_page_sections)), url(r'^published_pages/$', self.get_published_pagelist, name='get_published_pagelist'), ] urls.extend(super(CascadePageAdmin, self).get_urls()) return urls def get_page_sections(self, request, page_pk=None): choices = [] try: for key, val in self.model.objects.get(extended_object_id=page_pk).glossary['element_ids'].items(): choices.append((key, val)) except (self.model.DoesNotExist, KeyError): pass return JsonResponse({'element_ids': choices}) def get_published_pagelist(self, request, *args, **kwargs): """ This view is used by the SearchLinkField as the user types to feed the autocomplete drop-down. """ if not request.is_ajax(): return HttpResponseForbidden() query_term = request.GET.get('term','').strip('/') language = get_language_from_request(request) matching_published_pages = Page.objects.published().public().filter( Q(title_set__title__icontains=query_term, title_set__language=language) | Q(title_set__path__icontains=query_term, title_set__language=language) | Q(title_set__menu_title__icontains=query_term, title_set__language=language) | Q(title_set__page_title__icontains=query_term, title_set__language=language) ).distinct().order_by('title_set__title').iterator() data = {'results': []} for page in matching_published_pages: title = page.get_title(language=language) path = page.get_absolute_url(language=language) data['results'].append({ 'id': page.pk, 'text': format_page_link(title, path), }) if len(data['results']) > 15: break return JsonResponse(data)
Python
0.000001
77d8f11277e3b006c9f9137a35291892a73156f2
format python code
alexBot/cogs/games_reposting.py
alexBot/cogs/games_reposting.py
import logging from typing import Dict import discord from discord import PartialEmoji from discord.ext import commands from discord.message import Message from discord.webhook import AsyncWebhookAdapter, WebhookMessage from emoji_data import EmojiSequence from ..tools import Cog log = logging.getLogger(__name__) class GamesReposting(Cog): def __init__(self, bot: "Bot"): super().__init__(bot) self.linked: Dict[int, WebhookMessage] = {} self.webhook = discord.Webhook.from_url( self.bot.config.nerdiowo_announcements_webhook, adapter=AsyncWebhookAdapter(session=self.bot.session) ) @Cog.listener() async def on_message(self, message: discord.Message): if message.channel.category_id == 896853287108759615: additional_content = [await x.to_file() for x in message.attachments] msg = await self.webhook.send( content=message.content, wait=True, username=message.author.name, avatar_url=message.author.avatar_url, files=additional_content, embeds=message.embeds, ) self.linked[message.id] = msg @Cog.listener() async def on_message_edit(self, before: Message, after: Message): if before.id in self.linked: if before.content != after.content: await self.linked[before.id].edit(content=after.content) def setup(bot): bot.add_cog(GamesReposting(bot))
import logging from typing import Dict import discord from discord import PartialEmoji from discord.ext import commands from discord.message import Message from discord.webhook import AsyncWebhookAdapter, WebhookMessage from emoji_data import EmojiSequence from ..tools import Cog log = logging.getLogger(__name__) class GamesReposting(Cog): def __init__(self, bot: "Bot"): super().__init__(bot) self.linked: Dict[int, WebhookMessage] = {} self.webhook = discord.Webhook.from_url( self.bot.config.nerdiowo_announcements_webhook, adapter=AsyncWebhookAdapter(session=self.bot.session) ) @Cog.listener() async def on_message(self, message: discord.Message): if message.channel.category_id == 896853287108759615: additional_content = [await x.to_file() for x in message.attachments] msg = await self.webhook.send( content=message.content, wait=True, username=message.author.name, avatar_url=message.author.avatar_url, files=additional_content, embeds=message.embeds, ) self.linked[message.id] = msg @Cog.listener() async def on_message_edit(self, before: Message, after: Message): if before.id in self.linked: if before.content != after.content: await self.linked[before.id].edit(content=after.content) def setup(bot): bot.add_cog(GamesReposting(bot))
Python
0.000174
cdb7c87fd133b6e99916919b525e9d277a3913dd
Fix a typo.
libcloud/test/compute/test_ikoula.py
libcloud/test/compute/test_ikoula.py
# Licensed to the Apache Software Foundation (ASF) 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 sys from libcloud.compute.drivers.ikoula import IkoulaNodeDriver from libcloud.test.compute.test_cloudstack import CloudStackCommonTestCase from libcloud.test import unittest class IkoulaNodeDriverTestCase(CloudStackCommonTestCase, unittest.TestCase): driver_klass = IkoulaNodeDriver if __name__ == '__main__': sys.exit(unittest.main())
# Licensed to the Apache Software Foundation (ASF) 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 sys from libcloud.compute.drivers.ikoula import IkoulaNodeDriver from libcloud.test.compute.test_cloudstack import CloudStackCommonTestCase from libcloud.test import unittest class ExoscaleNodeDriverTestCase(CloudStackCommonTestCase, unittest.TestCase): driver_klass = IkoulaNodeDriver if __name__ == '__main__': sys.exit(unittest.main())
Python
0.999957
8c70752c87eb0519150e7cf17b146c97847b1460
add new preview-graylog ip to reversedns.py
modules/nagios/files/reversedns.py
modules/nagios/files/reversedns.py
#!/usr/bin/env python import socket import sys if sys.argv[1] == "ip-10-236-86-54.eu-west-1.compute.internal": print "frontend.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-250-157-37.eu-west-1.compute.internal": print "static.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-53-54-49.eu-west-1.compute.internal": print "frontend.cluster" exit(0) if sys.argv[1] == "ip-10-54-182-112.eu-west-1.compute.internal": print "signonotron.production.alphagov.co.uk" exit(0) # hack for the change to whitehalls host not being done correctly if sys.argv[1] == "ip-10-229-67-207.eu-west-1.compute.internal": # print "ip-10-224-50-207.eu-west-1.compute.internal" print "whitehall.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-236-86-54.eu-west-1.compute.internal": print "frontend.production.alphagov.co.uk" # hacks to pickup correct graphs, due to local hosts and ganglia name mismatch if sys.argv[1] in ['ip-10-54-182-112.eu-west-1.compute.internal', 'ip-10-236-86-54.eu-west-1.compute.internal', 'ip-10-250-157-37.eu-west-1.compute.internal', 'ip-10-53-54-49.eu-west-1.compute.internal', 'ip-10-32-31-104.eu-west-1.compute.internal' ]: print sys.argv[1] exit(0) try: print socket.gethostbyaddr(sys.argv[1])[0] except: print sys.argv[1]
#!/usr/bin/env python import socket import sys if sys.argv[1] == "ip-10-236-86-54.eu-west-1.compute.internal": print "frontend.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-250-157-37.eu-west-1.compute.internal": print "static.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-53-54-49.eu-west-1.compute.internal": print "frontend.cluster" exit(0) if sys.argv[1] == "ip-10-54-182-112.eu-west-1.compute.internal": print "signonotron.production.alphagov.co.uk" exit(0) # hack for the change to whitehalls host not being done correctly if sys.argv[1] == "ip-10-229-67-207.eu-west-1.compute.internal": # print "ip-10-224-50-207.eu-west-1.compute.internal" print "whitehall.production.alphagov.co.uk" exit(0) if sys.argv[1] == "ip-10-236-86-54.eu-west-1.compute.internal": print "frontend.production.alphagov.co.uk" # hacks to pickup correct graphs, due to local hosts and ganglia name mismatch if sys.argv[1] in ['ip-10-54-182-112.eu-west-1.compute.internal', 'ip-10-236-86-54.eu-west-1.compute.internal', 'ip-10-250-157-37.eu-west-1.compute.internal', 'ip-10-53-54-49.eu-west-1.compute.internal']: print sys.argv[1] exit(0) try: print socket.gethostbyaddr(sys.argv[1])[0] except: print sys.argv[1]
Python
0
b5b4c1f5b72494e00064b36f2ee1c53d1b5c2aca
Revert 83430 - NaCl: Re-enable tests, since they pass on the trybotsBUG=noneTEST=nacl_integrationReview URL: http://codereview.chromium.org/6904067 TBR=mseaborn@chromium.org Review URL: http://codereview.chromium.org/6902132
chrome/test/nacl_test_injection/buildbot_nacl_integration.py
chrome/test/nacl_test_injection/buildbot_nacl_integration.py
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in os.environ.get('PWD', '')): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in os.environ.get('PWD', '')): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in os.environ.get('PWD', '')): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
Python
0.000001
bbfa0b6fc8e4bb851528084d147ee898fd5af06a
fix path issues
experimentator/__main__.py
experimentator/__main__.py
"""experimentator Usage: exp run [options] <exp-file> (--next <level> [--not-finished] | (<level> <n>)...) exp resume [options] <exp-file> <level> [<n> (<level> <n>)...] exp export <exp-file> <data-file> exp -h | --help exp --version Options: --not-finished Run the first <level> that hasn't finished (rather than first that hasn't started). --demo Don't save data. --debug Set logging level to DEBUG. --skip-parents Don't call start and end callbacks of parent levels. -h, --help Show full help. --version Print the installed version number of experimentator. Commands: run <exp-file> --next <level> Runs the first <level> that hasn't started. E.g.: exp run exp1.dat --next session run <exp-file> (<level> <n>)... Runs the section specified by any number of <level> <n> pairs. E.g.: exp run exp1.dat participant 3 session 1 resume <exp-file> <level> Resume the first section at <level> that has been started but not finished. resume <exp-file> (<level> <n>)... Resume the section specified by any number of <level> <n> pairs. The specified section must have been started but not finished. E.g.: exp resume exp1.dat participant 2 session 2 export <exp-file> <data-file> Export the data in <exp-file> to csv format as <data-file>. Note: This will not produce readable csv files for experiments with results in multi-element data structures (e.g., timeseries, dicts). """ import sys import os import logging from docopt import docopt from schema import Schema, Use, And, Or, Optional from experimentator import __version__, load_experiment, run_experiment_section, export_experiment_data def main(args=None): # I can't figure out why but this is necessary. sys.path.insert(0, os.getcwd()) scheme = Schema({Optional('--debug'): bool, Optional('--demo'): bool, Optional('--help'): bool, Optional('--next'): bool, Optional('--not-finished'): bool, Optional('--skip-parents'): bool, Optional('--version'): bool, Optional('<data-file>'): Or(lambda x: x is None, os.path.exists), Optional('<exp-file>'): Or(lambda x: x is None, os.path.exists), Optional('<level>'): [str], Optional('<n>'): [And(Use(int), lambda n: n > 0)], Optional('export'): bool, Optional('resume'): bool, Optional('run'): bool, }) options = scheme.validate(docopt(__doc__, argv=args, version=__version__)) if options['--debug']: logging.basicConfig(level=logging.DEBUG) if options['run'] or options['resume']: exp = load_experiment(options['<exp-file>']) kwargs = {'demo': options['--demo'], 'parent_callbacks': not options['--skip-parents'], 'resume': options['resume'], } if options['--next']: kwargs.update(section_obj=exp.find_first_not_run( options['<level>'][0], by_started=options['--not-finished'])) elif options['resume'] and not options['<n>']: kwargs.update(section_obj=exp.find_first_partially_run(options['<level>'][0])) else: kwargs.update(zip(options['<level>'], options['<n>'])) run_experiment_section(exp, **kwargs) elif options['export']: export_experiment_data(options['<exp-file>'], options['<data-file>'])
"""experimentator Usage: exp run [options] <exp-file> (--next <level> [--not-finished] | (<level> <n>)...) exp resume [options] <exp-file> <level> [<n> (<level> <n>)...] exp export <exp-file> <data-file> exp -h | --help exp --version Options: --not-finished Run the first <level> that hasn't finished (rather than first that hasn't started). --demo Don't save data. --debug Set logging level to DEBUG. --skip-parents Don't call start and end callbacks of parent levels. -h, --help Show full help. --version Print the installed version number of experimentator. Commands: run <exp-file> --next <level> Runs the first <level> that hasn't started. E.g.: exp run exp1.dat --next session run <exp-file> (<level> <n>)... Runs the section specified by any number of <level> <n> pairs. E.g.: exp run exp1.dat participant 3 session 1 resume <exp-file> <level> Resume the first section at <level> that has been started but not finished. resume <exp-file> (<level> <n>)... Resume the section specified by any number of <level> <n> pairs. The specified section must have been started but not finished. E.g.: exp resume exp1.dat participant 2 session 2 export <exp-file> <data-file> Export the data in <exp-file> to csv format as <data-file>. Note: This will not produce readable csv files for experiments with results in multi-element data structures (e.g., timeseries, dicts). """ import sys import os.path import logging from docopt import docopt from schema import Schema, Use, And, Or, Optional from experimentator import __version__, load_experiment, run_experiment_section, export_experiment_data def main(args=None): scheme = Schema({Optional('--debug'): bool, Optional('--demo'): bool, Optional('--help'): bool, Optional('--next'): bool, Optional('--not-finished'): bool, Optional('--skip-parents'): bool, Optional('--version'): bool, Optional('<data-file>'): Or(lambda x: x is None, os.path.exists), Optional('<exp-file>'): Or(lambda x: x is None, os.path.exists), Optional('<level>'): [str], Optional('<n>'): [And(Use(int), lambda n: n > 0)], Optional('export'): bool, Optional('resume'): bool, Optional('run'): bool, }) options = scheme.validate(docopt(__doc__, argv=args, version=__version__)) if options['--debug']: logging.basicConfig(level=logging.DEBUG) if options['run'] or options['resume']: exp = load_experiment(options['<exp-file>']) kwargs = {'demo': options['--demo'], 'parent_callbacks': not options['--skip-parents'], 'resume': options['resume'], } if options['--next']: kwargs.update(section_obj=exp.find_first_not_run( options['<level>'][0], by_started=options['--not-finished'])) elif options['resume'] and not options['<n>']: kwargs.update(section_obj=exp.find_first_partially_run(options['<level>'][0])) else: kwargs.update(zip(options['<level>'], options['<n>'])) run_experiment_section(exp, **kwargs) elif options['export']: export_experiment_data(options['<exp-file>'], options['<data-file>']) if __name__ == '__main__': main(sys.argv) sys.exit(0)
Python
0.000001
0bf63976303515d0702f0a29d14364825a67053a
use pid for msgid to avoid duplicate message error
mpcontribs-api/mpcontribs/api/notebooks/__init__.py
mpcontribs-api/mpcontribs/api/notebooks/__init__.py
# -*- coding: utf-8 -*- import os from tornado.escape import json_encode, json_decode, url_escape from websocket import create_connection from notebook.utils import url_path_join from notebook.gateway.managers import GatewayClient def run_cells(kernel_id, cid, cells): print(f"running {cid} on {kernel_id}") gw_client = GatewayClient.instance() url = url_path_join( gw_client.ws_url, gw_client.kernels_endpoint, url_escape(kernel_id), "channels", ) outputs = {} ws = create_connection(url) for idx, cell in enumerate(cells): if cell["cell_type"] == "code": ws.send( json_encode( { "header": { "username": cid, "version": "5.3", "session": "", "msg_id": f"{cid}-{idx}-{os.getpid()}", "msg_type": "execute_request", }, "parent_header": {}, "channel": "shell", "content": { "code": cell["source"], "silent": False, "store_history": False, "user_expressions": {}, "allow_stdin": False, "stop_on_error": True, }, "metadata": {}, "buffers": {}, } ) ) outputs[idx] = [] status = None while status is None or status == "busy" or not len(outputs[idx]): msg = ws.recv() msg = json_decode(msg) msg_type = msg["msg_type"] if msg_type == "status": status = msg["content"]["execution_state"] elif msg_type in ["stream", "display_data", "execute_result"]: # display_data/execute_result required fields: # "output_type", "data", "metadata" # stream required fields: "output_type", "name", "text" output = msg["content"] output.pop("transient", None) output["output_type"] = msg_type msg_idx = msg["parent_header"]["msg_id"].split("-")[1] outputs[int(msg_idx)].append(output) elif msg_type == "error": tb = msg["content"]["traceback"] raise ValueError(tb) ws.close() return outputs
# -*- coding: utf-8 -*- from tornado.escape import json_encode, json_decode, url_escape from websocket import create_connection from notebook.utils import url_path_join from notebook.gateway.managers import GatewayClient def run_cells(kernel_id, cid, cells): print(f"running {cid} on {kernel_id}") gw_client = GatewayClient.instance() url = url_path_join( gw_client.ws_url, gw_client.kernels_endpoint, url_escape(kernel_id), "channels", ) outputs = {} ws = create_connection(url) for idx, cell in enumerate(cells): if cell["cell_type"] == "code": ws.send( json_encode( { "header": { "username": cid, "version": "5.3", "session": "", "msg_id": f"{cid}-{idx}", "msg_type": "execute_request", }, "parent_header": {}, "channel": "shell", "content": { "code": cell["source"], "silent": False, "store_history": False, "user_expressions": {}, "allow_stdin": False, "stop_on_error": True, }, "metadata": {}, "buffers": {}, } ) ) outputs[idx] = [] status = None while status is None or status == "busy" or not len(outputs[idx]): msg = ws.recv() msg = json_decode(msg) msg_type = msg["msg_type"] if msg_type == "status": status = msg["content"]["execution_state"] elif msg_type in ["stream", "display_data", "execute_result"]: # display_data/execute_result required fields: # "output_type", "data", "metadata" # stream required fields: "output_type", "name", "text" output = msg["content"] output.pop("transient", None) output["output_type"] = msg_type msg_idx = msg["parent_header"]["msg_id"].split("-", 1)[1] outputs[int(msg_idx)].append(output) elif msg_type == "error": tb = msg["content"]["traceback"] raise ValueError(tb) ws.close() return outputs
Python
0
abb28a62ae8bf6ca95e3cb4419abc6a1bf161f5b
Remove outdated notes
scopus/utils/get_content.py
scopus/utils/get_content.py
import os import requests from scopus import exception from scopus.utils import config errors = {400: exception.Scopus400Error, 401: exception.Scopus401Error, 404: exception.Scopus404Error, 429: exception.Scopus429Error, 500: exception.Scopus500Error} def download(url, params=None, accept="xml"): """Helper function to download a file and return its content. Parameters ---------- url : string The URL to be parsed. params : dict (optional) Dictionary containing query parameters. For required keys and accepted values see e.g. https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl accept : str (optional, default=xml) mime type of the file to be downloaded. Accepted values are json, atom+xml, xml. Raises ------ ScopusHtmlError If the status of the response is not ok. ValueError If the accept parameter is not one of the accepted values. Returns ------- resp : byte-like object The content of the file, which needs to be serialized. """ # Value check accepted = ("json", "xml", "atom+xml") if accept.lower() not in accepted: raise ValueError('accept parameter must be one of ' + ', '.join(accepted)) # Get credentials key = config.get('Authentication', 'APIKey') header = {'X-ELS-APIKey': key} if config.has_option('Authentication', 'InstToken'): token = config.get('Authentication', 'InstToken') header.update({'X-ELS-APIKey': key, 'X-ELS-Insttoken': token}) header.update({'Accept': 'application/{}'.format(accept)}) # Perform request resp = requests.get(url, headers=header, params=params) # Raise error if necessary try: reason = resp.reason.upper() + " for url: " + url raise errors[resp.status_code](reason) except KeyError: # Exception not specified in scopus resp.raise_for_status() # Will pass when everything is ok return resp def get_content(qfile, refresh, *args, **kwds): """Helper function to read file content as xml. The file is cached in a subfolder of ~/.scopus/. Parameters ---------- qfile : string The name of the file to be created. refresh : bool Whether the file content should be refreshed if it exists. *args, **kwds : Arguments and keywords to be passed on to download(). Returns ------- content : str The content of the file. """ if not refresh and os.path.exists(qfile): with open(qfile, 'rb') as f: content = f.read() else: content = download(*args, **kwds).text.encode('utf-8') with open(qfile, 'wb') as f: f.write(content) return content
import os import requests from scopus import exception from scopus.utils import config errors = {400: exception.Scopus400Error, 401: exception.Scopus401Error, 404: exception.Scopus404Error, 429: exception.Scopus429Error, 500: exception.Scopus500Error} def download(url, params=None, accept="xml"): """Helper function to download a file and return its content. Parameters ---------- url : string The URL to be parsed. params : dict (optional) Dictionary containing query parameters. For required keys and accepted values see e.g. https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl accept : str (optional, default=xml) mime type of the file to be downloaded. Accepted values are json, atom+xml, xml. Raises ------ ScopusHtmlError If the status of the response is not ok. ValueError If the accept parameter is not one of the accepted values. Returns ------- resp : byte-like object The content of the file, which needs to be serialized. Notes ----- Loads the Authentication creditation into scopus namespace on first run. If there is a config file, which must contain InstToken, it is given preference. Alternatively it loads the API key from my_scopus.py file. """ # Value check accepted = ("json", "xml", "atom+xml") if accept.lower() not in accepted: raise ValueError('accept parameter must be one of ' + ', '.join(accepted)) # Get credentials key = config.get('Authentication', 'APIKey') header = {'X-ELS-APIKey': key} if config.has_option('Authentication', 'InstToken'): token = config.get('Authentication', 'InstToken') header.update({'X-ELS-APIKey': key, 'X-ELS-Insttoken': token}) header.update({'Accept': 'application/{}'.format(accept)}) # Perform request resp = requests.get(url, headers=header, params=params) # Raise error if necessary try: reason = resp.reason.upper() + " for url: " + url raise errors[resp.status_code](reason) except KeyError: # Exception not specified in scopus resp.raise_for_status() # Will pass when everything is ok return resp def get_content(qfile, refresh, *args, **kwds): """Helper function to read file content as xml. The file is cached in a subfolder of ~/.scopus/. Parameters ---------- qfile : string The name of the file to be created. refresh : bool Whether the file content should be refreshed if it exists. *args, **kwds : Arguments and keywords to be passed on to download(). Returns ------- content : str The content of the file. """ if not refresh and os.path.exists(qfile): with open(qfile, 'rb') as f: content = f.read() else: content = download(*args, **kwds).text.encode('utf-8') with open(qfile, 'wb') as f: f.write(content) return content
Python
0.000002
b8fd3a256062a5f7740480bb5b844560e3a47f6d
Add more log on test_versioning
nuxeo-drive-client/nxdrive/tests/test_versioning.py
nuxeo-drive-client/nxdrive/tests/test_versioning.py
import time from nxdrive.tests.common import TEST_WORKSPACE_PATH from nxdrive.tests.common import OS_STAT_MTIME_RESOLUTION from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.logging_config import get_logger log = get_logger(__name__) class TestVersioning(UnitTestCase): def test_versioning(self): # Call the Nuxeo operation to set the versioning delay to 30 seconds self.versioning_delay = OS_STAT_MTIME_RESOLUTION * 30 self.root_remote_client.execute( "NuxeoDrive.SetVersioningOptions", delay=str(self.versioning_delay)) local = self.local_client_1 self.engine_1.start() # Create a file as user 2 self.remote_document_client_2.make_file('/', 'Test versioning.txt', "This is version 0") self.assertTrue(self.remote_document_client_2.exists('/Test versioning.txt')) doc = self.root_remote_client.fetch(TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 0) # Synchronize it for user 1 self.wait_sync(wait_for_async=True) self.assertTrue(local.exists('/Test versioning.txt')) # Update it as user 1 => should be versioned time.sleep(OS_STAT_MTIME_RESOLUTION) local.update_content('/Test versioning.txt', "Modified content") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 1) # Update it as user 1 => should NOT be versioned # since the versioning delay is not passed by time.sleep(OS_STAT_MTIME_RESOLUTION) local.update_content('/Test versioning.txt', "Content twice modified") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 1) # Wait for versioning delay expiration then update it as user 1 after # => should be versioned since the versioning delay is passed by log.debug("wait for %d to end the versioning grace", (self.versioning_delay + 2.0)) time.sleep(self.versioning_delay + 2.0) log.debug("will now update content of Test versioning.txt") local.update_content('/Test versioning.txt', "Updated again!!") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 2) def test_version_restore(self): remote_client = self.remote_document_client_1 local_client = self.local_client_1 self.engine_1.start() # Create a remote doc doc = remote_client.make_file(self.workspace, 'Document to restore.txt', content="Initial content.") self.wait_sync(wait_for_async=True) self.assertTrue(local_client.exists('/Document to restore.txt')) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Initial content.") # Create version 1.0, update content, then restore version 1.0 remote_client.create_version(doc, 'Major') remote_client.update_content(doc, "Updated content.") self.wait_sync(wait_for_async=True) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Updated content.") version_uid = remote_client.get_versions(doc)[0][0] remote_client.restore_version(version_uid) self.wait_sync(wait_for_async=True) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Initial content.") def _assert_version(self, doc, major, minor): self.assertEquals(doc['properties']['uid:major_version'], major) self.assertEquals(doc['properties']['uid:minor_version'], minor)
import time from nxdrive.tests.common import TEST_WORKSPACE_PATH from nxdrive.tests.common import OS_STAT_MTIME_RESOLUTION from nxdrive.tests.common_unit_test import UnitTestCase class TestVersioning(UnitTestCase): def test_versioning(self): # Call the Nuxeo operation to set the versioning delay to 30 seconds self.versioning_delay = OS_STAT_MTIME_RESOLUTION * 30 self.root_remote_client.execute( "NuxeoDrive.SetVersioningOptions", delay=str(self.versioning_delay)) local = self.local_client_1 self.engine_1.start() # Create a file as user 2 self.remote_document_client_2.make_file('/', 'Test versioning.txt', "This is version 0") self.assertTrue(self.remote_document_client_2.exists('/Test versioning.txt')) doc = self.root_remote_client.fetch(TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 0) # Synchronize it for user 1 self.wait_sync(wait_for_async=True) self.assertTrue(local.exists('/Test versioning.txt')) # Update it as user 1 => should be versioned time.sleep(OS_STAT_MTIME_RESOLUTION) local.update_content('/Test versioning.txt', "Modified content") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 1) # Update it as user 1 => should NOT be versioned # since the versioning delay is not passed by time.sleep(OS_STAT_MTIME_RESOLUTION) local.update_content('/Test versioning.txt', "Content twice modified") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 1) # Wait for versioning delay expiration then update it as user 1 after # => should be versioned since the versioning delay is passed by time.sleep(self.versioning_delay + 2.0) local.update_content('/Test versioning.txt', "Updated again!!") self.wait_sync() doc = self.root_remote_client.fetch( TEST_WORKSPACE_PATH + '/Test versioning.txt') self._assert_version(doc, 0, 2) def test_version_restore(self): remote_client = self.remote_document_client_1 local_client = self.local_client_1 self.engine_1.start() # Create a remote doc doc = remote_client.make_file(self.workspace, 'Document to restore.txt', content="Initial content.") self.wait_sync(wait_for_async=True) self.assertTrue(local_client.exists('/Document to restore.txt')) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Initial content.") # Create version 1.0, update content, then restore version 1.0 remote_client.create_version(doc, 'Major') remote_client.update_content(doc, "Updated content.") self.wait_sync(wait_for_async=True) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Updated content.") version_uid = remote_client.get_versions(doc)[0][0] remote_client.restore_version(version_uid) self.wait_sync(wait_for_async=True) self.assertEquals(local_client.get_content('/Document to restore.txt'), "Initial content.") def _assert_version(self, doc, major, minor): self.assertEquals(doc['properties']['uid:major_version'], major) self.assertEquals(doc['properties']['uid:minor_version'], minor)
Python
0
434f565dc7b2b1c037b36096ad10978cfc0eaa49
add yaml dump encode utf8
lmdo/resolvers/templates_resolver.py
lmdo/resolvers/templates_resolver.py
import os import tempfile import json import yaml from lmdo.resolvers import Resolver from lmdo.convertors.env_var_convertor import EnvVarConvertor from lmdo.convertors.stack_var_convertor import StackVarConvertor from lmdo.convertors.nested_template_url_convertor import NestedTemplateUrlConvertor from lmdo.file_loader import FileLoader from lmdo.config import FILE_LOADER_TEMPLATE_ALLOWED_EXT from lmdo.oprint import Oprint class TemplatesResolver(Resolver): """ Resolve templates """ YAML_TO = {'!': '^'} TO_YAML = {'^': '!'} def __init__(self, template_path, repo_path=None): if not os.path.isfile(template_path): Oprint.err('Template not found by given path {}'.format(templated_path), 'cloudformation') self._template_path = template_path # Default to project root if not given self._repo_path = repo_path or './' self._temp_dir = tempfile.mkdtemp() def resolve(self): return self.get_templates() def get_templates(self): """Get all the nested stacks""" # Create master template templates = { "tmp_dir": self._temp_dir, "master": None, "children": [] } def yaml_tmp_ctor(loader, tag_suffix, node): if tag.suffix.startswith('!'): return node master_tpl = FileLoader(file_path=self._template_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT, yaml_replacements=self.YAML_TO).process() template_urls = [] for name, resource in master_tpl['Resources'].iteritems(): if resource['Type'] == 'AWS::CloudFormation::Stack': template_urls.append(resource['Properties']['TemplateURL']) if template_urls: for url in template_urls: if url.startswith('$template'): header, template_name = url.split("|") templates['children'].append(self.create_template(template_name)) templates['master'] = self.create_template(self._template_path) return templates def create_template(self, template_name): """Create shadow template for upload""" # Setup convertor chain env_var_convertor = EnvVarConvertor() stack_var_convertor = StackVarConvertor() nested_template_convertor = NestedTemplateUrlConvertor() env_var_convertor.successor = stack_var_convertor stack_var_convertor.successor = nested_template_convertor if not os.path.isfile(template_name): file_path = self.find_template(template_name) else: file_path = template_name if not file_path: Oprint.err('Cannot find template {} in {}'.format(template_name, self._repo_path)) file_loader = FileLoader(file_path=file_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT, yaml_replacements=self.YAML_TO) file_loader.successor = env_var_convertor result = file_loader.process() if file_loader.is_yaml(): result = yaml.safe_dump(result, default_flow_style=False, encoding=('utf-8')) for key, value in self.TO_YAML.iteritems(): result = result.replace(key, value) template_name = os.path.basename(file_path) new_file_path = os.path.join(self._temp_dir, template_name) with open(new_file_path, 'w+') as f: f.write(json.dumps(result)) f.close() return new_file_path def find_template(self, template_name): """Get list of params files""" findings = [] if os.path.isdir(self._repo_path): findings = FileLoader.find_files_by_names(search_path=self._repo_path, only_files=[template_name]) # Only return the first found return findings[0] if findings else None
import os import tempfile import json import yaml from lmdo.resolvers import Resolver from lmdo.convertors.env_var_convertor import EnvVarConvertor from lmdo.convertors.stack_var_convertor import StackVarConvertor from lmdo.convertors.nested_template_url_convertor import NestedTemplateUrlConvertor from lmdo.file_loader import FileLoader from lmdo.config import FILE_LOADER_TEMPLATE_ALLOWED_EXT from lmdo.oprint import Oprint class TemplatesResolver(Resolver): """ Resolve templates """ YAML_TO = {'!': '^'} TO_YAML = {'^': '!'} def __init__(self, template_path, repo_path=None): if not os.path.isfile(template_path): Oprint.err('Template not found by given path {}'.format(templated_path), 'cloudformation') self._template_path = template_path # Default to project root if not given self._repo_path = repo_path or './' self._temp_dir = tempfile.mkdtemp() def resolve(self): return self.get_templates() def get_templates(self): """Get all the nested stacks""" # Create master template templates = { "tmp_dir": self._temp_dir, "master": None, "children": [] } def yaml_tmp_ctor(loader, tag_suffix, node): if tag.suffix.startswith('!'): return node master_tpl = FileLoader(file_path=self._template_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT, yaml_replacements=self.YAML_TO).process() template_urls = [] for name, resource in master_tpl['Resources'].iteritems(): if resource['Type'] == 'AWS::CloudFormation::Stack': template_urls.append(resource['Properties']['TemplateURL']) if template_urls: for url in template_urls: if url.startswith('$template'): header, template_name = url.split("|") templates['children'].append(self.create_template(template_name)) templates['master'] = self.create_template(self._template_path) return templates def create_template(self, template_name): """Create shadow template for upload""" # Setup convertor chain env_var_convertor = EnvVarConvertor() stack_var_convertor = StackVarConvertor() nested_template_convertor = NestedTemplateUrlConvertor() env_var_convertor.successor = stack_var_convertor stack_var_convertor.successor = nested_template_convertor if not os.path.isfile(template_name): file_path = self.find_template(template_name) else: file_path = template_name if not file_path: Oprint.err('Cannot find template {} in {}'.format(template_name, self._repo_path)) file_loader = FileLoader(file_path=file_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT, yaml_replacements=self.YAML_TO) file_loader.successor = env_var_convertor result = file_loader.process() if file_loader.is_yaml(): result = yaml.safe_dump(result, default_flow_style=False) for key, value in self.TO_YAML.iteritems(): result = result.replace(key, value) template_name = os.path.basename(file_path) new_file_path = os.path.join(self._temp_dir, template_name) with open(new_file_path, 'w+') as f: f.write(json.dumps(result)) f.close() return new_file_path def find_template(self, template_name): """Get list of params files""" findings = [] if os.path.isdir(self._repo_path): findings = FileLoader.find_files_by_names(search_path=self._repo_path, only_files=[template_name]) # Only return the first found return findings[0] if findings else None
Python
0.000002
c2ca2932ba6aa29e002317ce7775611a2ed39d42
fix template resovler for yaml file
lmdo/resolvers/templates_resolver.py
lmdo/resolvers/templates_resolver.py
import os import tempfile import json from lmdo.resolvers import Resolver from lmdo.convertors.env_var_convertor import EnvVarConvertor from lmdo.convertors.stack_var_convertor import StackVarConvertor from lmdo.convertors.nested_template_url_convertor import NestedTemplateUrlConvertor from lmdo.file_loader import FileLoader from lmdo.config import FILE_LOADER_TEMPLATE_ALLOWED_EXT from lmdo.oprint import Oprint class TemplatesResolver(Resolver): """ Resolve templates """ def __init__(self, template_path, repo_path=None): if not os.path.isfile(template_path): Oprint.err('Template not found by given path {}'.format(templated_path), 'cloudformation') self._template_path = template_path # Default to project root if not given self._repo_path = repo_path or './' self._temp_dir = tempfile.mkdtemp() def resolve(self): return self.get_templates() def get_templates(self): """Get all the nested stacks""" # Create master template templates = { "tmp_dir": self._temp_dir, "master": None, "children": [] } master_tpl = FileLoader(file_path=self._template_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT).process() template_urls = [] for name, resource in master_tpl['Resources'].iteritems(): if resource['Type'] == 'AWS::CloudFormation::Stack': template_urls.append(resource['Properties']['TemplateURL']) if template_urls: for url in template_urls: if url.startswith('$template'): header, template_name = url.split("|") templates['children'].append(self.create_template(template_name)) templates['master'] = self.create_template(self._template_path) return templates def create_template(self, template_name): """Create shadow template for upload""" # Setup convertor chain env_var_convertor = EnvVarConvertor() stack_var_convertor = StackVarConvertor() nested_template_convertor = NestedTemplateUrlConvertor() env_var_convertor.successor = stack_var_convertor stack_var_convertor.successor = nested_template_convertor if not os.path.isfile(template_name): file_path = self.find_template(template_name) else: file_path = template_name if not file_path: Oprint.err('Cannot find template {} in {}'.format(template_name, self._repo_path)) file_loader = FileLoader(file_path=file_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT) file_loader.successor = env_var_convertor result = file_loader.process() template_name = os.path.basename(file_path) new_file_path = os.path.join(self._temp_dir, template_name) with open(new_file_path, 'w+') as f: f.write(unicode(result)) f.close() return new_file_path def find_template(self, template_name): """Get list of params files""" findings = [] if os.path.isdir(self._repo_path): findings = FileLoader.find_files_by_names(search_path=self._repo_path, only_files=[template_name]) # Only return the first found return findings[0] if findings else None
import os import tempfile import json from lmdo.resolvers import Resolver from lmdo.convertors.env_var_convertor import EnvVarConvertor from lmdo.convertors.stack_var_convertor import StackVarConvertor from lmdo.convertors.nested_template_url_convertor import NestedTemplateUrlConvertor from lmdo.file_loader import FileLoader from lmdo.config import FILE_LOADER_TEMPLATE_ALLOWED_EXT from lmdo.oprint import Oprint class TemplatesResolver(Resolver): """ Resolve templates """ def __init__(self, template_path, repo_path=None): if not os.path.isfile(template_path): Oprint.err('Template not found by given path {}'.format(templated_path), 'cloudformation') self._template_path = template_path # Default to project root if not given self._repo_path = repo_path or './' self._temp_dir = tempfile.mkdtemp() def resolve(self): return self.get_templates() def get_templates(self): """Get all the nested stacks""" # Create master template templates = { "tmp_dir": self._temp_dir, "master": None, "children": [] } templates['master'] = self._template_path with open(templates['master'], 'r') as outfile: master_tpl = json.loads(outfile.read()) template_urls = [] for name, resource in master_tpl['Resources'].iteritems(): if resource['Type'] == 'AWS::CloudFormation::Stack': template_urls.append(resource['Properties']['TemplateURL']) if template_urls: for url in template_urls: if url.startswith('$template'): header, template_name = url.split("|") templates['children'].append(self.create_template(template_name)) return templates def create_template(self, template_name): """Create shadow template for upload""" # Setup convertor chain env_var_convertor = EnvVarConvertor() stack_var_convertor = StackVarConvertor() nested_template_convertor = NestedTemplateUrlConvertor() env_var_convertor.successor = stack_var_convertor stack_var_convertor.successor = nested_template_convertor file_path = self.find_template(template_name) if not file_path: Oprint.err('Cannot find template {} in {}'.format(template_name, self._repo_path)) file_loader = FileLoader(file_path=file_path, allowed_ext=FILE_LOADER_TEMPLATE_ALLOWED_EXT) file_loader.successor = env_var_convertor result = file_loader.process() template_name = os.path.basename(file_path) new_file_path = os.path.join(self._temp_dir, template_name) with open(new_file_path, 'w+') as f: f.write(unicode(result)) f.close() return new_file_path def find_template(self, template_name): """Get list of params files""" findings = [] if os.path.isdir(self._repo_path): findings = FileLoader.find_files_by_names(search_path=self._repo_path, only_files=[template_name]) print(findings) # Only return the first found return findings[0] if findings else None
Python
0
4ab211d6dd50c043cacd24db93a6bc64cfdb9ed5
update tools/validate_runtests_log.py for pytest
tools/validate_runtests_log.py
tools/validate_runtests_log.py
#!/usr/bin/env python """ Take the test runner log output from the stdin, looking for the magic line nose runner prints when the test run was successful. In an ideal world, this should be done directly in runtests.py using the nose API, some failure modes are fooling nose to terminate the python process with zero exit code, see, eg, https://github.com/scipy/scipy/issues/4736 In short, lapack's xerbla can terminate the process with a fortran level STOP command, which (i) aborts the py process so that runtests.py does not finish, and (ii) the exit code is implementation-defined. Also check that the number of tests run is larger than some baseline number (taken from the state of the master branch at some random point in time.) This probably could/should be made less brittle. """ from __future__ import print_function import sys import re if __name__ == "__main__": # full or fast test suite? try: testmode = sys.argv[1] if testmode not in ('fast', 'full'): raise IndexError except IndexError: raise ValueError("Usage: validate.py {full|fast} < logfile.") # fetch the expected number of tests # these numbers are for 6abad09 # XXX: this should probably track the commit hash or commit date expected_size = {'full': 19055, 'fast': 17738} # read in the log, parse for the pytest printout r1 = re.compile("(?P<num_failed>\d+) failed, (?P<num_passed>\d+) passed,.* in (?P<time>\d+\S+)") r2 = re.compile("(?P<num_passed>\d+) passed,.* in (?P<time>\d+\S+)") found_it = False while True: line = sys.stdin.readline() if not line: break m = r1.search(line) if not m: m = r2.search(line) if m: found_it = True break if found_it: passed = int(m.group('num_passed')) try: failed = int(m.group('num_failed')) except IndexError: failed = 0 if failed: print("*** Looks like some tests failed.") sys.exit(-1) # now check that the number of tests run is reasonable expected = expected_size[testmode] actual = passed + failed if actual < expected: print("*** Too few tests: expected %s, run %s" % (expected, actual)) sys.exit(1) else: sys.exit(0) else: print('*** Test runner validation errored: did the run really finish?') sys.exit(-1)
#!/usr/bin/env python """ Take the test runner log output from the stdin, looking for the magic line nose runner prints when the test run was successful. In an ideal world, this should be done directly in runtests.py using the nose API, some failure modes are fooling nose to terminate the python process with zero exit code, see, eg, https://github.com/scipy/scipy/issues/4736 In short, lapack's xerbla can terminate the process with a fortran level STOP command, which (i) aborts the py process so that runtests.py does not finish, and (ii) the exit code is implementation-defined. Also check that the number of tests run is larger than some baseline number (taken from the state of the master branch at some random point in time.) This probably could/should be made less brittle. """ from __future__ import print_function import sys import re if __name__ == "__main__": # full or fast test suite? try: testmode = sys.argv[1] if testmode not in ('fast', 'full'): raise IndexError except IndexError: raise ValueError("Usage: validate.py {full|fast} < logfile.") # fetch the expected number of tests # these numbers are for 6abad09 # XXX: this should probably track the commit hash or commit date expected_size = {'full': 19055, 'fast': 17738} # read in the log, parse for the nose printout: # Ran NNN tests in MMMs # <blank line> # OK (SKIP=X, KNOWNFAIL=Y) or FAILED (errors=X, failures=Y) r = re.compile("Ran (?P<num_tests>\d+) tests in (?P<time>\d+\S+)") status, found_it = False, False while True: line = sys.stdin.readline() if not line: break m = r.search(line) if m: found_it = True sys.stdin.readline() # skip the next one line = sys.stdin.readline() if "OK" in line: status = True break if found_it: # did it errored or failed? if not status: print("*** Looks like some tests failed.") sys.exit(-1) # now check that the number of tests run is reasonable expected = expected_size[testmode] actual = int(m.group('num_tests')) if actual < expected: print("*** Too few tests: expected %s, run %s" % (expected, actual)) sys.exit(1) else: sys.exit(0) else: print('*** Test runner validation errored: did the run really finish?') sys.exit(-1)
Python
0.000001
d4cbcfff04738d8fea0070f724540345a04d517a
Fix NameError bug: s/Devirtualizer/SpeculativeDevirtualizer/
utils/pass-pipeline/src/passes.py
utils/pass-pipeline/src/passes.py
from pass_pipeline import Pass # TODO: This should not be hard coded. Create a tool in the compiler that knows # how to dump the passes and the pipelines themselves. AADumper = Pass('AADumper') ABCOpt = Pass('ABCOpt') AllocBoxToStack = Pass('AllocBoxToStack') CFGPrinter = Pass('CFGPrinter') COWArrayOpts = Pass('COWArrayOpts') CSE = Pass('CSE') CapturePromotion = Pass('CapturePromotion') CapturePropagation = Pass('CapturePropagation') ClosureSpecializer = Pass('ClosureSpecializer') CodeMotion = Pass('CodeMotion') CopyForwarding = Pass('CopyForwarding') DCE = Pass('DCE') DeadFunctionElimination = Pass('DeadFunctionElimination') DeadObjectElimination = Pass('DeadObjectElimination') DefiniteInitialization = Pass('DefiniteInitialization') SpeculativeDevirtualizer = Pass('SpeculativeDevirtualizer') DiagnoseUnreachable = Pass('DiagnoseUnreachable') DiagnosticConstantPropagation = Pass('DiagnosticConstantPropagation') EarlyInliner = Pass('EarlyInliner') EmitDFDiagnostics = Pass('EmitDFDiagnostics') FunctionSignatureOpts = Pass('FunctionSignatureOpts') GlobalARCOpts = Pass('GlobalARCOpts') GlobalLoadStoreOpts = Pass('GlobalLoadStoreOpts') GlobalOpt = Pass('GlobalOpt') IVInfoPrinter = Pass('IVInfoPrinter') InOutDeshadowing = Pass('InOutDeshadowing') InstCount = Pass('InstCount') LICM = Pass('LICM') LateInliner = Pass('LateInliner') LoopInfoPrinter = Pass('LoopInfoPrinter') LoopRotate = Pass('LoopRotate') LowerAggregateInstrs = Pass('LowerAggregateInstrs') MandatoryInlining = Pass('MandatoryInlining') Mem2Reg = Pass('Mem2Reg') NoReturnFolding = Pass('NoReturnFolding') PerfInliner = Pass('PerfInliner') PerformanceConstantPropagation = Pass('PerformanceConstantPropagation') PredictableMemoryOptimizations = Pass('PredictableMemoryOptimizations') SILCleanup = Pass('SILCleanup') SILCombine = Pass('SILCombine') SILLinker = Pass('SILLinker') SROA = Pass('SROA') SimplifyCFG = Pass('SimplifyCFG') SplitAllCriticalEdges = Pass('SplitAllCriticalEdges') SplitNonCondBrCriticalEdges = Pass('SplitNonCondBrCriticalEdges') StripDebugInfo = Pass('StripDebugInfo') SwiftArrayOpts = Pass('SwiftArrayOpts') PASSES = [ AADumper, ABCOpt, AllocBoxToStack, CFGPrinter, COWArrayOpts, CSE, CapturePromotion, CapturePropagation, ClosureSpecializer, CodeMotion, CopyForwarding, DCE, DeadFunctionElimination, DeadObjectElimination, DefiniteInitialization, SpeculativeDevirtualizer, DiagnoseUnreachable, DiagnosticConstantPropagation, EarlyInliner, EmitDFDiagnostics, FunctionSignatureOpts, GlobalARCOpts, GlobalLoadStoreOpts, GlobalOpt, IVInfoPrinter, InOutDeshadowing, InstCount, LICM, LateInliner, LoopInfoPrinter, LoopRotate, LowerAggregateInstrs, MandatoryInlining, Mem2Reg, NoReturnFolding, PerfInliner, PerformanceConstantPropagation, PredictableMemoryOptimizations, SILCleanup, SILCombine, SILLinker, SROA, SimplifyCFG, SplitAllCriticalEdges, SplitNonCondBrCriticalEdges, StripDebugInfo, SwiftArrayOpts, ]
from pass_pipeline import Pass # TODO: This should not be hard coded. Create a tool in the compiler that knows # how to dump the passes and the pipelines themselves. AADumper = Pass('AADumper') ABCOpt = Pass('ABCOpt') AllocBoxToStack = Pass('AllocBoxToStack') CFGPrinter = Pass('CFGPrinter') COWArrayOpts = Pass('COWArrayOpts') CSE = Pass('CSE') CapturePromotion = Pass('CapturePromotion') CapturePropagation = Pass('CapturePropagation') ClosureSpecializer = Pass('ClosureSpecializer') CodeMotion = Pass('CodeMotion') CopyForwarding = Pass('CopyForwarding') DCE = Pass('DCE') DeadFunctionElimination = Pass('DeadFunctionElimination') DeadObjectElimination = Pass('DeadObjectElimination') DefiniteInitialization = Pass('DefiniteInitialization') Devirtualizer = Pass('SpeculativeDevirtualizer') DiagnoseUnreachable = Pass('DiagnoseUnreachable') DiagnosticConstantPropagation = Pass('DiagnosticConstantPropagation') EarlyInliner = Pass('EarlyInliner') EmitDFDiagnostics = Pass('EmitDFDiagnostics') FunctionSignatureOpts = Pass('FunctionSignatureOpts') GlobalARCOpts = Pass('GlobalARCOpts') GlobalLoadStoreOpts = Pass('GlobalLoadStoreOpts') GlobalOpt = Pass('GlobalOpt') IVInfoPrinter = Pass('IVInfoPrinter') InOutDeshadowing = Pass('InOutDeshadowing') InstCount = Pass('InstCount') LICM = Pass('LICM') LateInliner = Pass('LateInliner') LoopInfoPrinter = Pass('LoopInfoPrinter') LoopRotate = Pass('LoopRotate') LowerAggregateInstrs = Pass('LowerAggregateInstrs') MandatoryInlining = Pass('MandatoryInlining') Mem2Reg = Pass('Mem2Reg') NoReturnFolding = Pass('NoReturnFolding') PerfInliner = Pass('PerfInliner') PerformanceConstantPropagation = Pass('PerformanceConstantPropagation') PredictableMemoryOptimizations = Pass('PredictableMemoryOptimizations') SILCleanup = Pass('SILCleanup') SILCombine = Pass('SILCombine') SILLinker = Pass('SILLinker') SROA = Pass('SROA') SimplifyCFG = Pass('SimplifyCFG') SplitAllCriticalEdges = Pass('SplitAllCriticalEdges') SplitNonCondBrCriticalEdges = Pass('SplitNonCondBrCriticalEdges') StripDebugInfo = Pass('StripDebugInfo') SwiftArrayOpts = Pass('SwiftArrayOpts') PASSES = [ AADumper, ABCOpt, AllocBoxToStack, CFGPrinter, COWArrayOpts, CSE, CapturePromotion, CapturePropagation, ClosureSpecializer, CodeMotion, CopyForwarding, DCE, DeadFunctionElimination, DeadObjectElimination, DefiniteInitialization, SpeculativeDevirtualizer, DiagnoseUnreachable, DiagnosticConstantPropagation, EarlyInliner, EmitDFDiagnostics, FunctionSignatureOpts, GlobalARCOpts, GlobalLoadStoreOpts, GlobalOpt, IVInfoPrinter, InOutDeshadowing, InstCount, LICM, LateInliner, LoopInfoPrinter, LoopRotate, LowerAggregateInstrs, MandatoryInlining, Mem2Reg, NoReturnFolding, PerfInliner, PerformanceConstantPropagation, PredictableMemoryOptimizations, SILCleanup, SILCombine, SILLinker, SROA, SimplifyCFG, SplitAllCriticalEdges, SplitNonCondBrCriticalEdges, StripDebugInfo, SwiftArrayOpts, ]
Python
0.000001
992b9c46dd432ad409025a3cbaeb1c06f880526c
Resolve readline/ncurses dependency when building Lua
var/spack/packages/lua/package.py
var/spack/packages/lua/package.py
from spack import * import os class Lua(Package): """ The Lua programming language interpreter and library """ homepage = "http://www.lua.org" url = "http://www.lua.org/ftp/lua-5.1.5.tar.gz" version('5.3.1', '797adacada8d85761c079390ff1d9961') version('5.3.0', 'a1b0a7e92d0c85bbff7a8d27bf29f8af') version('5.2.4', '913fdb32207046b273fdb17aad70be13') version('5.2.3', 'dc7f94ec6ff15c985d2d6ad0f1b35654') version('5.2.2', 'efbb645e897eae37cad4344ce8b0a614') version('5.2.1', 'ae08f641b45d737d12d30291a5e5f6e3') version('5.2.0', 'f1ea831f397214bae8a265995ab1a93e') version('5.1.5', '2e115fe26e435e33b0d5c022e4490567') version('5.1.4', 'd0870f2de55d59c1c8419f36e8fac150') version('5.1.3', 'a70a8dfaa150e047866dc01a46272599') depends_on('ncurses') depends_on('readline') def install(self, spec, prefix): make('INSTALL_TOP=%s' % prefix, 'MYLDFLAGS=-L%s -lncurses' % spec['ncurses'].prefix.lib, 'linux') make('INSTALL_TOP=%s' % prefix, 'MYLDFLAGS=-L%s -lncurses' % spec['ncurses'].prefix.lib, 'install')
from spack import * import os class Lua(Package): """ The Lua programming language interpreter and library """ homepage = "http://www.lua.org" url = "http://www.lua.org/ftp/lua-5.1.5.tar.gz" version('5.3.1', '797adacada8d85761c079390ff1d9961') version('5.3.0', 'a1b0a7e92d0c85bbff7a8d27bf29f8af') version('5.2.4', '913fdb32207046b273fdb17aad70be13') version('5.2.3', 'dc7f94ec6ff15c985d2d6ad0f1b35654') version('5.2.2', 'efbb645e897eae37cad4344ce8b0a614') version('5.2.1', 'ae08f641b45d737d12d30291a5e5f6e3') version('5.2.0', 'f1ea831f397214bae8a265995ab1a93e') version('5.1.5', '2e115fe26e435e33b0d5c022e4490567') version('5.1.4', 'd0870f2de55d59c1c8419f36e8fac150') version('5.1.3', 'a70a8dfaa150e047866dc01a46272599') depends_on('ncurses') def install(self, spec, prefix): make('INSTALL_TOP=%s' % prefix, 'MYLDFLAGS="-L%s/lib -Wl,-rpath,%s"' % (spec['ncurses'].prefix,spec['ncurses'].prefix), 'linux') make('INSTALL_TOP=%s' % prefix, 'MYLDFLAGS="-L%s/lib -Wl,-rpath,%s"' % (spec['ncurses'].prefix,spec['ncurses'].prefix), 'install')
Python
0
971a1dd12c11c66ea3a42cddd693e7f20c45846c
Adding a blank line
mysite/missions/git/controllers.py
mysite/missions/git/controllers.py
# This file is part of OpenHatch. # Copyright (C) 2010 Jack Grigg # Copyright (C) 2010 John Stumpo # Copyright (C) 2010, 2011 OpenHatch, Inc. # # 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/>. from mysite.missions.base.controllers import * class GitRepository(object): def __init__(self, username): self.username = username self.repo_path = os.path.join(settings.GIT_REPO_PATH, username) self.file_url = 'file://' + self.repo_path self.public_url = settings.GIT_REPO_URL_PREFIX + username def reset(self): if os.path.isdir(self.repo_path): shutil.rmtree(self.repo_path) subprocess.check_call(['git', 'init', self.repo_path]) subprocess.check_call(['git', 'config', 'user.name', '"The Brain"'], cwd=self.repo_path) subprocess.check_call(['cp', '../../../missions/git/data/hello.py', '.'], cwd=self.repo_path) subprocess.check_call(['git', 'add', '.'], cwd=self.repo_path) subprocess.check_call(['git', 'commit', '-m', '"Initial commit"'], cwd=self.repo_path) # Touch the git-daemon-export-ok file file_obj = file(os.path.join(self.repo_path, '.git', 'git-daemon-export-ok'), 'w') file_obj.close() person = Person.objects.get(user__username=self.username) def exists(self): return os.path.isdir(self.repo_path) class GitDiffMission(object): @classmethod def commit_if_ok(cls, username, diff): repo = GitRepository(username) commit_diff = subprocess.Popen(['git', 'am'], cwd=repo.repo_path, stdin=subprocess.PIPE) commit_diff.communicate(str(diff)) if commit_diff.returncode == 0: # for shell commands, success is 0 commit_msg = """Fixed a terrible mistake. Thanks for reporting this %s. Come to my house for a dinner party. Knock 3 times and give the secret password: Pinky.""" % username subprocess.Popen(['git', 'commit', '--allow-empty', '-m', commit_msg], cwd=repo.repo_path) return True else: subprocess.check_call(['git', 'am', '--abort'], cwd=repo.repo_path) return False
# This file is part of OpenHatch. # Copyright (C) 2010 Jack Grigg # Copyright (C) 2010 John Stumpo # Copyright (C) 2010, 2011 OpenHatch, Inc. # # 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/>. from mysite.missions.base.controllers import * class GitRepository(object): def __init__(self, username): self.username = username self.repo_path = os.path.join(settings.GIT_REPO_PATH, username) self.file_url = 'file://' + self.repo_path self.public_url = settings.GIT_REPO_URL_PREFIX + username def reset(self): if os.path.isdir(self.repo_path): shutil.rmtree(self.repo_path) subprocess.check_call(['git', 'init', self.repo_path]) subprocess.check_call(['git', 'config', 'user.name', '"The Brain"'], cwd=self.repo_path) subprocess.check_call(['cp', '../../../missions/git/data/hello.py', '.'], cwd=self.repo_path) subprocess.check_call(['git', 'add', '.'], cwd=self.repo_path) subprocess.check_call(['git', 'commit', '-m', '"Initial commit"'], cwd=self.repo_path) # Touch the git-daemon-export-ok file file_obj = file(os.path.join(self.repo_path, '.git', 'git-daemon-export-ok'), 'w') file_obj.close() person = Person.objects.get(user__username=self.username) def exists(self): return os.path.isdir(self.repo_path) class GitDiffMission(object): @classmethod def commit_if_ok(cls, username, diff): repo = GitRepository(username) commit_diff = subprocess.Popen(['git', 'am'], cwd=repo.repo_path, stdin=subprocess.PIPE) commit_diff.communicate(str(diff)) if commit_diff.returncode == 0: # for shell commands, success is 0 commit_msg = """Fixed a terrible mistake. Thanks for reporting this %s. Come to my house for a dinner party. Knock 3 times and give the secret password: Pinky.""" % username subprocess.Popen(['git', 'commit', '--allow-empty', '-m', commit_msg], cwd=repo.repo_path) return True else: subprocess.check_call(['git', 'am', '--abort'], cwd=repo.repo_path) return False
Python
0.999999
81e9bf3a9cca702af11f0d7ed17d25611b9a1380
Fix for creating node instance set
vcloud_plugin_common/workflows.py
vcloud_plugin_common/workflows.py
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cloudify.decorators import workflow from cloudify.manager import update_node_instance import cloudify.plugins.workflows as default_workflow import vcloud_plugin_common def update(ctx, instance, token, org_url): """update token and url in instance""" node_instance = instance._node_instance rt_properties = node_instance['runtime_properties'] rt_properties.update({ vcloud_plugin_common.SESSION_TOKEN: token, vcloud_plugin_common.ORG_URL: org_url }) version = node_instance['version'] node_instance['version'] = version if version else 0 if ctx.local: version = node_instance['version'] state = node_instance.get('state') node_id = instance.id storage = ctx.internal.handler.storage storage.update_node_instance(node_id, version, rt_properties, state) else: update_node_instance(node_instance) def _get_all_nodes_instances(ctx, token, org_url): """return all instances from context nodes""" node_instances = set() for node in ctx.nodes: for instance in node.instances: if (vcloud_plugin_common.VCLOUD_CONFIG in node.properties and token and org_url): update(ctx, instance, token, org_url) node_instances.add(instance) return node_instances @workflow def install(ctx, **kwargs): """Score install workflow""" default_workflow._install_node_instances( ctx, _get_all_nodes_instances(ctx, kwargs.get('session_token'), kwargs.get('org_url')), set(), default_workflow.NodeInstallationTasksSequenceCreator(), default_workflow.InstallationTasksGraphFinisher ) @workflow def uninstall(ctx, **kwargs): """Score uninstall workflow""" default_workflow._uninstall_node_instances( ctx, _get_all_nodes_instances(ctx, kwargs.get('session_token'), kwargs.get('org_url')), set(), default_workflow.NodeUninstallationTasksSequenceCreator(), default_workflow.UninstallationTasksGraphFinisher )
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cloudify.decorators import workflow from cloudify.manager import update_node_instance import cloudify.plugins.workflows as default_workflow import vcloud_plugin_common def update(ctx, instance, token, org_url): """update token and url in instance""" node_instance = instance._node_instance rt_properties = node_instance['runtime_properties'] rt_properties.update({ vcloud_plugin_common.SESSION_TOKEN: token, vcloud_plugin_common.ORG_URL: org_url }) version = node_instance['version'] node_instance['version'] = version if version else 0 if ctx.local: version = node_instance['version'] state = node_instance.get('state') node_id = instance.id storage = ctx.internal.handler.storage storage.update_node_instance(node_id, version, rt_properties, state) else: update_node_instance(node_instance) def _get_all_nodes_instances(ctx, token, org_url): """return all instances from context nodes""" node_instances = set() for node in ctx.nodes: if vcloud_plugin_common.VCLOUD_CONFIG in node.properties: for instance in node.instances: if token and org_url: update(ctx, instance, token, org_url) node_instances.add(instance) return node_instances @workflow def install(ctx, **kwargs): """Score install workflow""" default_workflow._install_node_instances( ctx, _get_all_nodes_instances(ctx, kwargs.get('session_token'), kwargs.get('org_url')), set(), default_workflow.NodeInstallationTasksSequenceCreator(), default_workflow.InstallationTasksGraphFinisher ) @workflow def uninstall(ctx, **kwargs): """Score uninstall workflow""" default_workflow._uninstall_node_instances( ctx, _get_all_nodes_instances(ctx, kwargs.get('session_token'), kwargs.get('org_url')), set(), default_workflow.NodeUninstallationTasksSequenceCreator(), default_workflow.UninstallationTasksGraphFinisher )
Python
0
679755a0bae0ce8a34b9907cbc2ff9bd90144822
Remove pwd from binding file
src/spatialite/deps/iconv/binding.gyp
src/spatialite/deps/iconv/binding.gyp
{ 'variables': { 'target_arch%': 'ia32' }, 'target_defaults': { 'default_configuration': 'Debug', 'configurations': { 'Debug': { 'defines': [ 'DEBUG', '_DEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 1, # static debug }, }, }, 'Release': { 'defines': [ 'NDEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 0, # static release }, }, } }, 'msvs_settings': { 'VCCLCompilerTool': { }, 'VCLibrarianTool': { }, 'VCLinkerTool': { 'GenerateDebugInformation': 'true', }, }, 'include_dirs': [ 'config/<(OS)/<(target_arch)', '.', 'iconv/include', 'iconv/lib', 'iconv/srclib' ], 'conditions': [ ['OS == "win"', { 'defines': [ 'WIN32' ], }] ], }, 'targets': [ { 'target_name': 'iconv', 'type': 'static_library', 'sources': [ # 'iconv/extras/iconv_string.c', 'iconv/lib/iconv.c', # 'iconv/lib/iconv_relocatable.c', 'iconv/libcharset/lib/localcharset.c', # 'iconv/libcharset/lib/localcharset_relocatable.c', # 'iconv/srclib/allocator.c', # 'iconv/srclib/areadlink.c', # 'iconv/srclib/c-ctype.c', # 'iconv/srclib/canonicalize-lgpl.c', # 'iconv/srclib/careadlinkat.c', # 'iconv/srclib/error.c', # 'iconv/srclib/lstat.c', # 'iconv/srclib/malloca.c', # 'iconv/srclib/memmove.c', # 'iconv/srclib/progname.c', # 'iconv/srclib/progreloc.c', # 'iconv/srclib/read.c', # 'iconv/srclib/readlink.c', # 'iconv/srclib/relocatable.c', # 'iconv/srclib/safe-read.c', # 'iconv/srclib/setenv.c', # 'iconv/srclib/stat.c', # 'iconv/srclib/stdio-write.c', # 'iconv/srclib/strerror.c', # 'iconv/srclib/xmalloc.c', # 'iconv/srclib/xreadlink.c', # 'iconv/srclib/xstrdup.c' ], 'defines': [ 'BUILDING_LIBCHARSET', 'LIBDIR="."', 'INSTALLDIR="."', 'NO_XMALLOC', 'HAVE_CONFIG_H', 'EXEEXT=""', 'LIBPATHVAR="."' ], 'direct_dependent_settings': { 'include_dirs': [ 'config/<(OS)/<(target_arch)', '.', 'iconv/include' ], }, }, ] }
{ 'variables': { 'target_arch%': 'ia32' }, 'target_defaults': { 'default_configuration': 'Debug', 'configurations': { 'Debug': { 'defines': [ 'DEBUG', '_DEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 1, # static debug }, }, }, 'Release': { 'defines': [ 'NDEBUG' ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 0, # static release }, }, } }, 'msvs_settings': { 'VCCLCompilerTool': { }, 'VCLibrarianTool': { }, 'VCLinkerTool': { 'GenerateDebugInformation': 'true', }, }, 'include_dirs': [ 'config/<(OS)/<(target_arch)', '.', 'iconv/include', 'iconv/lib', 'iconv/srclib' ], 'conditions': [ ['OS == "win"', { 'defines': [ 'WIN32' ], }] ], }, 'targets': [ { 'target_name': 'iconv', 'type': 'static_library', 'sources': [ # 'iconv/extras/iconv_string.c', 'iconv/lib/iconv.c', # 'iconv/lib/iconv_relocatable.c', 'iconv/libcharset/lib/localcharset.c', # 'iconv/libcharset/lib/localcharset_relocatable.c', # 'iconv/srclib/allocator.c', # 'iconv/srclib/areadlink.c', # 'iconv/srclib/c-ctype.c', # 'iconv/srclib/canonicalize-lgpl.c', # 'iconv/srclib/careadlinkat.c', # 'iconv/srclib/error.c', # 'iconv/srclib/lstat.c', # 'iconv/srclib/malloca.c', # 'iconv/srclib/memmove.c', # 'iconv/srclib/progname.c', # 'iconv/srclib/progreloc.c', # 'iconv/srclib/read.c', # 'iconv/srclib/readlink.c', # 'iconv/srclib/relocatable.c', # 'iconv/srclib/safe-read.c', # 'iconv/srclib/setenv.c', # 'iconv/srclib/stat.c', # 'iconv/srclib/stdio-write.c', # 'iconv/srclib/strerror.c', # 'iconv/srclib/xmalloc.c', # 'iconv/srclib/xreadlink.c', # 'iconv/srclib/xstrdup.c' ], 'defines': [ 'BUILDING_LIBCHARSET', 'LIBDIR="."', 'INSTALLDIR="<!(pwd)"', 'NO_XMALLOC', 'HAVE_CONFIG_H', 'EXEEXT=""', 'LIBPATHVAR="."' ], 'direct_dependent_settings': { 'include_dirs': [ 'config/<(OS)/<(target_arch)', '.', 'iconv/include' ], }, }, ] }
Python
0
9d60b14e35917e7227a03d53bf6a6e83c25b7e81
Correct publication mapping dependencies
luigi/tasks/quickgo/load_mappings.py
luigi/tasks/quickgo/load_mappings.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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. """ from tasks.config import publications from tasks.utils.pgloader import PGLoader from tasks.publications.pubmed import PubmedLoader from .quickgo_data import QuickGoData from .load_annotations import QuickGoLoadAnnotations CONTROL_FILE = """ LOAD CSV FROM '{filename}' WITH ENCODING ISO-8859-14 HAVING FIELDS ({fields}) INTO {db_url} TARGET COLUMNS ({columns}) SET search_path = '{search_path}' WITH fields escaped by double-quote, fields terminated by ',' BEFORE LOAD DO $$ create table if not exists {load_table} ( rna_id varchar(50), qualifier varchar(30), assigned_by varchar(50), ontology_term_id varchar(15), evidence_code varchar(15), pubmed_id int ); $$, $$ truncate table {load_table}; $$ AFTER LOAD DO $$ insert into {final_table} (go_term_annotation_id, ref_pubmed_id) ( select annotations.go_term_annotation_id, {load_table}.pubmed_id from {load_table} join go_term_annotations annotations on annotations.rna_id = {load_table}.rna_id AND annotations.qualifier = {load_table}.qualifier AND annotations.assigned_by = {load_table}.assigned_by AND annotations.ontology_term_id = {load_table}.ontology_term_id AND annotations.evidence_code = {load_table}.evidence_code ) ON CONFLICT (go_term_annotation_id, ref_pubmed_id) DO NOTHING ; $$, $$ drop table {load_table}; $$ ; """ class QuickGoLoadPublicationMapping(PGLoader): def requires(self): return [ QuickGoData(), PubmedLoader(), QuickGoLoadAnnotations(), ] def control_file(self): output = self.requires()[0].output() table = 'go_term_publication_map' load_table = 'load_' + table fields = ', '.join(output.publication_mappings.headers) return CONTROL_FILE.format( filename=output.publication_mappings.filename, directory=publications().to_load(), final_table=table, load_table=load_table, db_url=self.db_url(table=load_table), columns=fields, fields=fields, search_path=self.db_search_path(), )
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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. """ from tasks.config import publications from tasks.utils.pgloader import PGLoader from tasks.publications.pubmed import PubmedLoader from .quickgo_data import QuickGoData CONTROL_FILE = """ LOAD CSV FROM '{filename}' WITH ENCODING ISO-8859-14 HAVING FIELDS ({fields}) INTO {db_url} TARGET COLUMNS ({columns}) SET search_path = '{search_path}' WITH fields escaped by double-quote, fields terminated by ',' BEFORE LOAD DO $$ create table if not exists {load_table} ( rna_id varchar(50), qualifier varchar(30), assigned_by varchar(50), ontology_term_id varchar(15), evidence_code varchar(15), pubmed_id int ); $$, $$ truncate table {load_table}; $$ AFTER LOAD DO $$ insert into {final_table} (go_term_annotation_id, ref_pubmed_id) ( select annotations.go_term_annotation_id, {load_table}.pubmed_id from {load_table} join go_term_annotations annotations on annotations.rna_id = {load_table}.rna_id AND annotations.qualifier = {load_table}.qualifier AND annotations.assigned_by = {load_table}.assigned_by AND annotations.ontology_term_id = {load_table}.ontology_term_id AND annotations.evidence_code = {load_table}.evidence_code ) ON CONFLICT (go_term_annotation_id, ref_pubmed_id) DO NOTHING ; $$, $$ drop table {load_table}; $$ ; """ class QuickGoLoadPublicationMapping(PGLoader): def requires(self): return [ QuickGoData(), PubmedLoader(), ] def control_file(self): output = self.requires()[0].output() table = 'go_term_publication_map' load_table = 'load_' + table fields = ', '.join(output.publication_mappings.headers) return CONTROL_FILE.format( filename=output.publication_mappings.filename, directory=publications().to_load(), final_table=table, load_table=load_table, db_url=self.db_url(table=load_table), columns=fields, fields=fields, search_path=self.db_search_path(), )
Python
0
fd8c3bdcd1fe3dea8186c4870285731e3081b396
modify parse request
src/server.py
src/server.py
# -*- coding: utf-8 -*- """Server module.""" from __future__ import unicode_literals import socket import email.utils RESOURCES = { 'images': } def resolve_uri(uri): """Return request body and file type.""" file_path = uri.split('/') print(file_path) if file_path[0] != 'webroot': response_error(u'400 Bad Request') raise LookupError('File path not found.') else: file = file_path[-1].split('.') file_type = file[1] file_name = file[0] if file_type == 'png' or file_type == 'jpg': return def parse_request(request): """Parse and validate request to confirm parts are correct.""" lines = request.split('\r\n') if: lines[0][:3] == 'GET' else: raise RuntimeError('Only accepts GET requests.') if: lines[1][-8:] == 'HTTP/1.1' else: raise TypeError if: len(lines[1].split()) == 3 and lines[1][0] == '/' uri = lines[1].split() lines = resolve_uri(uri) else: raise SyntaxError return lines def response_ok(uri): """Return 200 ok.""" first = u'HTTP/1.1 200 OK' second_line = u'Content-Type: text/plain; charset=utf-8' date = u'Date: ' + email.utils.formatdate(usegmt=True) header_break = u'' body = uri bytes_ = body.encode('utf-8') fourth_line = u'Content-Length: {}'.format(len(bytes_)) string_list = [first, second_line, date, fourth_line, header_break, body] string_list = '\r\n'.join(string_list) return string_list def response_error(error='500 Internal Server Error'): """Return 500 internal server error.""" first = u'HTTP/1.1 {}'.format(error) second_line = u'Content-Type: text/plain; charset=utf-8' date = email.utils.formatdate(usegmt=True) header_break = u'' body = u'The system is down' bytes_ = body.encode('utf-8') fourth_line = u'Content-Length: {}'.format(len(bytes_)) string_list = [first, second_line, date, fourth_line, header_break, body] string_list = '\r\n'.join(string_list) return string_list def server(): """Return message to client.""" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) address = ('127.0.0.1', 5001) server.bind(address) server.listen(1) conn, addr = server.accept() try: while True: try: buffer_length = 8 reply_complete = False full_string = u"" while not reply_complete: part = conn.recv(buffer_length) full_string = full_string + part.decode('utf-8') if len(part) < buffer_length: reply_complete = True print(full_string) try: conn.sendall(response_ok(parse_request(full_string)).encode('utf-8')) except: pass # server.listen(1) conn, addr = server.accept() except: response_error() raise except KeyboardInterrupt: conn.close() finally: server.close() if __name__ == '__main__': server() """u'405 Method Not Allowed' u'505 HTTP Version Not Supported' u'404 Page Not Found'"""
# -*- coding: utf-8 -*- """Server module.""" from __future__ import unicode_literals import socket import email.utils def resolve_uri(uri): def parse_request(request): """Parse and validate request to confirm parts are correct.""" lines = request.split('\r\n') try: lines[1][:3] == 'GET' except: response_error(u'405 Method Not Allowed') raise RuntimeError('Only accepts GET requests.') try: lines[1][-8:] == 'HTTP/1.1' except: response_error(u'505 HTTP Version Not Supported') raise RuntimeError('Only accepts HTTP/1.1 protocol requests.') try: len(lines[1].split()) == 3 and lines[1][0] == '/' uri = lines[1].split() lines = resolve_uri(uri) except: response_error(u'404 Page Not Found') raise RuntimeError('URI not properly formatted.') return lines def response_ok(uri): """Return 200 ok.""" first = u'HTTP/1.1 200 OK' second_line = u'Content-Type: text/plain; charset=utf-8' date = u'Date: ' + email.utils.formatdate(usegmt=True) header_break = u'' body = uri bytes_ = body.encode('utf-8') fourth_line = u'Content-Length: {}'.format(len(bytes_)) string_list = [first, second_line, date, fourth_line, header_break, body] string_list = '\r\n'.join(string_list) return string_list def response_error(error='500 Internal Server Error'): """Return 500 internal server error.""" first = u'HTTP/1.1 {}'.format(error) second_line = u'Content-Type: text/plain; charset=utf-8' date = email.utils.formatdate(usegmt=True) header_break = u'' body = u'The system is down' bytes_ = body.encode('utf-8') fourth_line = u'Content-Length: {}'.format(len(bytes_)) string_list = [first, second_line, date, fourth_line, header_break, body] string_list = '\r\n'.join(string_list) return string_list def server(): """Return message to client.""" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) address = ('127.0.0.1', 5001) server.bind(address) server.listen(1) conn, addr = server.accept() try: while True: try: buffer_length = 8 reply_complete = False full_string = u"" while not reply_complete: part = conn.recv(buffer_length) full_string = full_string + part.decode('utf-8') if len(part) < buffer_length: reply_complete = True print(full_string) try: conn.sendall(response_ok(parse_request(full_string)).encode('utf-8')) except: pass # server.listen(1) conn, addr = server.accept() except: response_error() raise except KeyboardInterrupt: conn.close() finally: server.close() if __name__ == '__main__': server()
Python
0.000001
c25d97ccc5109064ef80141e62c44134702b8125
Add endpoints for the admin page
src/server.py
src/server.py
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2017 - Edoardo Morassutto <edoardo.morassutto@gmail.com> import sys import traceback import gevent.wsgi from gevent import monkey from werkzeug.exceptions import (HTTPException, InternalServerError, NotFound) from werkzeug.routing import Map, Rule, RequestRedirect from werkzeug.wrappers import Request from werkzeug.wsgi import responder from .config import Config from .logger import Logger from .handlers.contest_handler import ContestHandler from .handlers.info_handler import InfoHandler from .handlers.upload_handler import UploadHandler from .handlers.admin_handler import AdminHandler monkey.patch_all() class Server: """ Main server """ def __init__(self): self.handlers = { "contest": ContestHandler(), "info": InfoHandler(), "upload": UploadHandler(), "admin": AdminHandler() } # The router tries to match the rules, the endpoint MUST be a string with this format # CONTROLLER#ACTION # Where CONTROLLER is an handler registered in self.handlers and ACTION is a valid # method of that handler self.router = Map([ Rule("/contest", methods=["GET"], endpoint="info#get_contest"), Rule("/input/<id>", methods=["GET"], endpoint="info#get_input"), Rule("/output/<id>", methods=["GET"], endpoint="info#get_output"), Rule("/source/<id>", methods=["GET"], endpoint="info#get_source"), Rule("/submission/<id>", methods=["GET"], endpoint="info#get_submission"), Rule("/user/<token>", methods=["GET"], endpoint="info#get_user"), Rule("/user/<token>/submissions/<task>", methods=["GET"], endpoint="info#get_submissions"), Rule("/generate_input", methods=["POST"], endpoint="contest#generate_input"), Rule("/submit", methods=["POST"], endpoint="contest#submit"), Rule("/upload_source", methods=["POST"], endpoint="upload#upload_source"), Rule("/upload_output", methods=["POST"], endpoint="upload#upload_output"), Rule("/admin/extract", methods=["POST"], endpoint="admin#extract"), Rule("/admin/log", methods=["POST"], endpoint="admin#log"), Rule("/admin/start", methods=["POST"], endpoint="admin#start"), Rule("/admin/set_extra_time", methods=["POST"], endpoint="admin#set_extra_time"), Rule("/admin/status", methods=["POST"], endpoint="admin#status"), Rule("/admin/user_list", methods=["POST"], endpoint="admin#user_list") ]) @responder def __call__(self, environ, start_response): try: return self.wsgi_app(environ, start_response) except: Logger.error("UNCAUGHT_EXCEPTION", traceback.format_exc()) return InternalServerError() def wsgi_app(self, environ, start_response): route = self.router.bind_to_environ(environ) request = Request(environ) try: endpoint, args = route.match() except RequestRedirect as e: return e except HTTPException: # TODO find a way to get the real ip address Logger.warning("HTTP_ERROR", "%s %s %s 404" % (request.remote_addr, request.method, request.url)) return NotFound() controller, action = endpoint.split("#") res = self.handlers[controller].handle(action, args, request) return res def run(self): """ Start a greenlet with the main HTTP server loop """ server = gevent.wsgi.WSGIServer((Config.address, Config.port), self) try: server.init_socket() except OSError: Logger.error("PORT_ALREADY_IN_USE", "Address: '%s' Port: %d" % (Config.address, Config.port)) sys.exit(1) greenlet = gevent.spawn(server.serve_forever) Logger.info("SERVER_STATUS", "Server started") greenlet.join()
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2017 - Edoardo Morassutto <edoardo.morassutto@gmail.com> import sys import traceback import gevent.wsgi from gevent import monkey from werkzeug.exceptions import (HTTPException, InternalServerError, NotFound) from werkzeug.routing import Map, Rule, RequestRedirect from werkzeug.wrappers import Request from werkzeug.wsgi import responder from .config import Config from .logger import Logger from .handlers.contest_handler import ContestHandler from .handlers.info_handler import InfoHandler from .handlers.upload_handler import UploadHandler from .handlers.admin_handler import AdminHandler monkey.patch_all() class Server: """ Main server """ def __init__(self): self.handlers = { "contest": ContestHandler(), "info": InfoHandler(), "upload": UploadHandler(), "admin": AdminHandler() } # The router tries to match the rules, the endpoint MUST be a string with this format # CONTROLLER#ACTION # Where CONTROLLER is an handler registered in self.handlers and ACTION is a valid # method of that handler self.router = Map([ Rule("/contest", methods=["GET"], endpoint="info#get_contest"), Rule("/input/<id>", methods=["GET"], endpoint="info#get_input"), Rule("/output/<id>", methods=["GET"], endpoint="info#get_output"), Rule("/source/<id>", methods=["GET"], endpoint="info#get_source"), Rule("/submission/<id>", methods=["GET"], endpoint="info#get_submission"), Rule("/user/<token>", methods=["GET"], endpoint="info#get_user"), Rule("/user/<token>/submissions/<task>", methods=["GET"], endpoint="info#get_submissions"), Rule("/generate_input", methods=["POST"], endpoint="contest#generate_input"), Rule("/submit", methods=["POST"], endpoint="contest#submit"), Rule("/upload_source", methods=["POST"], endpoint="upload#upload_source"), Rule("/upload_output", methods=["POST"], endpoint="upload#upload_output") ]) @responder def __call__(self, environ, start_response): try: return self.wsgi_app(environ, start_response) except: Logger.error("UNCAUGHT_EXCEPTION", traceback.format_exc()) return InternalServerError() def wsgi_app(self, environ, start_response): route = self.router.bind_to_environ(environ) request = Request(environ) try: endpoint, args = route.match() except RequestRedirect as e: return e except HTTPException: # TODO find a way to get the real ip address Logger.warning("HTTP_ERROR", "%s %s %s 404" % (request.remote_addr, request.method, request.url)) return NotFound() controller, action = endpoint.split("#") res = self.handlers[controller].handle(action, args, request) return res def run(self): """ Start a greenlet with the main HTTP server loop """ server = gevent.wsgi.WSGIServer((Config.address, Config.port), self) try: server.init_socket() except OSError: Logger.error("PORT_ALREADY_IN_USE", "Address: '%s' Port: %d" % (Config.address, Config.port)) sys.exit(1) greenlet = gevent.spawn(server.serve_forever) Logger.info("SERVER_STATUS", "Server started") greenlet.join()
Python
0.000001
4f2fa4e43b314c9d05e0b9b9e73641463c16a9cb
Set up the proposal tasks on app startup
server/proposal/__init__.py
server/proposal/__init__.py
from django.apps import AppConfig class ProposalConfig(AppConfig): name = "proposal" def ready(self): # Register tasks with Celery: from . import tasks tasks.set_up_hooks()
from django.apps import AppConfig class ProposalConfig(AppConfig): name = "proposal" def ready(self): # Register tasks with Celery: from . import tasks
Python
0.000064
69a16e61f0b0d5eb6d1f0819ff379c0d86b67dc3
fix in lcb
robo/acquisition/lcb.py
robo/acquisition/lcb.py
import logging import numpy as np from robo.acquisition.base_acquisition import BaseAcquisitionFunction logger = logging.getLogger(__name__) class LCB(BaseAcquisitionFunction): def __init__(self, model, X_lower, X_upper, par=0.0, **kwargs): r""" The lower confidence bound acquisition functions that computes for a test point the acquisition value by: .. math:: LCB(X) := \mu(X) - \kappa\sigma(X) Parameters ---------- model: Model object A model that implements at least - predict(X) - getCurrentBestX(). If you want to calculate derivatives than it should also support - predictive_gradients(X) X_lower: np.ndarray (D) Lower bounds of the input space X_upper: np.ndarray (D) Upper bounds of the input space par: float Controls the balance between exploration and exploitation of the acquisition function. Default is 0.01 """ self.par = par super(LCB, self).__init__(model, X_lower, X_upper) def compute(self, X, derivative=False, **kwargs): """ Computes the LCB acquisition value and its derivatives. Parameters ---------- X: np.ndarray(1, D), The input point where the acquisition function should be evaluate. The dimensionality of X is (N, D), with N as the number of points to evaluate at and D is the number of dimensions of one X. derivative: Boolean If is set to true also the derivative of the acquisition function at X is returned. Returns ------- np.ndarray(1,1) LCB value of X np.ndarray(1,D) Derivative of LCB at X (only if derivative=True) """ mean, var = self.model.predict(X) # Minimize in f so we maximize the negative lower bound acq = - (mean - self.par * np.sqrt(var)) if derivative: dm, dv = self.model.predictive_gradients(X) grad = -(dm - self.par * dv / (2 * np.sqrt(var))) return acq, grad else: return acq def update(self, model): self.model = model
import logging import numpy as np from robo.acquisition.base_acquisition import BaseAcquisitionFunction logger = logging.getLogger(__name__) class LCB(BaseAcquisitionFunction): def __init__(self, model, X_lower, X_upper, par=0.0, **kwargs): r""" The lower confidence bound acquisition functions that computes for a test point the acquisition value by: .. math:: LCB(X) := \mu(X) - \kappa\sigma(X) Parameters ---------- model: Model object A model that implements at least - predict(X) - getCurrentBestX(). If you want to calculate derivatives than it should also support - predictive_gradients(X) X_lower: np.ndarray (D) Lower bounds of the input space X_upper: np.ndarray (D) Upper bounds of the input space par: float Controls the balance between exploration and exploitation of the acquisition function. Default is 0.01 """ self.par = par super(LCB, self).__init__(model, X_lower, X_upper) def compute(self, X, derivative=False, **kwargs): """ Computes the LCB acquisition value and its derivatives. Parameters ---------- X: np.ndarray(1, D), The input point where the acquisition function should be evaluate. The dimensionality of X is (N, D), with N as the number of points to evaluate at and D is the number of dimensions of one X. derivative: Boolean If is set to true also the derivative of the acquisition function at X is returned. Returns ------- np.ndarray(1,1) LCB value of X np.ndarray(1,D) Derivative of LCB at X (only if derivative=True) """ mean, var = self.model.predict(X) # Minimize in f so we maximize the negative lower bound acq = - mean + self.par * np.sqrt(var) if derivative: dm, dv = self.model.predictive_gradients(X) grad = -dm + self.par * dv / (2 * np.sqrt(var)) return acq, grad else: return acq def update(self, model): self.model = model
Python
0.000004
3468b32964560f4092593e03ba552d7e6b56943d
Support renaming of _ to % routines
Scripts/PackRO.py
Scripts/PackRO.py
#!/usr/bin/env python # Pack .m files into M[UMPS] routine transfer format (^%RO) # # python PackRO.py *.m > routines.ro # # or # # ls *.m | python PackRO.py > routines.ro # #--------------------------------------------------------------------------- # Copyright 2011 The Open Source Electronic Health Record Agent # # 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 sys import os def pack(files, output): output.write('Routines\n\n') for f in files: if not f.endswith('.m'): sys.stderr.write('Skipping non-.m file: %s\n' % f) continue n = os.path.basename(f)[:-2] n = n.replace("_","%") m = open(f,"r") output.write('%s\n'%n) for line in m: output.write(line) output.write('\n') output.write('\n') output.write('\n') def main(): files = sys.argv[1:] if not files: files = [a.rstrip() for a in sys.stdin] pack(files, sys.stdout) if __name__ == '__main__': main()
#!/usr/bin/env python # Pack .m files into M[UMPS] routine transfer format (^%RO) # # python PackRO.py *.m > routines.ro # # or # # ls *.m | python PackRO.py > routines.ro # #--------------------------------------------------------------------------- # Copyright 2011 The Open Source Electronic Health Record Agent # # 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 sys import os def pack(files, output): output.write('Routines\n\n') for f in files: if not f.endswith('.m'): sys.stderr.write('Skipping non-.m file: %s\n' % f) continue n = os.path.basename(f)[:-2] m = open(f,"r") output.write('%s\n'%n) for line in m: output.write(line) output.write('\n') output.write('\n') output.write('\n') def main(): files = sys.argv[1:] if not files: files = [a.rstrip() for a in sys.stdin] pack(files, sys.stdout) if __name__ == '__main__': main()
Python
0.000003
1b398b07b1ba1fa8a304f24d9e75d6f76fbc56f7
remove caps and spaces walmart
Server/walmart.py
Server/walmart.py
from crawl_lib import * from pymongo import MongoClient import unicodedata import json # Parses starting from the base_url and sends the data to the db def parse(): deps_exclusions = {'91083', '5426', '4096', '4104'} full_json = json.loads(urlopen('http://api.walmartlabs.com/v1/taxonomy?format=json&apiKey=' + api_key).read().decode('utf8')) departments = full_json['categories'] for department in departments: if department['id'] in deps_exclusions: continue print(department['id']) categories = department['children'] for category in categories: if 'name' in category: cat_name = category['name'].replace('.', '-').replace(' ', '-').lower() else: print('there is no name for this category! skipping it for now!') print(category) continue if 'children' in category: subcats = category['children'] else: subcats = [category] for subcat in subcats: cat_id = subcat['id'] cat_json = json.loads(urlopen('http://api.walmartlabs.com/v1/paginated/items?format=json&category=' + cat_id + '&apiKey=' + api_key).read().decode('utf8')) items = cat_json['items'] for item in items: data = {} name = item['name'] name.encode('ascii', 'ignore') data['name'] = name.replace('.', '-').lower() if 'salePrice' in item: data['price'] = item['salePrice'] else: continue # no price for this item data['url'] = item['productUrl'] if 'thumbnailImage' in item: data['image'] = item['thumbnailImage'] else: data['image'] = '' data['store'] = 'Walmart' send_to_db(cat_name, data, cat_db, item_db, None, None) return if __name__ == '__main__': api_key = 'dw25ngn8v6wa97qt757m2a97' client = MongoClient() cat_db = client.cat_db item_db = client.items_db parse() # todo: # add category exclusion list # send timestamp along with json doc to server
from crawl_lib import * from pymongo import MongoClient import unicodedata import json # Parses starting from the base_url and sends the data to the db def parse(): deps_exclusions = {'91083', '5426', '4096', '4104'} full_json = json.loads(urlopen('http://api.walmartlabs.com/v1/taxonomy?format=json&apiKey=' + api_key).read().decode('utf8')) departments = full_json['categories'] for department in departments: if department['id'] in deps_exclusions: continue print(department['id']) categories = department['children'] for category in categories: if 'name' in category: cat_name = category['name'] else: print('there is no name for this category! skipping it for now!') print(category) continue if 'children' in category: subcats = category['children'] else: subcats = [category] for subcat in subcats: cat_id = subcat['id'] cat_json = json.loads(urlopen('http://api.walmartlabs.com/v1/paginated/items?format=json&category=' + cat_id + '&apiKey=' + api_key).read().decode('utf8')) items = cat_json['items'] for item in items: data = {} name = item['name'] name.encode('ascii', 'ignore') data['name'] = name.replace('.', '-').lower() if 'salePrice' in item: data['price'] = item['salePrice'] else: continue # no price for this item data['url'] = item['productUrl'] if 'thumbnailImage' in item: data['image'] = item['thumbnailImage'] else: data['image'] = '' data['store'] = 'Walmart' send_to_db(cat_name, data, cat_db, item_db, None, None) return if __name__ == '__main__': api_key = 'dw25ngn8v6wa97qt757m2a97' client = MongoClient() cat_db = client.cat_db item_db = client.items_db parse() # todo: # add category exclusion list # send timestamp along with json doc to server
Python
0.000002
a1d02e3a88e5c46a700385e9cef50c9ebcad68b1
Simplify test_roi_pooling_2d with no_grads option in check_backward
tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py
tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition class TestROIPooling2D(unittest.TestCase): def setUp(self): N = 4 n_channels = 3 self.x = numpy.arange( N * n_channels * 12 * 8, dtype=numpy.float32).reshape((N, n_channels, 12, 8)) numpy.random.shuffle(self.x) self.x = 2 * self.x / self.x.size - 1 self.rois = numpy.array([ [0, 1, 1, 6, 6], [2, 6, 2, 7, 11], [1, 3, 1, 5, 10], [0, 3, 3, 3, 3] ], dtype=numpy.float32) self.outh, self.outw = 5, 7 self.spatial_scale = 0.6 self.gy = numpy.random.uniform( -1, 1, (N, n_channels, self.outh, self.outw)).astype(numpy.float32) def check_forward(self, x_data, roi_data): x = chainer.Variable(x_data) rois = chainer.Variable(roi_data) y = functions.roi_pooling_2d( x, rois, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) self.assertEqual(y.data.dtype, numpy.float32) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) @condition.retry(3) def test_forward_cpu(self): self.check_forward(self.x, self.rois) @attr.gpu @condition.retry(3) def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois)) @attr.gpu @condition.retry(3) def test_forward_cpu_gpu_equal(self): # cpu x_cpu = chainer.Variable(self.x) rois_cpu = chainer.Variable(self.rois) y_cpu = functions.roi_pooling_2d( x_cpu, rois_cpu, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) # gpu x_gpu = chainer.Variable(cuda.to_gpu(self.x)) rois_gpu = chainer.Variable(cuda.to_gpu(self.rois)) y_gpu = functions.roi_pooling_2d( x_gpu, rois_gpu, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) gradient_check.assert_allclose(y_cpu.data, cuda.to_cpu(y_gpu.data)) def check_backward(self, x_data, roi_data, y_grad): gradient_check.check_backward( functions.ROIPooling2D(outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale), (x_data, roi_data), y_grad, no_grads=[False, True]) @condition.retry(3) def test_backward_cpu(self): self.check_backward(self.x, self.rois, self.gy) @attr.gpu @condition.retry(3) def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois), cuda.to_gpu(self.gy)) testing.run_module(__name__, __file__)
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition class TestROIPooling2D(unittest.TestCase): def setUp(self): N = 4 n_channels = 3 self.x = numpy.arange( N * n_channels * 12 * 8, dtype=numpy.float32).reshape((N, n_channels, 12, 8)) numpy.random.shuffle(self.x) self.x = 2 * self.x / self.x.size - 1 self.rois = numpy.array([ [0, 1, 1, 6, 6], [2, 6, 2, 7, 11], [1, 3, 1, 5, 10], [0, 3, 3, 3, 3] ], dtype=numpy.float32) self.outh, self.outw = 5, 7 self.spatial_scale = 0.6 self.gy = numpy.random.uniform( -1, 1, (N, n_channels, self.outh, self.outw)).astype(numpy.float32) def check_forward(self, x_data, roi_data): x = chainer.Variable(x_data) rois = chainer.Variable(roi_data) y = functions.roi_pooling_2d( x, rois, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) self.assertEqual(y.data.dtype, numpy.float32) y_data = cuda.to_cpu(y.data) self.assertEqual(self.gy.shape, y_data.shape) @condition.retry(3) def test_forward_cpu(self): self.check_forward(self.x, self.rois) @attr.gpu @condition.retry(3) def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois)) @attr.gpu @condition.retry(3) def test_forward_cpu_gpu_equal(self): # cpu x_cpu = chainer.Variable(self.x) rois_cpu = chainer.Variable(self.rois) y_cpu = functions.roi_pooling_2d( x_cpu, rois_cpu, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) # gpu x_gpu = chainer.Variable(cuda.to_gpu(self.x)) rois_gpu = chainer.Variable(cuda.to_gpu(self.rois)) y_gpu = functions.roi_pooling_2d( x_gpu, rois_gpu, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) gradient_check.assert_allclose(y_cpu.data, cuda.to_cpu(y_gpu.data)) def check_backward(self, x_data, roi_data, y_grad): x = chainer.Variable(x_data) rois = chainer.Variable(roi_data) y = functions.roi_pooling_2d(x, rois, outh=self.outh, outw=self.outw, spatial_scale=self.spatial_scale) y.grad = y_grad y.backward() xs = (x.data, rois.data) def f(): func = y.creator return func.forward(xs) gx, _ = gradient_check.numerical_grad(f, xs, (y.grad,)) gradient_check.assert_allclose(cuda.to_cpu(gx), cuda.to_cpu(x.grad)) @condition.retry(3) def test_backward_cpu(self): self.check_backward(self.x, self.rois, self.gy) @attr.gpu @condition.retry(3) def test_backward_gpu(self): self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois), cuda.to_gpu(self.gy)) testing.run_module(__name__, __file__)
Python
0.000003
d6c1774b75839192b0235e5737cdba0d17759fde
Update mqtt_easydriver_stepper.py
linkit/easydriver/mqtt_easydriver_stepper.py
linkit/easydriver/mqtt_easydriver_stepper.py
import paho.mqtt.client as mqtt import json, time import mraa pin19 = mraa.Pwm(19) pin0 = mraa.Gpio(0) pin0.dir(mraa.DIR_OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 #--------------------------------------- def on_connect(client, userdata, rc): print("\nConnected with result code " + str(rc) + "\n") client.subscribe("/pryxo/yxusers/motor/control/") print("Subscribed to homecontrol") def on_message_iotrl(client, userdata, msg): print("\n\t* Linkit UPDATED ("+msg.topic+"): " + str(msg.payload)) if msg.payload == "m1": pin0.write(0) pin1 = mraa.Gpio(1) pin1.dir(mraa.DIR_OUT) pin1.write(0) pin19.period_us(300) pin19.enable(True) pin19.write(0.1) time.sleep(2) client.publish("/pryxo/yxusers/iot/status/", "derecha", 2) if msg.payload == "m0": pin0.write(0) pin1 = mraa.Gpio(1) pin1.dir(mraa.DIR_OUT) pin1.write(1) pin19.period_us(300) pin19.enable(True) pin19.write(0.1) time.sleep(2) client.publish("/pryxo/yxusers/iot/status/", "izquierda", 2) if msg.payload == "m2": pin0.write(1) client.publish("/pryxo/yxusers/iot/status/", "STOP", 2) def command_error(): print("Error: Unknown command") client = mqtt.Client(client_id="linkit7688-stepper-motor") client.on_connect = on_connect client.message_callback_add("/pryxo/yxusers/motor/control/", on_message_iotrl) client.connect(MQTT_HOST, MQTT_PORT, 60) client.loop_start() # Main program loop while True: time.sleep(10)
import paho.mqtt.client as mqtt import json, time import mraa pin19 = mraa.Pwm(19) pin0 = mraa.Gpio(0) pin0.dir(mraa.DIR_OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 def on_connect(client, userdata, rc): print("\nConnected with result code " + str(rc) + "\n") #Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("/pyxo/xyusers/{USERNAME}/{APIKEY}/iot/control/".format(**vars()), 2) # Connect to everything in /mcu topic client.subscribe("/pryxo/yxusers/motor/control/") print("Subscribed to homecontrol") def on_message_iotrl(client, userdata, msg): print("\n\t* Linkit UPDATED ("+msg.topic+"): " + str(msg.payload)) if msg.payload == "m1": pin0.write(0) pin1 = mraa.Gpio(1) pin1.dir(mraa.DIR_OUT) pin1.write(0) pin19.period_us(300) pin19.enable(True) pin19.write(0.1) time.sleep(2) client.publish("/pryxo/yxusers/iot/status/", "derecha", 2) if msg.payload == "m0": pin1 = mraa.Gpio(1) pin1.dir(mraa.DIR_OUT) pin1.write(1) pin19.period_us(300) pin19.enable(True) pin19.write(0.1) time.sleep(2) client.publish("/pryxo/yxusers/iot/status/", "izquierda", 2) if msg.payload == "m2": pin0.write(1) client.publish("/pryxo/yxusers/iot/status/", "STOP", 2) def command_error(): print("Error: Unknown command") client = mqtt.Client(client_id="linkit7688-stepper-motor") # Callback declarations (functions run based on certain messages) client.on_connect = on_connect client.message_callback_add("/pryxo/yxusers/motor/control/", on_message_iotrl) # This is where the MQTT service connects and starts listening for messages client.connect(MQTT_HOST, MQTT_PORT, 60) client.loop_start() # Background thread to call loop() automatically # Main program loop while True: time.sleep(10)
Python
0
6b7bd1c412b21a748b39a07a792f8b2c8461f9e2
Fix issue #17
marmoset/installimage/installimage_config.py
marmoset/installimage/installimage_config.py
import os class InstallimageConfig: CFG_DIR = '/srv/tftp/installimage/' def __init__(self, mac): self.variables = {} self.mac = mac if self.exists(): self.__read_config_file() def add_or_set(self, key, value): self.variables[key.upper()] = value def create(self): self.__write_config_file() def exists(self): return os.path.isfile(self.file_path()) def file_name(self): '''Return the file name in the Installimage file name style.''' return self.mac.replace(":", "_") def file_path(self, name=None): '''Return the path to the config file of th instance.''' if name is None: name = self.file_name() cfgdir = InstallimageConfig.CFG_DIR.rstrip('/') return os.path.join(cfgdir, name) def __read_config_file(self, path=None): if path is None: path = self.file_path() lines = [] with open(path, 'r') as f: lines = f.readlines() f.close() for line in lines: key = line.split(" ")[0] value = line.split(" ", 1)[1] self.variables[key] = value def __write_config_file(self, path=None): if path is None: path = self.file_path() variable_lines = [] for key in self.variables: variable_lines.append("%s %s" % (key, self.variables[key])) content = "\n".join(variable_lines) os.makedirs(InstallimageConfig.CFG_DIR, exist_ok=True) with open(path, 'w') as f: f.write(content) f.close()
import os class InstallimageConfig: CFG_DIR = '/srv/tftp/installimage/' def __init__(self, mac): self.variables = {} self.mac = mac if self.exists(): self.__read_config_file() def add_or_set(self, key, value): self.variables[key] = value def create(self): self.__write_config_file() def exists(self): return os.path.isfile(self.file_path()) def file_name(self): '''Return the file name in the Installimage file name style.''' return self.mac.replace(":", "_") def file_path(self, name=None): '''Return the path to the config file of th instance.''' if name is None: name = self.file_name() cfgdir = InstallimageConfig.CFG_DIR.rstrip('/') return os.path.join(cfgdir, name) def __read_config_file(self, path=None): if path is None: path = self.file_path() lines = [] with open(path, 'r') as f: lines = f.readlines() f.close() for line in lines: key = line.split(" ")[0] value = line.split(" ", 1)[1] self.variables[key] = value def __write_config_file(self, path=None): if path is None: path = self.file_path() variable_lines = [] for key in self.variables: variable_lines.append("%s %s" % (key.upper(), self.variables[key])) content = "\n".join(variable_lines) os.makedirs(InstallimageConfig.CFG_DIR, exist_ok=True) with open(path, 'w') as f: f.write(content) f.close()
Python
0
74cfb1bd8e60e1d348115677e92c5e64858ec785
Add clearer instructions on no component support. (#2685)
packaged_releases/patches/patch_component_custom.py
packaged_releases/patches/patch_component_custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.core._util import CLIError MSG_TMPL = """ az component and subcommands are not available with the current Azure CLI installation. If installed with apt-get, please use 'apt-get update' to update this installation. If installed with Docker, please use 'docker pull' to update this installation. If installed with Windows MSI, download the new MSI to update this installation. {} """ def _raise_error(msg): raise CLIError(MSG_TMPL.format(msg)) def list_components(): """ List the installed components """ _raise_error("Use 'az --version' to list component versions.") def list_available_components(): """ List publicly available components that can be installed """ _raise_error("No additional components available.") def remove(component_name): """ Remove a component """ _raise_error("Components cannot be removed.") def update(private=False, pre=False, link=None, additional_components=None, allow_third_party=False): """ Update the CLI and all installed components """ _raise_error("Components cannot be updated.")
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.core._util import CLIError MSG_TMPL = """ az component and subcommands are not available with the current Azure CLI installation. If installed with apt-get, please use apt-get to update this installation. {} """ def _raise_error(msg): raise CLIError(MSG_TMPL.format(msg)) def list_components(): """ List the installed components """ _raise_error("Use 'az --version' to list component versions.") def list_available_components(): """ List publicly available components that can be installed """ _raise_error("No additional components available.") def remove(component_name): """ Remove a component """ _raise_error("Components cannot be removed.") def update(private=False, pre=False, link=None, additional_components=None, allow_third_party=False): """ Update the CLI and all installed components """ _raise_error("Components cannot be updated.")
Python
0.000552
c5a31be1bd452224c2b35c4f3e3132b2df1431e7
reorder imports
meinberlin/apps/documents/exports.py
meinberlin/apps/documents/exports.py
from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from adhocracy4.comments.models import Comment from adhocracy4.exports import mixins as export_mixins from adhocracy4.exports import views as export_views from meinberlin.apps.exports import mixins as mb_export_mixins from meinberlin.apps.exports import register_export @register_export(_('Documents with comments')) class DocumentExportView( export_mixins.ExportModelFieldsMixin, mb_export_mixins.UserGeneratedContentExportMixin, export_mixins.ItemExportWithLinkMixin, export_mixins.ItemExportWithRatesMixin, mb_export_mixins.ItemExportWithRepliesToMixin, export_views.BaseItemExportView ): model = Comment fields = ['id', 'comment', 'created'] def get_queryset(self): comments = ( Comment.objects.filter(paragraph__chapter__module=self.module) | Comment.objects.filter(chapter__module=self.module) | Comment.objects.filter( parent_comment__paragraph__chapter__module=self.module) | Comment.objects.filter(parent_comment__chapter__module=self.module) ) return comments def get_base_filename(self): return '%s_%s' % (self.project.slug, timezone.now().strftime('%Y%m%dT%H%M%S'))
from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from adhocracy4.comments.models import Comment from adhocracy4.exports import mixins as export_mixins from adhocracy4.exports import views as export_views from adhocracy4.projects.mixins import ProjectMixin from meinberlin.apps.exports import mixins as mb_export_mixins from meinberlin.apps.exports import register_export @register_export(_('Documents with comments')) class DocumentExportView( export_views.BaseItemExportView, export_mixins.ExportModelFieldsMixin, mb_export_mixins.UserGeneratedContentExportMixin, export_mixins.ItemExportWithLinkMixin, export_mixins.ItemExportWithRatesMixin, mb_export_mixins.ItemExportWithRepliesToMixin, ProjectMixin): model = Comment fields = ['id', 'comment', 'created'] def get_queryset(self): comments = ( Comment.objects.filter(paragraph__chapter__module=self.module) | Comment.objects.filter(chapter__module=self.module) | Comment.objects.filter( parent_comment__paragraph__chapter__module=self.module) | Comment.objects.filter(parent_comment__chapter__module=self.module) ) return comments def get_base_filename(self): return '%s_%s' % (self.project.slug, timezone.now().strftime('%Y%m%dT%H%M%S'))
Python
0.000009
1c6c31653889c8acb60a54dc1dc9ea0f8795f122
bump to next dev version: 0.6.7-dev
ulmo/version.py
ulmo/version.py
# set version number __version__ = '0.6.7-dev'
# set version number __version__ = '0.6.6'
Python
0
8546e14e152c79f137e0db15e3cd7de71cd0e8b4
bump to next dev version: 0.7.3-dev
ulmo/version.py
ulmo/version.py
# set version number __version__ = '0.7.3-dev'
# set version number __version__ = '0.7.2'
Python
0
a8b43950610adb41a3de4c342c51d5b22fd5454b
Fix indents
saleor/product/forms.py
saleor/product/forms.py
import json from django import forms from django.utils.encoding import smart_text from django.utils.translation import pgettext_lazy from django_prices.templatetags.prices_i18n import gross from ..cart.forms import AddToCartForm class VariantChoiceField(forms.ModelChoiceField): discounts = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def label_from_instance(self, obj): variant_label = smart_text(obj) label = pgettext_lazy( 'Variant choice field label', '%(variant_label)s - %(price)s') % { 'variant_label': variant_label, 'price': gross(obj.get_price(discounts=self.discounts))} return label def update_field_data(self, product, cart): """ Function initializing fields custom data """ self.queryset = product.variants self.discounts = cart.discounts self.empty_label = None images_map = {variant.pk: [vi.image.image.url for vi in variant.variant_images.all()] for variant in product.variants.all()} self.widget.attrs['data-images'] = json.dumps(images_map) # Don't display select input if there are less than two variants if self.queryset.count() < 2: self.widget = forms.HiddenInput( {'value': product.variants.all()[0].pk}) class ProductForm(AddToCartForm): variant = VariantChoiceField(queryset=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) variant_field = self.fields['variant'] variant_field.update_field_data(self.product, self.cart) def get_variant(self, cleaned_data): return cleaned_data.get('variant')
import json from django import forms from django.utils.encoding import smart_text from django.utils.translation import pgettext_lazy from django_prices.templatetags.prices_i18n import gross from ..cart.forms import AddToCartForm class VariantChoiceField(forms.ModelChoiceField): discounts = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def label_from_instance(self, obj): variant_label = smart_text(obj) label = pgettext_lazy( 'Variant choice field label', '%(variant_label)s - %(price)s') % { 'variant_label': variant_label, 'price': gross(obj.get_price(discounts=self.discounts))} return label def update_field_data(self, product, cart): """ Function initializing fields custom data """ self.queryset = product.variants self.discounts = cart.discounts self.empty_label = None images_map = {variant.pk: [vi.image.image.url for vi in variant.variant_images.all()] for variant in product.variants.all()} self.widget.attrs['data-images'] = json.dumps(images_map) # Don't display select input if there are less than two variants if self.queryset.count() < 2: self.widget = forms.HiddenInput( {'value': product.variants.all()[0].pk}) class ProductForm(AddToCartForm): variant = VariantChoiceField(queryset=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) variant_field = self.fields['variant'] variant_field.update_field_data(self.product, self.cart) def get_variant(self, cleaned_data): return cleaned_data.get('variant')
Python
0.000034
833f8ce0673701eb64fb20ee067ccd8c58e473c6
Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
child_sync_typo3/wizard/child_depart_wizard.py
child_sync_typo3/wizard/child_depart_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class child_depart_wizard(orm.TransientModel): _inherit = 'child.depart.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(child_depart_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class end_sponsorship_wizard(orm.TransientModel): _inherit = 'end.sponsorship.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(end_sponsorship_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
Python
0
97c5cb0312d7b093752376a373cc3773fcf44f34
Add SunOS to the basic service module
salt/modules/service.py
salt/modules/service.py
''' The default service module, if not otherwise specified salt will fall back to this basic module ''' import os grainmap = { 'Arch': '/etc/rc.d', 'Debian': '/etc/init.d', 'Fedora': '/etc/init.d', 'RedHat': '/etc/init.d', 'Ubuntu': '/etc/init.d', 'Gentoo': '/etc/init.d', 'CentOS': '/etc/init.d', 'SunOS': '/etc/init.d', } def __virtual__(): ''' Only work on systems which default to systemd ''' # Disable on these platforms, specific service modules exist: disable = [ 'RedHat', 'CentOS', 'Scientific', 'Fedora', 'Gentoo', 'Ubuntu', 'FreeBSD', 'Windows', ] if __grains__['os'] in disable: return False return 'service' def start(name): ''' Start the specified service CLI Example:: salt '*' service.start <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example:: salt '*' service.stop <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example:: salt '*' service.restart <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' restart') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service, returns the PID or an empty string if the service is running or not, pass a signature to use to find the service via ps CLI Example:: salt '*' service.status <service name> [service signature] ''' sig = name if not sig else sig cmd = "{0[ps]} | grep {1} | grep -v grep | awk '{{print $2}}'".format( __grains__, sig) return __salt__['cmd.run'](cmd).strip()
''' The default service module, if not otherwise specified salt will fall back to this basic module ''' import os grainmap = { 'Arch': '/etc/rc.d', 'Debian': '/etc/init.d', 'Fedora': '/etc/init.d', 'RedHat': '/etc/init.d', 'Ubuntu': '/etc/init.d', 'Gentoo': '/etc/init.d', 'CentOS': '/etc/init.d', } def __virtual__(): ''' Only work on systems which default to systemd ''' # Disable on these platforms, specific service modules exist: disable = [ 'RedHat', 'CentOS', 'Scientific', 'Fedora', 'Gentoo', 'Ubuntu', 'FreeBSD', 'Windows', ] if __grains__['os'] in disable: return False return 'service' def start(name): ''' Start the specified service CLI Example:: salt '*' service.start <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' start') return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stop the specified service CLI Example:: salt '*' service.stop <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' stop') return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart the named service CLI Example:: salt '*' service.restart <service name> ''' cmd = os.path.join(grainmap[__grains__['os']], name + ' restart') return not __salt__['cmd.retcode'](cmd) def status(name, sig=None): ''' Return the status for a service, returns the PID or an empty string if the service is running or not, pass a signature to use to find the service via ps CLI Example:: salt '*' service.status <service name> [service signature] ''' sig = name if not sig else sig cmd = "{0[ps]} | grep {1} | grep -v grep | awk '{{print $2}}'".format( __grains__, sig) return __salt__['cmd.run'](cmd).strip()
Python
0
6ddb38eee5624ea8753e52cfde4b8d17c0ac2b14
Making salt.output.json_out python3 compatible
salt/output/json_out.py
salt/output/json_out.py
# -*- coding: utf-8 -*- ''' Display return data in JSON format ================================== :configuration: The output format can be configured in two ways: Using the ``--out-indent`` CLI flag and specifying a positive integer or a negative integer to group JSON from each minion to a single line. Or setting the ``output_indent`` setting in the Master or Minion configuration file with one of the following values: * ``Null``: put each minion return on a single line. * ``pretty``: use four-space indents and sort the keys. * An integer: specify the indentation level. Salt's outputters operate on a per-minion basis. Each minion return will be output as a single JSON object once it comes in to the master. Some JSON parsers can guess when an object ends and a new one begins but many can not. A good way to differentiate between each minion return is to use the single-line output format and to parse each line individually. Example output (truncated):: {"dave": {"en0": {"hwaddr": "02:b0:26:32:4c:69", ...}}} {"jerry": {"en0": {"hwaddr": "02:26:ab:0d:b9:0d", ...}}} {"kevin": {"en0": {"hwaddr": "02:6d:7f:ce:9f:ee", ...}}} {"mike": {"en0": {"hwaddr": "02:48:a2:4b:70:a0", ...}}} {"phill": {"en0": {"hwaddr": "02:1d:cc:a2:33:55", ...}}} {"stuart": {"en0": {"hwaddr": "02:9a:e0:ea:9e:3c", ...}}} ''' from __future__ import absolute_import # Import python libs import json import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'json' def __virtual__(): ''' Rename to json ''' return __virtualname__ def output(data): ''' Print the output data in JSON ''' try: if 'output_indent' not in __opts__: return json.dumps(data, default=repr, indent=4) indent = __opts__.get('output_indent') sort_keys = False if indent is None: indent = None elif indent == 'pretty': indent = 4 sort_keys = True elif isinstance(indent, int): if indent >= 0: indent = indent else: indent = None return json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys) except TypeError: log.debug('An error occurred while outputting JSON', exc_info=True) # Return valid JSON for unserializable objects return json.dumps({})
# -*- coding: utf-8 -*- ''' Display return data in JSON format ================================== :configuration: The output format can be configured in two ways: Using the ``--out-indent`` CLI flag and specifying a positive integer or a negative integer to group JSON from each minion to a single line. Or setting the ``output_indent`` setting in the Master or Minion configuration file with one of the following values: * ``Null``: put each minion return on a single line. * ``pretty``: use four-space indents and sort the keys. * An integer: specify the indentation level. Salt's outputters operate on a per-minion basis. Each minion return will be output as a single JSON object once it comes in to the master. Some JSON parsers can guess when an object ends and a new one begins but many can not. A good way to differentiate between each minion return is to use the single-line output format and to parse each line individually. Example output (truncated):: {"dave": {"en0": {"hwaddr": "02:b0:26:32:4c:69", ...}}} {"jerry": {"en0": {"hwaddr": "02:26:ab:0d:b9:0d", ...}}} {"kevin": {"en0": {"hwaddr": "02:6d:7f:ce:9f:ee", ...}}} {"mike": {"en0": {"hwaddr": "02:48:a2:4b:70:a0", ...}}} {"phill": {"en0": {"hwaddr": "02:1d:cc:a2:33:55", ...}}} {"stuart": {"en0": {"hwaddr": "02:9a:e0:ea:9e:3c", ...}}} ''' # Import python libs import json import logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'json' def __virtual__(): ''' Rename to json ''' return __virtualname__ def output(data): ''' Print the output data in JSON ''' try: if 'output_indent' not in __opts__: return json.dumps(data, default=repr, indent=4) indent = __opts__.get('output_indent') sort_keys = False if indent is None: indent = None elif indent == 'pretty': indent = 4 sort_keys = True elif isinstance(indent, int): if indent >= 0: indent = indent else: indent = None return json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys) except TypeError: log.debug('An error occurred while outputting JSON', exc_info=True) # Return valid JSON for unserializable objects return json.dumps({})
Python
0.998869
f422535179d9f55e28d5c1b0e098e0a4931d366b
Making salt.pillar.cmd_json python3 compatible
salt/pillar/cmd_json.py
salt/pillar/cmd_json.py
# -*- coding: utf-8 -*- ''' Execute a command and read the output as JSON. The JSON data is then directly overlaid onto the minion's Pillar data. ''' from __future__ import absolute_import # Don't "fix" the above docstring to put it on two lines, as the sphinx # autosummary pulls only the first line for its description. # Import python libs import logging import json # Set up logging log = logging.getLogger(__name__) def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as JSON ''' try: return json.loads(__salt__['cmd.run'](command)) except Exception: log.critical( 'JSON data from {0} failed to parse'.format(command) ) return {}
# -*- coding: utf-8 -*- ''' Execute a command and read the output as JSON. The JSON data is then directly overlaid onto the minion's Pillar data. ''' # Don't "fix" the above docstring to put it on two lines, as the sphinx # autosummary pulls only the first line for its description. # Import python libs import logging import json # Set up logging log = logging.getLogger(__name__) def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as JSON ''' try: return json.loads(__salt__['cmd.run'](command)) except Exception: log.critical( 'JSON data from {0} failed to parse'.format(command) ) return {}
Python
0.998816
e40a9b3676101d7d7bd65cff8487f48a285f3139
Fix typo
scripts/obtain_user_auth.py
scripts/obtain_user_auth.py
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This program obtains a set of user credentials. These credentials are needed to run the system test for OAuth2 credentials. It's expected that a developer will run this program manually once to obtain a refresh token. It's highly recommended to use a Google account created specifically for testing. """ import json import os from oauth2client import client from oauth2client import tools HERE = os.path.dirname(__file__) CLIENT_SECRETS_PATH = os.path.abspath(os.path.join( HERE, '..', 'system_tests', 'data', 'client_secret.json')) AUTHORIZED_USER_PATH = os.path.abspath(os.path.join( HERE, '..', 'system_tests', 'data', 'authorized_user.json')) SCOPES = ['email', 'profile'] class NullStorage(client.Storage): """Null storage implementation to prevent oauth2client from failing on storage.put.""" def locked_put(self, credentials): pass def main(): flow = client.flow_from_clientsecrets(CLIENT_SECRETS_PATH, SCOPES) print('Starting credentials flow...') credentials = tools.run_flow(flow, NullStorage()) # Save the credentials in the same format as the Cloud SDK's authorized # user file. data = { 'type': 'authorized_user', 'client_id': flow.client_id, 'client_secret': flow.client_secret, 'refresh_token': credentials.refresh_token } with open(AUTHORIZED_USER_PATH, 'w') as fh: json.dump(data, fh, indent=4) print('Created {}.'.format(AUTHORIZED_USER_PATH)) if __name__ == '__main__': main()
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This program obtains a set of user credentials. These credentials are needed to run the system test for OAuth2 credentials. It's expected that a developer will run this program manually once to obtain a refresh token. It's highly recommended to use a Google account created specifically created for testing. """ import json import os from oauth2client import client from oauth2client import tools HERE = os.path.dirname(__file__) CLIENT_SECRETS_PATH = os.path.abspath(os.path.join( HERE, '..', 'system_tests', 'data', 'client_secret.json')) AUTHORIZED_USER_PATH = os.path.abspath(os.path.join( HERE, '..', 'system_tests', 'data', 'authorized_user.json')) SCOPES = ['email', 'profile'] class NullStorage(client.Storage): """Null storage implementation to prevent oauth2client from failing on storage.put.""" def locked_put(self, credentials): pass def main(): flow = client.flow_from_clientsecrets(CLIENT_SECRETS_PATH, SCOPES) print('Starting credentials flow...') credentials = tools.run_flow(flow, NullStorage()) # Save the credentials in the same format as the Cloud SDK's authorized # user file. data = { 'type': 'authorized_user', 'client_id': flow.client_id, 'client_secret': flow.client_secret, 'refresh_token': credentials.refresh_token } with open(AUTHORIZED_USER_PATH, 'w') as fh: json.dump(data, fh, indent=4) print('Created {}.'.format(AUTHORIZED_USER_PATH)) if __name__ == '__main__': main()
Python
0.999999
f1e1513cf739b8f25b9364226cc8ce987a47fa56
Fix check for helpers with staff perms
utils/checks.py
utils/checks.py
import discord from discord import app_commands from discord.ext import commands from utils.configuration import StaffRank from typing import Union, TYPE_CHECKING if TYPE_CHECKING: from kurisu import Kurisu class InsufficientStaffRank(commands.CheckFailure): message: str def is_staff(role: str): async def predicate(ctx: commands.Context): if check_staff(ctx.bot, role, ctx.author.id) or (ctx.guild and ctx.author == ctx.guild.owner): return True raise InsufficientStaffRank(f"You must be at least {role} to use this command.") return commands.check(predicate) def is_staff_app(role: str): async def predicate(interaction: discord.Interaction) -> bool: if (interaction.guild and interaction.user == interaction.guild.owner) or check_staff(interaction.client, role, interaction.user.id): # type: ignore return True raise InsufficientStaffRank(f"You must be at least {role} to use this command.") return app_commands.check(predicate) def check_staff(bot: 'Kurisu', role: str, user_id: int) -> bool: position = bot.configuration.staff.get(user_id) if not position and bot.configuration.helpers.get(user_id): position = StaffRank.Helper if position is None: return False return position <= StaffRank[role] async def check_bot_or_staff(ctx: Union[commands.Context, discord.Interaction], target: Union[discord.Member, discord.User], action: str): bot = ctx.bot if isinstance(ctx, commands.Context) else ctx.client if target.bot: who = "a bot" elif check_staff(bot, "Helper", target.id): who = "another staffer" else: return False if isinstance(ctx, commands.Context): await ctx.send(f"You can't {action} {who} with this command!") else: await ctx.response.send_message(f"You can't {action} {who} with this command!", ephemeral=True) return True def check_if_user_can_sr(): async def predicate(ctx): author = ctx.author if not check_staff(ctx.bot, 'Helper', author.id) and (ctx.bot.roles['Verified'] not in author.roles) and ( ctx.bot.roles['Trusted'] not in author.roles) and (ctx.bot.roles['Retired Staff'] not in author.roles): return False return True return commands.check(predicate) def check_if_user_can_ready(): async def predicate(ctx): channel = ctx.channel if channel != ctx.bot.channels['newcomers']: return False return True return commands.check(predicate)
import discord from discord import app_commands from discord.ext import commands from utils.configuration import StaffRank from typing import Union, TYPE_CHECKING if TYPE_CHECKING: from kurisu import Kurisu class InsufficientStaffRank(commands.CheckFailure): message: str def is_staff(role: str): async def predicate(ctx: commands.Context): if check_staff(ctx.bot, role, ctx.author.id) or (ctx.guild and ctx.author == ctx.guild.owner): return True raise InsufficientStaffRank(f"You must be at least {role} to use this command.") return commands.check(predicate) def is_staff_app(role: str): async def predicate(interaction: discord.Interaction) -> bool: if (interaction.guild and interaction.user == interaction.guild.owner) or check_staff(interaction.client, role, interaction.user.id): # type: ignore return True raise InsufficientStaffRank(f"You must be at least {role} to use this command.") return app_commands.check(predicate) def check_staff(bot: 'Kurisu', role: str, user_id: int) -> bool: if bot.configuration.helpers.get(user_id): position = StaffRank.Helper else: position = bot.configuration.staff.get(user_id) if position is None: return False return position <= StaffRank[role] async def check_bot_or_staff(ctx: Union[commands.Context, discord.Interaction], target: Union[discord.Member, discord.User], action: str): bot = ctx.bot if isinstance(ctx, commands.Context) else ctx.client if target.bot: who = "a bot" elif check_staff(bot, "Helper", target.id): who = "another staffer" else: return False if isinstance(ctx, commands.Context): await ctx.send(f"You can't {action} {who} with this command!") else: await ctx.response.send_message(f"You can't {action} {who} with this command!", ephemeral=True) return True def check_if_user_can_sr(): async def predicate(ctx): author = ctx.author if not check_staff(ctx.bot, 'Helper', author.id) and (ctx.bot.roles['Verified'] not in author.roles) and ( ctx.bot.roles['Trusted'] not in author.roles) and (ctx.bot.roles['Retired Staff'] not in author.roles): return False return True return commands.check(predicate) def check_if_user_can_ready(): async def predicate(ctx): channel = ctx.channel if channel != ctx.bot.channels['newcomers']: return False return True return commands.check(predicate)
Python
0
2031c415144fe7c616fb1b020c9571ced5726654
Handle yanked Projects, Versions, and Files
warehouse/synchronize/commands.py
warehouse/synchronize/commands.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import eventlet from progress.bar import ShadyBar from warehouse import create_app, db, script from warehouse.packages import store from warehouse.packages.models import Project, Version, File from warehouse.synchronize.fetchers import PyPIFetcher eventlet.monkey_patch() class DummyBar(object): def iter(self, iterable): for x in iterable: yield x def synchronize_project(app, project, fetcher, force=False): with app.test_request_context(): project = store.project(project) versions = fetcher.versions(project.name) for v in versions: version = store.version(project, fetcher.release(project.name, v)) distributions = fetcher.distributions(project.name, version.version) for dist in distributions: distribution = store.distribution(project, version, dist) # Check if the stored hash matches what the fetcher says if (force or distribution.hashes is None or dist["md5_digest"] != distribution.hashes.get("md5")): # The fetcher has a different file store.distribution_file(project, version, distribution, fetcher.file(dist["url"])) # Get a list of filesnames filenames = [x["filename"] for x in distributions] # Find what files no longer exist in PyPI to yank them if filenames: # If there any files we use IN files_to_yank = File.query.filter( File.version == version, ~File.filename.in_(filenames), ) else: # If there are no filenames we can do a simpler query files_to_yank = File.query.filter(File.version == version) # Actually preform the yanking files_to_yank.update({"yanked": False}, synchronize_session=False) # Find what versions no longer exist in PyPI to yank them if versions: # If there are any versions we use IN versions_to_yank = Version.query.filter( Version.project == project, ~Version.version.in_(versions), ) else: # If there are no versions we can do a simpler query versions_to_yank = Version.query.filter(Version.project == project) # Actually preform the yanking versions_to_yank.update({"yanked": True}, synchronize_session=False) # Commit our changes db.session.commit() def syncer(projects=None, fetcher=None, pool=None, progress=True, force=False): if pool is None: pool = eventlet.GreenPool(10) if fetcher is None: fetcher = PyPIFetcher() # Sync the Classifiers for classifier in fetcher.classifiers(): store.classifier(classifier) # Commit the classifiers db.session.commit() # Sync the Projects/Versions/Files if not projects: # TODO(dstufft): Determine how to make this do the "since last sync" projects = fetcher.projects() if progress: bar = ShadyBar("Synchronizing", max=len(projects)) else: bar = DummyBar() app = create_app() with app.app_context(): for project in bar.iter(projects): pool.spawn_n(synchronize_project, app, project, fetcher, force) # Yank no longer existing projects (and versions and files) Project.query.filter( ~Project.name.in_(projects) ).update({"yanked": True}, synchronize_session=False) # Commit the deletion db.session.commit() @script.option("--force-download", action="store_true", dest="force") @script.option("--concurrency", dest="concurrency", type=int, default=10) @script.option("--no-progress", action="store_false", dest="progress") @script.option("projects", nargs="*", metavar="project") def synchronize(projects=None, concurrency=10, progress=True, force=False): # This is a hack to normalize the incoming projects to unicode projects = [x.decode("utf-8") for x in projects] # Create the Pool that Synchronization will use pool = eventlet.GreenPool(concurrency) # Run the actual Synchronization syncer(projects, pool=pool, progress=progress, force=force)
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import eventlet from progress.bar import ShadyBar from warehouse import create_app, db, script from warehouse.packages import store from warehouse.synchronize.fetchers import PyPIFetcher eventlet.monkey_patch() class DummyBar(object): def iter(self, iterable): for x in iterable: yield x def synchronize_project(app, project, fetcher, force=False): with app.test_request_context(): project = store.project(project) versions = fetcher.versions(project.name) for v in versions: version = store.version(project, fetcher.release(project.name, v)) distributions = fetcher.distributions(project.name, version.version) for dist in distributions: distribution = store.distribution(project, version, dist) # Check if the stored hash matches what the fetcher says if (force or distribution.hashes is None or dist["md5_digest"] != distribution.hashes.get("md5")): # The fetcher has a different file store.distribution_file(project, version, distribution, fetcher.file(dist["url"])) # Commit our changes db.session.commit() def syncer(projects=None, fetcher=None, pool=None, progress=True, force=False): if pool is None: pool = eventlet.GreenPool(10) if fetcher is None: fetcher = PyPIFetcher() # Sync the Classifiers for classifier in fetcher.classifiers(): store.classifier(classifier) # Commit the classifiers db.session.commit() # Sync the Projects/Versions/Files if not projects: # TODO(dstufft): Determine how to make this do the "since last sync" projects = fetcher.projects() if progress: bar = ShadyBar("Synchronizing", max=len(projects)) else: bar = DummyBar() app = create_app() with app.app_context(): for project in bar.iter(projects): pool.spawn_n(synchronize_project, app, project, fetcher, force) @script.option("--force-download", action="store_true", dest="force") @script.option("--concurrency", dest="concurrency", type=int, default=10) @script.option("--no-progress", action="store_false", dest="progress") @script.option("projects", nargs="*", metavar="project") def synchronize(projects=None, concurrency=10, progress=True, force=False): # This is a hack to normalize the incoming projects to unicode projects = [x.decode("utf-8") for x in projects] # Create the Pool that Synchronization will use pool = eventlet.GreenPool(concurrency) # Run the actual Synchronization syncer(projects, pool=pool, progress=progress, force=force)
Python
0
6cba22ad2c26185f6b3454116c3e31ea14160db8
Make collect-sprite-metadata.py work from any directory
scripts/collect-sprite-metadata.py
scripts/collect-sprite-metadata.py
from collections import OrderedDict import glob import json import os def main(): c = collect() c.sort(key = lambda x: x[0]) c = OrderedDict(c) print(json.dumps(c, separators=(',',':'))) def collect(): root = os.path.dirname(os.path.abspath(__file__)) + '/../build/website/assets/sprites' hitboxes = [] for (dirpath, dirnames, filenames) in os.walk(root): for fn in glob.glob(dirpath + '/*.json'): metadata = json.load(open(fn)) name = os.path.relpath(fn, root).replace('\\', '/')[:-5] hitboxes.append((name, metadata['hitbox'])) return hitboxes if __name__ == '__main__': main()
from collections import OrderedDict import glob import json import os def main(): c = collect() c.sort(key = lambda x: x[0]) c = OrderedDict(c) print(json.dumps(c, separators=(',',':'))) def collect(): root = '../build/website/static/sprites' hitboxes = [] for (dirpath, dirnames, filenames) in os.walk(root): for fn in glob.glob(dirpath + '/*.json'): metadata = json.load(open(fn)) name = os.path.relpath(fn, root).replace('\\', '/')[:-5] hitboxes.append((name, metadata['hitbox'])) return hitboxes if __name__ == '__main__': main()
Python
0.000007
2192219d92713c6eb76593d0c6c29413d040db6a
Revert "Added script for cron job to load surveys to database."
scripts/cronRefreshEdxQualtrics.py
scripts/cronRefreshEdxQualtrics.py
from surveyextractor import QualtricsExtractor import getopt, sys # Script for scheduling regular EdxQualtrics updates # Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r" qe = QualtricsExtractor() opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses']) for opt, arg in opts: if opt in ('-a', '--reset'): qe.resetMetadata() qe.resetSurveys() qe.resetResponses() elif opt in ('-m', '--loadmeta'): qe.loadSurveyMetadata() elif opt in ('-s', '--loadsurvey'): qe.resetSurveys() qe.loadSurveyData() elif opt in ('-r', '--loadresponses'): qe.loadResponseData()
from surveyextractor import QualtricsExtractor import getopt import sys ### Script for scheduling regular EdxQualtrics updates ### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r" # Append directory for dependencies to PYTHONPATH sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/") qe = QualtricsExtractor() opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses']) for opt, arg in opts: if opt in ('-a', '--reset'): qe.resetMetadata() qe.resetSurveys() qe.resetResponses() elif opt in ('-m', '--loadmeta'): qe.loadSurveyMetadata() elif opt in ('-s', '--loadsurvey'): qe.resetSurveys() qe.loadSurveyData() elif opt in ('-r', '--loadresponses'): qe.loadResponseData()
Python
0
98311b8b80d28ac6e6d92dbae3bcf987d5027e7a
Fix for housekeeping script error
photonix/photos/management/commands/housekeeping.py
photonix/photos/management/commands/housekeeping.py
import os from pathlib import Path from shutil import rmtree from time import sleep from django.conf import settings from django.core.management.base import BaseCommand from photonix.photos.models import Photo, Task from photonix.photos.utils.thumbnails import THUMBNAILER_VERSION class Command(BaseCommand): help = 'Makes sure that if there have been upgrades to thumbnailing or image analysis code then jobs get rescheduled.' def housekeeping(self): # Remove old cache directories try: for directory in os.listdir(settings.THUMBNAIL_ROOT): if directory not in ['photofile']: path = Path(settings.THUMBNAIL_ROOT) / directory print(f'Removing old cache directory {path}') rmtree(path) except FileNotFoundError: # In case thumbnail dir hasn't been created yet pass # Regenerate any outdated thumbnails photos = Photo.objects.filter(thumbnailed_version__lt=THUMBNAILER_VERSION) if photos.count(): print(f'Rescheduling {photos.count()} photos to have their thumbnails regenerated') for photo in photos: Task( type='generate_thumbnails', subject_id=photo.id, library=photo.library).save() def handle(self, *args, **options): self.housekeeping()
import os from pathlib import Path from shutil import rmtree from time import sleep from django.conf import settings from django.core.management.base import BaseCommand from photonix.photos.models import Photo, Task from photonix.photos.utils.thumbnails import THUMBNAILER_VERSION class Command(BaseCommand): help = 'Makes sure that if there have been upgrades to thumbnailing or image analysis code then jobs get rescheduled.' def housekeeping(self): # Remove old cache directories for directory in os.listdir(settings.THUMBNAIL_ROOT): if directory not in ['photofile']: path = Path(settings.THUMBNAIL_ROOT) / directory print(f'Removing old cache directory {path}') rmtree(path) # Regenerate any outdated thumbnails photos = Photo.objects.filter(thumbnailed_version__lt=THUMBNAILER_VERSION) if photos.count(): print(f'Rescheduling {photos.count()} photos to have their thumbnails regenerated') for photo in photos: Task( type='generate_thumbnails', subject_id=photo.id, library=photo.library).save() def handle(self, *args, **options): self.housekeeping()
Python
0
6bdc92345a58dc40749eedb9630d0d28d6d23e87
Add release notes for moving_mnist
tensorflow_datasets/video/moving_mnist.py
tensorflow_datasets/video/moving_mnist.py
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # 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. """MovingMNIST.""" import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets.public_api as tfds from tensorflow_datasets.video.moving_sequence import image_as_moving_sequence # pylint: disable=unused-import _OUT_RESOLUTION = (64, 64) _SEQUENCE_LENGTH = 20 _URL = "http://www.cs.toronto.edu/~nitish/unsupervised_video/" _CITATION = """\ @article{DBLP:journals/corr/SrivastavaMS15, author = {Nitish Srivastava and Elman Mansimov and Ruslan Salakhutdinov}, title = {Unsupervised Learning of Video Representations using LSTMs}, journal = {CoRR}, volume = {abs/1502.04681}, year = {2015}, url = {http://arxiv.org/abs/1502.04681}, archivePrefix = {arXiv}, eprint = {1502.04681}, timestamp = {Mon, 13 Aug 2018 16:47:05 +0200}, biburl = {https://dblp.org/rec/bib/journals/corr/SrivastavaMS15}, bibsource = {dblp computer science bibliography, https://dblp.org} } """ _DESCRIPTION = """\ Moving variant of MNIST database of handwritten digits. This is the data used by the authors for reporting model performance. See `tfds.video.moving_mnist.image_as_moving_sequence` for generating training/validation data from the MNIST dataset. """ class MovingMnist(tfds.core.GeneratorBasedBuilder): """MovingMnist.""" VERSION = tfds.core.Version("1.0.0") RELEASE_NOTES={ "1.0.0": "New split API (https://tensorflow.org/datasets/splits)", } def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "image_sequence": tfds.features.Video( shape=(_SEQUENCE_LENGTH,) + _OUT_RESOLUTION + (1,)) }), homepage=_URL, citation=_CITATION, ) def _split_generators(self, dl_manager): data_path = dl_manager.download(_URL + "mnist_test_seq.npy") # authors only provide test data. # See `tfds.video.moving_mnist.image_as_moving_sequence` for mapping # function to create training/validation dataset from MNIST. return [ tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs=dict(data_path=data_path)), ] def _generate_examples(self, data_path): """Generate MovingMnist sequences. Args: data_path (str): Path to the data file Yields: 20 x 64 x 64 x 1 uint8 numpy arrays """ with tf.io.gfile.GFile(data_path, "rb") as fp: images = np.load(fp) images = np.transpose(images, (1, 0, 2, 3)) images = np.expand_dims(images, axis=-1) for i, sequence in enumerate(images): yield i, dict(image_sequence=sequence)
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # 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. """MovingMNIST.""" import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets.public_api as tfds from tensorflow_datasets.video.moving_sequence import image_as_moving_sequence # pylint: disable=unused-import _OUT_RESOLUTION = (64, 64) _SEQUENCE_LENGTH = 20 _URL = "http://www.cs.toronto.edu/~nitish/unsupervised_video/" _CITATION = """\ @article{DBLP:journals/corr/SrivastavaMS15, author = {Nitish Srivastava and Elman Mansimov and Ruslan Salakhutdinov}, title = {Unsupervised Learning of Video Representations using LSTMs}, journal = {CoRR}, volume = {abs/1502.04681}, year = {2015}, url = {http://arxiv.org/abs/1502.04681}, archivePrefix = {arXiv}, eprint = {1502.04681}, timestamp = {Mon, 13 Aug 2018 16:47:05 +0200}, biburl = {https://dblp.org/rec/bib/journals/corr/SrivastavaMS15}, bibsource = {dblp computer science bibliography, https://dblp.org} } """ _DESCRIPTION = """\ Moving variant of MNIST database of handwritten digits. This is the data used by the authors for reporting model performance. See `tfds.video.moving_mnist.image_as_moving_sequence` for generating training/validation data from the MNIST dataset. """ class MovingMnist(tfds.core.GeneratorBasedBuilder): """MovingMnist.""" VERSION = tfds.core.Version( "1.0.0", "New split API (https://tensorflow.org/datasets/splits)") def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "image_sequence": tfds.features.Video( shape=(_SEQUENCE_LENGTH,) + _OUT_RESOLUTION + (1,)) }), homepage=_URL, citation=_CITATION, ) def _split_generators(self, dl_manager): data_path = dl_manager.download(_URL + "mnist_test_seq.npy") # authors only provide test data. # See `tfds.video.moving_mnist.image_as_moving_sequence` for mapping # function to create training/validation dataset from MNIST. return [ tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs=dict(data_path=data_path)), ] def _generate_examples(self, data_path): """Generate MovingMnist sequences. Args: data_path (str): Path to the data file Yields: 20 x 64 x 64 x 1 uint8 numpy arrays """ with tf.io.gfile.GFile(data_path, "rb") as fp: images = np.load(fp) images = np.transpose(images, (1, 0, 2, 3)) images = np.expand_dims(images, axis=-1) for i, sequence in enumerate(images): yield i, dict(image_sequence=sequence)
Python
0
3214645740866f4d15df826880169297b460bce4
fix file mode
egginst/utils.py
egginst/utils.py
import os import sys import random import shutil import string from os.path import basename, isdir, isfile, join chars = string.letters + string.digits def mk_tmp_dir(): tmp_dir = join(sys.prefix, '.tmp_ironpkg') try: shutil.rmtree(tmp_dir) except (WindowsError, IOError): pass if not isdir(tmp_dir): os.mkdir(tmp_dir) return tmp_dir def pprint_fn_action(fn, action): """ Pretty print the distribution name (filename) and an action, the width of the output corresponds to the with of the progress bar used by the function below. """ print "%-56s %20s" % (fn, '[%s]' % action) def rmdir_er(dn): """ Remove empty directories recursively. """ for name in os.listdir(dn): path = join(dn, name) if isdir(path): rmdir_er(path) if not os.listdir(dn): os.rmdir(dn) def rm_rf(path, verbose=False): if isfile(path): if verbose: print "Removing: %r (file)" % path try: os.unlink(path) except (WindowsError, IOError): tmp_dir = mk_tmp_dir() rand = ''.join(random.choice(chars) for x in xrange(10)) os.rename(path, join(tmp_dir, '%s_%s' % (rand, basename(path)))) elif isdir(path): if verbose: print "Removing: %r (directory)" % path shutil.rmtree(path) def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%i B' % n k = (n - 1) / 1024 + 1 if k < 1024: return '%i KB' % k return '%.2f MB' % (float(n) / (2**20))
import os import sys import random import shutil import string from os.path import basename, isdir, isfile, join chars = string.letters + string.digits def mk_tmp_dir(): tmp_dir = join(sys.prefix, '.tmp_ironpkg') try: shutil.rmtree(tmp_dir) except (WindowsError, IOError): pass if not isdir(tmp_dir): os.mkdir(tmp_dir) return tmp_dir def pprint_fn_action(fn, action): """ Pretty print the distribution name (filename) and an action, the width of the output corresponds to the with of the progress bar used by the function below. """ print "%-56s %20s" % (fn, '[%s]' % action) def rmdir_er(dn): """ Remove empty directories recursively. """ for name in os.listdir(dn): path = join(dn, name) if isdir(path): rmdir_er(path) if not os.listdir(dn): os.rmdir(dn) def rm_rf(path, verbose=False): if isfile(path): if verbose: print "Removing: %r (file)" % path try: os.unlink(path) except (WindowsError, IOError): tmp_dir = mk_tmp_dir() rand = ''.join(random.choice(chars) for x in xrange(10)) os.rename(path, join(tmp_dir, '%s_%s' % (rand, basename(path)))) elif isdir(path): if verbose: print "Removing: %r (directory)" % path shutil.rmtree(path) def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%i B' % n k = (n - 1) / 1024 + 1 if k < 1024: return '%i KB' % k return '%.2f MB' % (float(n) / (2**20))
Python
0.000001
ac90bdad2f09a5b79cb33b7ffed4782b7af6db61
Removing old hello world ish
webserver.py
webserver.py
import time from flask import Flask, render_template # DEFAULT_EXPIRATION = 10 # 10 sec # DEFAULT_EXPIRATION = 60 * 10 # 10 min DEFAULT_EXPIRATION = 60 * 20 # 20 min app = Flask(__name__) last_ping = {} @app.route('/') def index(): return render_template('index.html') @app.route('/ping/<thing>') def ping(thing): now = time.time() last_ping[thing] = now return "%s %s" % (thing, now) @app.route('/check/<thing>') def check(thing): if thing not in last_ping: response = u"No such thing as %s" % thing return response, 404 elapsed = time.time() - last_ping[thing] if elapsed > DEFAULT_EXPIRATION: del last_ping[thing] response = u"Thing expired: %s" % thing return response, 404 return "%s %s" % (thing, elapsed)
import time from flask import Flask, render_template # DEFAULT_EXPIRATION = 10 # 10 sec # DEFAULT_EXPIRATION = 60 * 10 # 10 min DEFAULT_EXPIRATION = 60 * 20 # 20 min app = Flask(__name__) last_ping = {} @app.route('/') def index(): # return 'Hello, World!' return render_template('index.html') @app.route('/ping/<thing>') def ping(thing): now = time.time() last_ping[thing] = now return "%s %s" % (thing, now) @app.route('/check/<thing>') def check(thing): if thing not in last_ping: response = u"No such thing as %s" % thing return response, 404 elapsed = time.time() - last_ping[thing] if elapsed > DEFAULT_EXPIRATION: del last_ping[thing] response = u"Thing expired: %s" % thing return response, 404 return "%s %s" % (thing, elapsed)
Python
0.998965
3fadef637ad17458f629a4baeba7fd38205a1510
Bump Katib Python SDK to 0.12.0rc0 version (#1640)
sdk/python/v1beta1/setup.py
sdk/python/v1beta1/setup.py
# Copyright 2021 The Kubeflow Authors. # # 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 setuptools with open('requirements.txt') as f: REQUIRES = f.readlines() setuptools.setup( name='kubeflow-katib', version='0.12.0rc0', author="Kubeflow Authors", author_email='premnath.vel@gmail.com', license="Apache License Version 2.0", url="https://github.com/kubeflow/katib/tree/master/sdk/python/v1beta1", description="Katib Python SDK for APIVersion v1beta1", long_description="Katib Python SDK for APIVersion v1beta1", packages=setuptools.find_packages( include=("kubeflow*")), package_data={}, include_package_data=False, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=REQUIRES )
# Copyright 2021 The Kubeflow Authors. # # 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 setuptools with open('requirements.txt') as f: REQUIRES = f.readlines() setuptools.setup( name='kubeflow-katib', version='0.10.1', author="Kubeflow Authors", author_email='premnath.vel@gmail.com', license="Apache License Version 2.0", url="https://github.com/kubeflow/katib/tree/master/sdk/python/v1beta1", description="Katib Python SDK for APIVersion v1beta1", long_description="Katib Python SDK for APIVersion v1beta1", packages=setuptools.find_packages( include=("kubeflow*")), package_data={}, include_package_data=False, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=REQUIRES )
Python
0
8517803a2cb3f3dd46911ec63acdeae283f23efd
Increase fund graph detail
srv/config.py
srv/config.py
""" Global configuration variables """ import os.path PIE_TOLERANCE = 0.075 PIE_DETAIL = 30 GRAPH_FUND_HISTORY_DETAIL = 200 OVERVIEW_NUM_LAST = 25 OVERVIEW_NUM_FUTURE = 10 START_YEAR = 2014 START_MONTH = 9 LIST_CATEGORIES = ('funds', 'in', 'bills', 'food', 'general', 'holiday', 'social') # common columns are added programmatically LIST_DATA_FORM_SCHEMA = { 'funds': { 'units': ('float', True), }, 'in': { }, 'bills': { }, 'food': { 'category': ('string', True), 'shop': ('string', True) }, 'general': { 'category': ('string', True), 'shop': ('string', True) }, 'holiday': { 'holiday': ('string', True), 'shop': ('string', True) }, 'social': { 'society': ('string', True), 'shop': ('string', True) } } IP_BAN_TIME = 60 IP_BAN_TRIES = 10 BASE_DIR = os.path.dirname(os.path.realpath(__file__)) + "/.." SERIAL_FILE = BASE_DIR + "/resources/serial" FUND_SALT = 'a963anx2' # error messages E_NO_PARAMS = "Not enough parameters given" E_BAD_PARAMS = "Invalid parameters given" E_NO_FORM = "Not enough form data given" E_BAD_FORM = "Invalid form data given" E_NO_ITEM = "Must supply an item (at least)"
""" Global configuration variables """ import os.path PIE_TOLERANCE = 0.075 PIE_DETAIL = 30 GRAPH_FUND_HISTORY_DETAIL = 100 OVERVIEW_NUM_LAST = 25 OVERVIEW_NUM_FUTURE = 10 START_YEAR = 2014 START_MONTH = 9 LIST_CATEGORIES = ('funds', 'in', 'bills', 'food', 'general', 'holiday', 'social') # common columns are added programmatically LIST_DATA_FORM_SCHEMA = { 'funds': { 'units': ('float', True), }, 'in': { }, 'bills': { }, 'food': { 'category': ('string', True), 'shop': ('string', True) }, 'general': { 'category': ('string', True), 'shop': ('string', True) }, 'holiday': { 'holiday': ('string', True), 'shop': ('string', True) }, 'social': { 'society': ('string', True), 'shop': ('string', True) } } IP_BAN_TIME = 60 IP_BAN_TRIES = 10 BASE_DIR = os.path.dirname(os.path.realpath(__file__)) + "/.." SERIAL_FILE = BASE_DIR + "/resources/serial" FUND_SALT = 'a963anx2' # error messages E_NO_PARAMS = "Not enough parameters given" E_BAD_PARAMS = "Invalid parameters given" E_NO_FORM = "Not enough form data given" E_BAD_FORM = "Invalid form data given" E_NO_ITEM = "Must supply an item (at least)"
Python
0
899e3c9f81a43dcb94e290ce0a86f128bd94effd
Apply filter channel published on menu list (channel context processors)
opps/channel/context_processors.py
opps/channel/context_processors.py
# -*- coding: utf-8 -*- from django.utils import timezone from .models import Channel def channel_context(request): """ Channel context processors """ opps_menu = Channel.objects.filter(date_available__lte=timezone.now(), published=True) return {'opps_menu': opps_menu}
# -*- coding: utf-8 -*- from .models import Channel def channel_context(request): return {'opps_menu': Channel.objects.all()}
Python
0
54451c4030bfeece4ab2157afe1ee3f8f65c4dcb
Fix sentry_useremail "duplicate key" error (#16)
sentry_ldap_auth/backend.py
sentry_ldap_auth/backend.py
from __future__ import absolute_import from django_auth_ldap.backend import LDAPBackend from django.conf import settings from sentry.models import ( Organization, OrganizationMember, UserOption, ) class SentryLdapBackend(LDAPBackend): def get_or_create_user(self, username, ldap_user): model = super(SentryLdapBackend, self).get_or_create_user(username, ldap_user) if len(model) < 1: return model user = model[0] user.is_managed = True try: from sentry.models import (UserEmail) except ImportError: pass else: userEmail = UserEmail.objects.get(user=user) if not userEmail: userEmail = UserEmail.objects.create(user=user) userEmail.email=ldap_user.attrs.get('mail', ' ')[0] or '' userEmail.save() # Check to see if we need to add the user to an organization if not settings.AUTH_LDAP_DEFAULT_SENTRY_ORGANIZATION: return model # If the user is already a member of an organization, leave them be orgs = OrganizationMember.objects.filter(user=user) if orgs != None and len(orgs) > 0: return model # Find the default organization organizations = Organization.objects.filter(name=settings.AUTH_LDAP_DEFAULT_SENTRY_ORGANIZATION) if not organizations or len(organizations) < 1: return model member_role = getattr(settings, 'AUTH_LDAP_SENTRY_ORGANIZATION_ROLE_TYPE', 'member') has_global_access = getattr(settings, 'AUTH_LDAP_SENTRY_ORGANIZATION_GLOBAL_ACCESS', False) # Add the user to the organization with global access OrganizationMember.objects.create( organization=organizations[0], user=user, role=member_role, has_global_access=has_global_access, flags=getattr(OrganizationMember.flags, 'sso:linked'), ) if not getattr(settings, 'AUTH_LDAP_SENTRY_SUBSCRIBE_BY_DEFAULT', True): UserOption.objects.set_value( user=user, project=None, key='subscribe_by_default', value='0', ) return model
from __future__ import absolute_import from django_auth_ldap.backend import LDAPBackend from django.conf import settings from sentry.models import ( Organization, OrganizationMember, UserOption, ) class SentryLdapBackend(LDAPBackend): def get_or_create_user(self, username, ldap_user): model = super(SentryLdapBackend, self).get_or_create_user(username, ldap_user) if len(model) < 1: return model user = model[0] user.is_managed = True try: from sentry.models import (UserEmail) except ImportError: pass else: UserEmail.objects.update( user=user, email=ldap_user.attrs.get('mail', ' ')[0] or '', ) # Check to see if we need to add the user to an organization if not settings.AUTH_LDAP_DEFAULT_SENTRY_ORGANIZATION: return model # If the user is already a member of an organization, leave them be orgs = OrganizationMember.objects.filter(user=user) if orgs != None and len(orgs) > 0: return model # Find the default organization organizations = Organization.objects.filter(name=settings.AUTH_LDAP_DEFAULT_SENTRY_ORGANIZATION) if not organizations or len(organizations) < 1: return model member_role = getattr(settings, 'AUTH_LDAP_SENTRY_ORGANIZATION_ROLE_TYPE', 'member') has_global_access = getattr(settings, 'AUTH_LDAP_SENTRY_ORGANIZATION_GLOBAL_ACCESS', False) # Add the user to the organization with global access OrganizationMember.objects.create( organization=organizations[0], user=user, role=member_role, has_global_access=has_global_access, flags=getattr(OrganizationMember.flags, 'sso:linked'), ) if not getattr(settings, 'AUTH_LDAP_SENTRY_SUBSCRIBE_BY_DEFAULT', True): UserOption.objects.set_value( user=user, project=None, key='subscribe_by_default', value='0', ) return model
Python
0.000008
c55bf8d153c47500615b8ded3c95957be8ee70a3
Refactor JSONResponse views to include ListView
froide/helper/json_view.py
froide/helper/json_view.py
from django import http from django.views.generic import DetailView, ListView class JSONResponseMixin(object): def render_to_json_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) class JSONResponseListView(ListView, JSONResponseMixin): def get_context_data(self, **kwargs): self.format = "html" if "format" in self.kwargs: self.format = self.kwargs['format'] context = super(JSONResponseListView, self).get_context_data(**kwargs) return context def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" return "[%s]" % ",".join([o.as_json() for o in context['object_list']]) class JSONResponseDetailView(DetailView, JSONResponseMixin): def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" return context['object'].as_json() def get_context_data(self, **kwargs): self.format = "html" if "format" in self.kwargs: self.format = self.kwargs['format'] context = super(JSONResponseDetailView, self).get_context_data(**kwargs) return context def render_to_response(self, context): if self.format == "json": return self.render_to_json_response(context) else: return super(DetailView, self).render_to_response(context)
from django import http from django.views.generic import DetailView class JSONResponseDetailView(DetailView): def render_to_json_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" return context['object'].as_json() def render_to_response(self, context): if self.format == "json": return self.render_to_json_response(context) else: return super(DetailView, self).render_to_response(context)
Python
0
e03103c74a066184178980f1073505724e094394
Fix url order
stadt/urls.py
stadt/urls.py
from django.conf import settings, urls from django.conf.urls import static from django.contrib import admin urlpatterns = [ urls.url(r'^stadt/admin/', admin.site.urls), urls.url(r'^stadt/api/', urls.include('core.api_urls')), urls.url(r'^stadt/', urls.include('account.urls')), urls.url(r'^stadt/', urls.include('content.urls')), urls.url(r'^stadt/', urls.include('entities.urls')), urls.url(r'^stadt/', urls.include('features.articles.urls')), urls.url(r'^stadt/', urls.include('features.associations.urls')), urls.url(r'^stadt/', urls.include('features.conversations.urls')), urls.url(r'^stadt/', urls.include('features.memberships.urls')), urls.url(r'^stadt/', urls.include('features.sharing.urls')), urls.url(r'^stadt/', urls.include('features.subscriptions.urls')), urls.url(r'^stadt/', urls.include('features.tags.urls')), urls.url(r'^', urls.include('features.stadt.urls')), urls.url(r'^', urls.include('features.events.urls')), # matches /*/, should be included late, groups before gestalten urls.url(r'^', urls.include('features.groups.urls')), urls.url(r'^', urls.include('features.gestalten.urls')), # matches /*/*/, should be included at last urls.url(r'^', urls.include('features.content.urls')), ] + static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings, urls from django.conf.urls import static from django.contrib import admin urlpatterns = [ urls.url(r'^stadt/admin/', admin.site.urls), urls.url(r'^stadt/api/', urls.include('core.api_urls')), urls.url(r'^stadt/', urls.include('account.urls')), urls.url(r'^stadt/', urls.include('content.urls')), urls.url(r'^stadt/', urls.include('entities.urls')), urls.url(r'^stadt/', urls.include('features.articles.urls')), urls.url(r'^stadt/', urls.include('features.associations.urls')), urls.url(r'^stadt/', urls.include('features.conversations.urls')), urls.url(r'^stadt/', urls.include('features.memberships.urls')), urls.url(r'^stadt/', urls.include('features.sharing.urls')), urls.url(r'^stadt/', urls.include('features.subscriptions.urls')), urls.url(r'^stadt/', urls.include('features.tags.urls')), urls.url(r'^', urls.include('features.stadt.urls')), urls.url(r'^', urls.include('features.events.urls')), urls.url(r'^', urls.include('features.content.urls')), urls.url(r'^', urls.include('features.groups.urls')), urls.url(r'^', urls.include('features.gestalten.urls')), ] + static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Python
0.999733
a72f72c16aaf1689fc364311afe3b42a6fed7eae
add examples
CourierToDovecot.py
CourierToDovecot.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ----------------------- # Author : jgo # Execute a perl script into all mailbox newly created, # on the Dovecot server. # ----------------------- import subprocess import os import logging from logging.handlers import RotatingFileHandler ## [Config VARS] -------------------------------------------- # Don't change this value! :) init_path = os.path.dirname(os.path.realpath(__file__)) # Change this value with your target dir (example : '/var/spool/mail') dest_path = '/var/spool/mail/' # Change this value with your script path (example: '/script.sh') script_path = '/courier-dovecot-migrate.pl --to-dovecot --convert --recursive' ## ---------------------------------------------------------- ## [Logging] ------------------------------------------------ # Create logger object used to write logfile logger = logging.getLogger() # Set your Log level to debug => Write everything logger.setLevel(logging.DEBUG) # Choose how you want your log format formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') # Create a file (valhalla.log) in "append mode", max size => 30Mb # and 1 backup. logfile = 'valhalla.log' file_handler = RotatingFileHandler(logfile, 'a', 30000000, 1) # Assign our formatter and set to debug mode. file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Create a second handler to display the log on the console steam_handler = logging.StreamHandler() steam_handler.setLevel(logging.DEBUG) logger.addHandler(steam_handler) ## ---------------------------------------------------------- print '====================================================' print '[SCRIPT STATUS]' print '====================================================' # Create a list with all directory output = subprocess.check_output( 'ls -R ' + dest_path + ' | grep "[[:alnum:]]\+@[[:alnum:]]\+" | tr ":" "/" | grep "/"', shell=True ) # Transform the output to a list output = output.split() obj = len(output) # Execute the script into all dir try: for path in output: os.chdir(path) logger.info('[Job] - Working on %s' % path) subprocess.call(init_path + script_path, shell=True) except SyntaxError: logger.error('SyntaxError, your target already exists.') print 'Please check your log file SyntaxError detected' except OSError: logger.error('OSError, this script can\'t be used on files') print 'Please check your log file OSError detected' finally: os.chdir(init_path) print '' print 'Number of objects handled : %s' % obj print 'Log file : %s' % logfile print '===================================================='
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ----------------------- # Author : jgo # Execute a perl script into all mailbox newly created, # on the Dovecot server. # ----------------------- import subprocess import os import logging from logging.handlers import RotatingFileHandler ## [Config VARS] -------------------------------------------- # Don't change this value! :) init_path = os.path.dirname(os.path.realpath(__file__)) # Change this value with your target dir dest_path = '/var/spool/mail/' # Change this value with your script path script_path = '/courier-dovecot-migrate.pl --to-dovecot --convert --recursive' ## ---------------------------------------------------------- ## [Logging] ------------------------------------------------ # Create logger object used to write logfile logger = logging.getLogger() # Set your Log level to debug => Write everything logger.setLevel(logging.DEBUG) # Choose how you want your log format formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') # Create a file (valhalla.log) in "append mode", max size => 30Mb # and 1 backup. logfile = 'valhalla.log' file_handler = RotatingFileHandler(logfile, 'a', 30000000, 1) # Assign our formatter and set to debug mode. file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Create a second handler to display the log on the console steam_handler = logging.StreamHandler() steam_handler.setLevel(logging.DEBUG) logger.addHandler(steam_handler) ## ---------------------------------------------------------- print '====================================================' print '[SCRIPT STATUS]' print '====================================================' # Create a list with all directory output = subprocess.check_output( 'ls -R ' + dest_path + ' | grep "[[:alnum:]]\+@[[:alnum:]]\+" | tr ":" "/" | grep "/"', shell=True ) # Transform the output to a list output = output.split() obj = len(output) # Execute the script into all dir try: for path in output: os.chdir(path) logger.info('[Job] - Working on %s' % path) subprocess.call(init_path + script_path, shell=True) except SyntaxError: logger.error('SyntaxError, your target already exists.') print 'Please check your log file SyntaxError detected' except OSError: logger.error('OSError, this script can\'t be used on files') print 'Please check your log file OSError detected' finally: os.chdir(init_path) print '' print 'Number of objects handled : %s' % obj print 'Log file : %s' % logfile print '===================================================='
Python
0
83ed8a4fd258f351da2ea358613ff57dadbf03f6
Remove blank line
junction/proposals/permissions.py
junction/proposals/permissions.py
# -*- coding: utf-8 -*- # Third Party Stuff from django.core.exceptions import PermissionDenied # Junction Stuff from junction.conferences.models import ConferenceProposalReviewer from junction.base.constants import ConferenceStatus from .models import ProposalSectionReviewer def is_proposal_voting_allowed(proposal): return proposal.conference.status != ConferenceStatus.SCHEDULE_PUBLISHED def is_proposal_author(user, proposal): return user.is_authenticated() and proposal.author == user def is_proposal_reviewer(user, conference): authenticated = user.is_authenticated() is_reviewer = ConferenceProposalReviewer.objects.filter( reviewer=user.id, conference=conference, active=True).exists() return authenticated and is_reviewer def is_proposal_section_reviewer(user, conference, proposal): return user.is_authenticated() and ProposalSectionReviewer.objects.filter( conference_reviewer__reviewer=user, conference_reviewer__conference=conference, proposal_section=proposal.proposal_section, active=True).exists() def is_proposal_author_or_proposal_reviewer(user, conference, proposal): reviewer = is_proposal_reviewer(user, conference) author = is_proposal_author(user, proposal) return reviewer or author def is_proposal_author_or_proposal_section_reviewer(user, conference, proposal): return is_proposal_author(user, proposal) or \ is_proposal_section_reviewer(user, conference, proposal) def is_proposal_author_or_permisson_denied(user, proposal): if is_proposal_author(user, proposal): return True raise PermissionDenied def is_conference_moderator(user, conference): if user.is_superuser: return True users = [mod.moderator for mod in conference.moderators.all()] return user in users
# -*- coding: utf-8 -*- # Third Party Stuff from django.core.exceptions import PermissionDenied # Junction Stuff from junction.conferences.models import ConferenceProposalReviewer from junction.base.constants import ConferenceStatus from .models import ProposalSectionReviewer def is_proposal_voting_allowed(proposal): return proposal.conference.status != ConferenceStatus.SCHEDULE_PUBLISHED def is_proposal_author(user, proposal): return user.is_authenticated() and proposal.author == user def is_proposal_reviewer(user, conference): authenticated = user.is_authenticated() is_reviewer = ConferenceProposalReviewer.objects.filter( reviewer=user.id, conference=conference, active=True).exists() return authenticated and is_reviewer def is_proposal_section_reviewer(user, conference, proposal): return user.is_authenticated() and ProposalSectionReviewer.objects.filter( conference_reviewer__reviewer=user, conference_reviewer__conference=conference, proposal_section=proposal.proposal_section, active=True).exists() def is_proposal_author_or_proposal_reviewer(user, conference, proposal): reviewer = is_proposal_reviewer(user, conference) author = is_proposal_author(user, proposal) return reviewer or author def is_proposal_author_or_proposal_section_reviewer(user, conference, proposal): return is_proposal_author(user, proposal) or \ is_proposal_section_reviewer(user, conference, proposal) def is_proposal_author_or_permisson_denied(user, proposal): if is_proposal_author(user, proposal): return True raise PermissionDenied def is_conference_moderator(user, conference): if user.is_superuser: return True users = [mod.moderator for mod in conference.moderators.all()] return user in users
Python
0.999999
f8ea5ef37280366b4b3991442e406952bb0575b3
Create calculate_cosine_distance.py
k-NN/calculate_cosine_distance.py
k-NN/calculate_cosine_distance.py
''' Calculates the cosine distance for an input data ''' import math import numpy as np import scipy.io __author__ = """Marina von Steinkirch""" def cosineDistance(x, y): ''' This function computes the cosine distance between feature vectors x and y. This distance is frequently used for text classification. It varies between 0 and 1. The distance is 0 if x==y. ''' denom = math.sqrt(sum(x**2)*sum(y**2)) dist = 1.0-(np.dot(x, y.conj().transpose()))/denom return round(dist, 6) def print_to_file(distances): with open('cos_distances.dat', 'w') as f: for i, col in enumerate(distances): f.write('# distance for example %d to others\n' %(i+1)) for item in col: f.write(str(item) + ' ') f.write('\n') def main(): f = scipy.io.loadmat('cvdataset.mat') traindata = f['traindata'] trainlabels = f['trainlabels'] testdata = f['testdata'] evaldata = f['evaldata'] testlabels = f['testlabels'] distances = [] for i in range(len(trainlabels)): first_train_example_class1 = traindata[i] aux = [] for j in range (len(trainlabels)): first_train_example_class2 = traindata[j] d = cosineDistance(first_train_example_class1, first_train_example_class2) aux.append(d) distances.append(aux) print_to_file(distances) if __name__ == '__main__': main()
''' Calculates the cosine distance for an input data ''' import math import numpy as np import scipy.io __author__ = """Mari Wahl""" def cosineDistance(x, y): ''' This function computes the cosine distance between feature vectors x and y. This distance is frequently used for text classification. It varies between 0 and 1. The distance is 0 if x==y. ''' denom = math.sqrt(sum(x**2)*sum(y**2)) dist = 1.0-(np.dot(x, y.conj().transpose()))/denom return round(dist, 6) def print_to_file(distances): with open('cos_distances.dat', 'w') as f: for i, col in enumerate(distances): f.write('# distance for example %d to others\n' %(i+1)) for item in col: f.write(str(item) + ' ') f.write('\n') def main(): f = scipy.io.loadmat('cvdataset.mat') traindata = f['traindata'] trainlabels = f['trainlabels'] testdata = f['testdata'] evaldata = f['evaldata'] testlabels = f['testlabels'] distances = [] for i in range(len(trainlabels)): first_train_example_class1 = traindata[i] aux = [] for j in range (len(trainlabels)): first_train_example_class2 = traindata[j] d = cosineDistance(first_train_example_class1, first_train_example_class2) aux.append(d) distances.append(aux) print_to_file(distances) if __name__ == '__main__': main()
Python
0.00003
2cde35bb6f948f861026921daf7fe24b353af273
Add bulleted and numbered list to CKEditor
kerrokantasi/settings/__init__.py
kerrokantasi/settings/__init__.py
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Video', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
Python
0
d09cc197d11efa2181ce68ef4212cb9df5ee285c
add daemon argument to launcher
selfdrive/athena/manage_athenad.py
selfdrive/athena/manage_athenad.py
#!/usr/bin/env python3 import time from multiprocessing import Process from common.params import Params from selfdrive.manager.process import launcher from selfdrive.swaglog import cloudlog from selfdrive.version import get_version, is_dirty ATHENA_MGR_PID_PARAM = "AthenadPid" def main(): params = Params() dongle_id = params.get("DongleId").decode('utf-8') cloudlog.bind_global(dongle_id=dongle_id, version=get_version(), dirty=is_dirty()) try: while 1: cloudlog.info("starting athena daemon") proc = Process(name='athenad', target=launcher, args=('selfdrive.athena.athenad', 'athenad')) proc.start() proc.join() cloudlog.event("athenad exited", exitcode=proc.exitcode) time.sleep(5) except Exception: cloudlog.exception("manage_athenad.exception") finally: params.delete(ATHENA_MGR_PID_PARAM) if __name__ == '__main__': main()
#!/usr/bin/env python3 import time from multiprocessing import Process from common.params import Params from selfdrive.manager.process import launcher from selfdrive.swaglog import cloudlog from selfdrive.version import get_version, is_dirty ATHENA_MGR_PID_PARAM = "AthenadPid" def main(): params = Params() dongle_id = params.get("DongleId").decode('utf-8') cloudlog.bind_global(dongle_id=dongle_id, version=get_version(), dirty=is_dirty()) try: while 1: cloudlog.info("starting athena daemon") proc = Process(name='athenad', target=launcher, args=('selfdrive.athena.athenad',)) proc.start() proc.join() cloudlog.event("athenad exited", exitcode=proc.exitcode) time.sleep(5) except Exception: cloudlog.exception("manage_athenad.exception") finally: params.delete(ATHENA_MGR_PID_PARAM) if __name__ == '__main__': main()
Python
0.000001
38eb6221ca41446c0c4fb1510354bdc4f00ba5f1
Remove children via uid rather than name
serfnode/build/handler/launcher.py
serfnode/build/handler/launcher.py
#!/usr/bin/env python import functools import os import signal import sys import docker_utils def handler(name, signum, frame): print('Should kill', name) try: cid = open('/child_{}'.format(name)).read().strip() docker_utils.client.remove_container(cid, force=True) except Exception: pass sys.exit(0) def launch(name, args): try: cid = open('/child_{}'.format(name)).read().strip() except IOError: cid = name try: os.unlink('/child_{}'.format(name)) except OSError: pass try: docker_utils.client.remove_container(cid, force=True) except Exception: pass args.insert(0, '--cidfile=/child_{}'.format(name)) docker_utils.docker('run', *args) if __name__ == '__main__': name = sys.argv[1] args = sys.argv[2:] signal.signal(signal.SIGINT, functools.partial(handler, name)) launch(name, args)
#!/usr/bin/env python import functools import os import signal import sys import docker_utils def handler(name, signum, frame): print('Should kill', name) try: docker_utils.client.remove_container(name, force=True) except Exception: pass sys.exit(0) def launch(name, args): try: os.unlink('/child_{}'.format(name)) except OSError: pass try: docker_utils.client.remove_container(name, force=True) except Exception: pass args.insert(0, '--cidfile=/child_{}'.format(name)) docker_utils.docker('run', *args) if __name__ == '__main__': name = sys.argv[1] args = sys.argv[2:] signal.signal(signal.SIGINT, functools.partial(handler, name)) launch(name, args)
Python
0
933201b14764b8a108986313b8bece8ae4ad7d51
handle in_progress event
km_hipchat_screamer/statuspage.py
km_hipchat_screamer/statuspage.py
# -*- coding: utf-8 -*- """ km-hipchat-screamer.statuspage ~~~~~~~~~~~~~~~~~~~~~~~ Module providing for status change alert routes the KISSmetrics HipChat Webhook service """ from flask import Blueprint, jsonify, request from utils import env_check import os import json import hipchat import requests hipchat_notification_color = { 'operational': 'green', 'degraded_performance': 'yellow', 'partial_outage': 'yellow', 'major_outage': 'red', 'scheduled': 'gray', 'in_progress': 'gray', 'investigating': 'red', 'identified': 'yellow', 'monitoring': 'gray', 'resolved': 'green' } def get_component_name(page_id, component_id): url = 'http://%s.statuspage.io/index.json' % (page_id) response = requests.get(url) data = response.json() for component in data['components']: if component['id'] == component_id: return component['name'] STATUSPAGE_HIPCHAT_TOKEN = os.environ.get('STATUSPAGE_HIPCHAT_TOKEN') STATUSPAGE_NOTIFY_ROOMS = os.environ.get('STATUSPAGE_NOTIFY_ROOMS') statuspage = Blueprint('statuspage', __name__) #------- # Routes #------- @statuspage.route('/statuspage/alert', methods=['POST']) @env_check('STATUSPAGE_HIPCHAT_TOKEN') @env_check('STATUSPAGE_NOTIFY_ROOMS') def statuspage_route(): """Send alerts for statuspage.io webhooks to rooms listed in STATUSPAGE_NOTIFY_ROOMS""" notification = json.loads(request.data) if 'component_update' in notification: page_id = notification['page']['id'] component_update = notification['component_update'] component_id = component_update['component_id'] component_name = get_component_name(page_id, component_id) old_status = component_update['old_status'] new_status = component_update['new_status'] color = hipchat_notification_color[new_status] message = "[%s] status changed from %s to %s" % (component_name, old_status, new_status) elif 'incident' in notification: incident_update = notification['incident'] incident_name = incident_update['name'] incident_status = incident_update['status'] incident_message = incident_update['incident_updates'][0]['body'] color = hipchat_notification_color[incident_status] message = "[%s] %s: %s" % (incident_name, incident_status, incident_message) hipchat_api = hipchat.HipChat(token=STATUSPAGE_HIPCHAT_TOKEN) for channel in STATUSPAGE_NOTIFY_ROOMS.split(','): hipchat_api.message_room(channel, 'KM Status', message, notify=True, color=color) body = { "action": "message sent" } return jsonify(body)
# -*- coding: utf-8 -*- """ km-hipchat-screamer.statuspage ~~~~~~~~~~~~~~~~~~~~~~~ Module providing for status change alert routes the KISSmetrics HipChat Webhook service """ from flask import Blueprint, jsonify, request from utils import env_check import os import json import hipchat import requests hipchat_notification_color = { 'operational': 'green', 'degraded_performance': 'yellow', 'partial_outage': 'yellow', 'major_outage': 'red', 'scheduled': 'gray', 'investigating': 'red', 'identified': 'yellow', 'monitoring': 'gray', 'resolved': 'green' } def get_component_name(page_id, component_id): url = 'http://%s.statuspage.io/index.json' % (page_id) response = requests.get(url) data = response.json() for component in data['components']: if component['id'] == component_id: return component['name'] STATUSPAGE_HIPCHAT_TOKEN = os.environ.get('STATUSPAGE_HIPCHAT_TOKEN') STATUSPAGE_NOTIFY_ROOMS = os.environ.get('STATUSPAGE_NOTIFY_ROOMS') statuspage = Blueprint('statuspage', __name__) #------- # Routes #------- @statuspage.route('/statuspage/alert', methods=['POST']) @env_check('STATUSPAGE_HIPCHAT_TOKEN') @env_check('STATUSPAGE_NOTIFY_ROOMS') def statuspage_route(): """Send alerts for statuspage.io webhooks to rooms listed in STATUSPAGE_NOTIFY_ROOMS""" notification = json.loads(request.data) if 'component_update' in notification: page_id = notification['page']['id'] component_update = notification['component_update'] component_id = component_update['component_id'] component_name = get_component_name(page_id, component_id) old_status = component_update['old_status'] new_status = component_update['new_status'] color = hipchat_notification_color[new_status] message = "[%s] status changed from %s to %s" % (component_name, old_status, new_status) elif 'incident' in notification: incident_update = notification['incident'] incident_name = incident_update['name'] incident_status = incident_update['status'] incident_message = incident_update['incident_updates'][0]['body'] color = hipchat_notification_color[incident_status] message = "[%s] %s: %s" % (incident_name, incident_status, incident_message) hipchat_api = hipchat.HipChat(token=STATUSPAGE_HIPCHAT_TOKEN) for channel in STATUSPAGE_NOTIFY_ROOMS.split(','): hipchat_api.message_room(channel, 'KM Status', message, notify=True, color=color) body = { "action": "message sent" } return jsonify(body)
Python
0.000012
875d558d69fcadcea5f89b4ef4021484b34e435b
fix #190
django-openstack/django_openstack/syspanel/views/services.py
django-openstack/django_openstack/syspanel/views/services.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 from django import template from django import http from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.shortcuts import redirect from django.utils.translation import ugettext as _ import datetime import json import logging import subprocess import urlparse from django.contrib import messages from django_openstack import api from django_openstack import forms from django_openstack.dash.views import instances as dash_instances from openstackx.api import exceptions as api_exceptions class ToggleService(forms.SelfHandlingForm): service = forms.CharField(required=False) name = forms.CharField(required=False) def handle(self, request, data): try: service = api.service_get(request, data['service']) api.service_update(request, data['service'], not service.disabled) if service.disabled: messages.info(request, "Service '%s' has been enabled" % data['name']) else: messages.info(request, "Service '%s' has been disabled" % data['name']) except api_exceptions.ApiException, e: messages.error(request, "Unable to update service '%s': %s" % data['name'], e.message) return redirect(request.build_absolute_uri()) @login_required def index(request): for f in (ToggleService,): _, handled = f.maybe_handle(request) if handled: return handled services = [] try: services = api.service_list(request) except api_exceptions.ApiException, e: messages.error(request, 'Unable to get service info: %s' % e.message) other_services = [] for k, v in request.session['serviceCatalog'].iteritems(): v = v[0] try: subprocess.check_call(['curl', '-m', '1', v['internalURL']]) up = True except: up = False hostname = urlparse.urlparse(v['internalURL']).hostname row = {'type': k, 'internalURL': v['internalURL'], 'host': hostname, 'region': v['region'], 'up': up } other_services.append(row) services = sorted(services, key=lambda svc: (svc.type + svc.host)) other_services = sorted(other_services, key=lambda svc: (svc['type'] + svc['host'])) return render_to_response('syspanel_services.html', { 'services': services, 'service_toggle_enabled_form': ToggleService, 'other_services': other_services, }, context_instance = template.RequestContext(request))
# vim: tabstop=4 shiftwidth=4 softtabstop=4 from django import template from django import http from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.shortcuts import redirect from django.utils.translation import ugettext as _ import datetime import json import logging import subprocess import urlparse from django.contrib import messages from django_openstack import api from django_openstack import forms from django_openstack.dash.views import instances as dash_instances from openstackx.api import exceptions as api_exceptions class ToggleService(forms.SelfHandlingForm): service = forms.CharField(required=False) name = forms.CharField(required=False) def handle(self, request, data): try: service = api.service_get(request, data['service']) api.service_update(request, data['service'], not service.disabled) if service.disabled: messages.info(request, "Service '%s' has been enabled" % data['name']) else: messages.info(request, "Service '%s' has been disabled" % data['name']) except api_exceptions.ApiException, e: messages.error(request, "Unable to update service '%s': %s" % data['name'], e.message) return redirect(request.build_absolute_uri()) @login_required def index(request): for f in (ToggleService,): _, handled = f.maybe_handle(request) if handled: return handled services = [] try: services = api.service_list(request) except api_exceptions.ApiException, e: messages.error(request, 'Unable to get service info: %s' % e.message) other_services = [] for k, v in request.session['serviceCatalog'].iteritems(): v = v[0] try: subprocess.check_call(['curl', '-m', '1', v['internalURL']]) up = True except: up = False hostname = urlparse.urlparse(v['internalURL']).hostname row = {'type': k, 'internalURL': v['internalURL'], 'host': hostname, 'region': v['region'], 'up': up } other_services.append(row) return render_to_response('syspanel_services.html', { 'services': services, 'service_toggle_enabled_form': ToggleService, 'other_services': other_services, }, context_instance = template.RequestContext(request))
Python
0.000001
93361bad12c132846b10966559fe89bc1d1a1e0b
Update settings.py
Epitome/settings.py
Epitome/settings.py
""" Django settings for Epitome project. Generated by 'django-admin startproject' using Django 2.0.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'DefaultKeyMustBeChanged' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Agora', 'Propylaea', 'Eisegesis', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Epitome.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Epitome.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'Atlas.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ]
""" Django settings for Epitome project. Generated by 'django-admin startproject' using Django 2.0.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'DefaultKeyMustBeChanged' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Agora', 'Propylaea', 'Eisegesis', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Epitome.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Epitome.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'Atlas.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ]
Python
0.000001
bd3d8738fc00b2d36aafe5749e88826845441541
fix handling of pages (closes #685)
weboob/backends/orange/browser.py
weboob/backends/orange/browser.py
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Nicolas Duhamel # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. #~ from .pages.compose import ClosePage, ComposePage, ConfirmPage, SentPage #~ from .pages.login import LoginPage from .pages import LoginPage, ComposePage, ConfirmPage from weboob.tools.browser import BaseBrowser, BrowserIncorrectPassword __all__ = ['OrangeBrowser'] class OrangeBrowser(BaseBrowser): DOMAIN = 'orange.fr' PAGES = { 'http://id.orange.fr/auth_user/bin/auth_user.cgi.*': LoginPage, 'http://id.orange.fr/auth_user/bin/auth0user.cgi.*': LoginPage, 'http://smsmms1.orange.fr/./Sms/sms_write.php.*' : ComposePage, 'http://smsmms1.orange.fr/./Sms/sms_write.php?command=send' : ConfirmPage, } def get_nb_remaining_free_sms(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php") return self.page.get_nb_remaining_free_sms() def home(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php") def is_logged(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php", no_login=True) return not self.is_on_page(LoginPage) def login(self): if not self.is_on_page(LoginPage): self.location('http://id.orange.fr/auth_user/bin/auth_user.cgi?url=http://www.orange.fr', no_login=True) self.page.login(self.username, self.password) if not self.is_logged(): raise BrowserIncorrectPassword() def post_message(self, message, sender): if not self.is_on_page(ComposePage): self.home() self.page.post_message(message, sender)
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Nicolas Duhamel # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. #~ from .pages.compose import ClosePage, ComposePage, ConfirmPage, SentPage #~ from .pages.login import LoginPage from .pages import LoginPage, ComposePage, ConfirmPage from weboob.tools.browser import BaseBrowser, BrowserIncorrectPassword __all__ = ['OrangeBrowser'] class OrangeBrowser(BaseBrowser): DOMAIN = 'orange.fr' PAGES = { 'http://id.orange.fr/auth_user/bin/auth_user.cgi.*': LoginPage, 'http://id.orange.fr/auth_user/bin/auth0user.cgi.*': LoginPage, 'http://smsmms1.orange.fr/M/Sms/sms_write.php.*' : ComposePage, 'http://smsmms1.orange.fr/M/Sms/sms_write.php?command=send' : ConfirmPage, } def get_nb_remaining_free_sms(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php") return self.page.get_nb_remaining_free_sms() def home(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php") def is_logged(self): self.location("http://smsmms1.orange.fr/M/Sms/sms_write.php", no_login=True) return not self.is_on_page(LoginPage) def login(self): if not self.is_on_page(LoginPage): self.location('http://id.orange.fr/auth_user/bin/auth_user.cgi?url=http://www.orange.fr', no_login=True) self.page.login(self.username, self.password) if not self.is_logged(): raise BrowserIncorrectPassword() def post_message(self, message, sender): if not self.is_on_page(ComposePage): self.home() self.page.post_message(message, sender)
Python
0
f631099894a02cb79b5be372894ed1f589849a8d
test for datetime.datetime type from dframe_dateconv
test/pandaservtest.py
test/pandaservtest.py
import unittest, sys, os from datetime import datetime import pandas as pd import src.pandaserv as pandaserv import numpy as np class Testpandaserv(unittest.TestCase): def setUp(self): self.dates = pd.date_range('20130101', periods=6) self.df = pd.DataFrame( np.random.randn(6,4), index=self.dates, columns=list('ABCD')) self.df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : np.array([3] * 4,dtype='int32'), 'E' : pd.Categorical(["test","train","test","train"]), 'F' : 'foo' }) def test_dframe_dateconv(self): print('Unfinished test, PASS.') pandaserv.dframe_dateconv(self.df2, 'B') for singledate in df['B']: self.assertIsInstance(singledate, datetime) def test_dframe_currencystrip(self): print('Unfinished test, PASS.') def test_make_sheets(self): print('Unfinished test, PASS.') def test_clean_sheets(self): print('Unfinished test, PASS.') if __name__ == '__main__': unittest.main()
import unittest, sys, os from datetime import datetime import pandas as pd import src.pandaserv as pandaserv import numpy as np class Testpandaserv(unittest.TestCase): def setUp(self): self.dates = pd.date_range('20130101', periods=6) self.df = pd.DataFrame( np.random.randn(6,4), index=self.dates, columns=list('ABCD')) self.df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : np.array([3] * 4,dtype='int32'), 'E' : pd.Categorical(["test","train","test","train"]), 'F' : 'foo' }) def test_dframe_dateconv(self): print('Unfinished test, PASS.') pandaserv.dframe_dateconv(self.df, 'D') self.assertIsInstance(self.df['D'], datetime) def test_dframe_currencystrip(self): print('Unfinished test, PASS.') def test_make_sheets(self): print('Unfinished test, PASS.') def test_clean_sheets(self): print('Unfinished test, PASS.') if __name__ == '__main__': unittest.main()
Python
0
e8e109de54ebed6336f6ed3bcb2400ec5d4aaafb
add docs for number
schematec/converters.py
schematec/converters.py
''' Convertaion rules ================= Can be converted into: integer ------- #. Any int or long value #. Any suitable string/unicode #. Boolean value number ------- #. Any float or int or long value #. Any suitable string/unicode #. Boolean value string ------ #. Any suitable string/unicode #. Any int or long value boolean ------- #. Boolean value #. 0 or 1 #. '0' or '1' #. u'0' or u'1' array ----- #. Any iterable value(collections.Iterable) dictionary ---------- #. Any mapping value(collections.Mapping) ''' from __future__ import absolute_import import collections import schematec.exc as exc class Converter(object): pass class Integer(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return int(value) if isinstance(value, (int, long)): return int(value) if isinstance(value, basestring): try: return int(value) except ValueError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) integer = Integer() class Number(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return float(value) if isinstance(value, (float, int, long)): return float(value) if isinstance(value, basestring): try: return float(value) except ValueError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) number = Number() class String(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, unicode): return value if isinstance(value, bool): raise exc.ConvertationError(value) if isinstance(value, (int, long)): return unicode(value) if isinstance(value, str): try: return unicode(value) except UnicodeDecodeError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) string = String() class Boolean(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return value if isinstance(value, (int, long)) and value in (0, 1): return bool(value) if isinstance(value, basestring) and value in (u'0', u'1'): return bool(int(value)) raise exc.ConvertationError(value) boolean = Boolean() class Array(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, collections.Iterable): return list(value) raise exc.ConvertationError(value) array = Array() class Dictionary(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, collections.Mapping): return dict(value) raise exc.ConvertationError(value) dictionary = Dictionary()
''' Convertaion rules ================= Can be converted into: integer ------- #. Any int or long value #. Any suitable string/unicode #. Boolean value string ------ #. Any suitable string/unicode #. Any int or long value boolean ------- #. Boolean value #. 0 or 1 #. '0' or '1' #. u'0' or u'1' array ----- #. Any iterable value(collections.Iterable) dictionary ---------- #. Any mapping value(collections.Mapping) ''' from __future__ import absolute_import import collections import schematec.exc as exc class Converter(object): pass class Integer(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return int(value) if isinstance(value, (int, long)): return int(value) if isinstance(value, basestring): try: return int(value) except ValueError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) integer = Integer() class Number(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return float(value) if isinstance(value, (float, int, long)): return float(value) if isinstance(value, basestring): try: return float(value) except ValueError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) number = Number() class String(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, unicode): return value if isinstance(value, bool): raise exc.ConvertationError(value) if isinstance(value, (int, long)): return unicode(value) if isinstance(value, str): try: return unicode(value) except UnicodeDecodeError: raise exc.ConvertationError(value) raise exc.ConvertationError(value) string = String() class Boolean(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, bool): return value if isinstance(value, (int, long)) and value in (0, 1): return bool(value) if isinstance(value, basestring) and value in (u'0', u'1'): return bool(int(value)) raise exc.ConvertationError(value) boolean = Boolean() class Array(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, collections.Iterable): return list(value) raise exc.ConvertationError(value) array = Array() class Dictionary(Converter): def __call__(self, value): if value is None: raise exc.ConvertationError(value) if isinstance(value, collections.Mapping): return dict(value) raise exc.ConvertationError(value) dictionary = Dictionary()
Python
0.000001
91238b6b0f0b14a6d0f7707aa0b388cedfd5894c
set default false allow_cnpj_multi_ie
l10n_br_base/models/res_config.py
l10n_br_base/models/res_config.py
# -*- coding: utf-8 -*- from openerp import fields, models from openerp.tools.safe_eval import safe_eval class res_config(models.TransientModel): _inherit = 'base.config.settings' allow_cnpj_multi_ie = fields.Boolean( string=u'Permitir o cadastro de Customers com CNPJs iguais', default=False, ) def get_default_allow_cnpj_multi_ie(self, cr, uid, fields, context=None): icp = self.pool.get('ir.config_parameter') return { 'allow_cnpj_multi_ie': safe_eval(icp.get_param( cr, uid, 'l10n_br_base_allow_cnpj_multi_ie', 'False')), } def set_allow_cnpj_multi_ie(self, cr, uid, ids, context=None): config = self.browse(cr, uid, ids[0], context=context) icp = self.pool.get('ir.config_parameter') icp.set_param(cr, uid, 'l10n_br_base_allow_cnpj_multi_ie', repr(config.allow_cnpj_multi_ie))
# -*- coding: utf-8 -*- from openerp import fields, models from openerp.tools.safe_eval import safe_eval class res_config(models.TransientModel): _inherit = 'base.config.settings' allow_cnpj_multi_ie = fields.Boolean( string=u'Permitir o cadastro de Customers com CNPJs iguais', default=True, ) def get_default_allow_cnpj_multi_ie(self, cr, uid, fields, context=None): icp = self.pool.get('ir.config_parameter') return { 'allow_cnpj_multi_ie': safe_eval(icp.get_param( cr, uid, 'l10n_br_base_allow_cnpj_multi_ie', 'False')), } def set_allow_cnpj_multi_ie(self, cr, uid, ids, context=None): config = self.browse(cr, uid, ids[0], context=context) icp = self.pool.get('ir.config_parameter') icp.set_param(cr, uid, 'l10n_br_base_allow_cnpj_multi_ie', repr(config.allow_cnpj_multi_ie))
Python
0.000003
bc9c782317eac99716bc961e42e6072f0e5616cf
Add dummy var in order to work around issue 1 https://github.com/LinuxTeam-teilar/cronos.teilar.gr/issues/1
apps/__init__.py
apps/__init__.py
# -*- coding: utf-8 -*- from django.conf import settings from django.core.mail import send_mail ''' For unkown reason, the logger is NOT able to find a handler unless a settings.VARIABLE is called!! https://github.com/LinuxTeam-teilar/cronos.teilar.gr/issues/1 I leave that here till the bug is fixed ''' settings.DEBUG def mail_cronos_admin(title, message): ''' Wrapper function of send_mail ''' try: send_mail(title, message, 'notification@cronos.teilar.gr', [settings.ADMIN[0][1]]) except: pass class CronosError(Exception): ''' Custom Exception class ''' def __init__(self, value): self.value = value def __unicode__(self): return repr(self.value) def log_extra_data(username = None, request = None, form = None, cronjob = None): ''' Extra data needed by the custom formatter All values default to None It provides three data: client_ip, username and cronjob name Username can be passed directly as argument, or it can be retrieved by either the request var or the form ''' log_extra_data = { 'client_ip': request.META.get('REMOTE_ADDR','None') if request else '', 'username': username if username else '', 'cronjob': cronjob if cronjob else '', } if not username: if form: log_extra_data['username'] = form.data.get('username', 'None') else: try: if request.user.is_authenticated(): ''' Handle logged in users ''' log_extra_data['username'] = request.user.name else: ''' Handle anonymous users ''' log_extra_data['username'] = 'Anonymous' except AttributeError: pass return log_extra_data
# -*- coding: utf-8 -*- from django.conf import settings from django.core.mail import send_mail def mail_cronos_admin(title, message): ''' Wrapper function of send_mail ''' try: send_mail(title, message, 'notification@cronos.teilar.gr', [settings.ADMIN[0][1]]) except: pass class CronosError(Exception): ''' Custom Exception class ''' def __init__(self, value): self.value = value def __unicode__(self): return repr(self.value) def log_extra_data(username = None, request = None, form = None, cronjob = None): ''' Extra data needed by the custom formatter All values default to None It provides three data: client_ip, username and cronjob name Username can be passed directly as argument, or it can be retrieved by either the request var or the form ''' log_extra_data = { 'client_ip': request.META.get('REMOTE_ADDR','None') if request else '', 'username': username if username else '', 'cronjob': cronjob if cronjob else '', } if not username: if form: log_extra_data['username'] = form.data.get('username', 'None') else: try: if request.user.is_authenticated(): ''' Handle logged in users ''' log_extra_data['username'] = request.user.name else: ''' Handle anonymous users ''' log_extra_data['username'] = 'Anonymous' except AttributeError: pass return log_extra_data
Python
0.001556
d006711787d018ed401ba003d3472b8a0e843437
Add documentation for ignoring empty strings
stringinfo.py
stringinfo.py
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: stringinfo [options] [--] [STRING]... Options: STRING The strings for which you want information. If none are given, read from stdin upto EOF. Empty strings are ignored. --list List all plugins, with their descriptions and whether they're default or not --all Run all plugins, even the ones that aren't default --verbose Print debugging messages --file INFILE Read inputs from inputfile, removing trailing newlines. BEWARE: leading/trailing whitespace is preserved! Plugins: """ import colorama from docopt import docopt import sys import veryprettytable import plugins from plugins.util import color __author__ = 'peter' def main(): args = docopt(__doc__ + plugins.usage_table()) # Find plugins ps = plugins.get_plugins(args) if args['--list']: table = veryprettytable.VeryPrettyTable() table.field_names = ('Name', 'Default', 'Description') table.align = 'l' for p in ps: table.add_row((p.__name__, color(p.default), p.description)) print(table) return if args['--file']: args['STRING'] = [x.strip('\n\r') for x in open(args['--file'], 'r')] if not args['STRING']: args['STRING'] = [sys.stdin.read()] args['STRING'] = filter(None, args['STRING']) # Initialize colorama colorama.init() # For each plugin, check if it's applicable and if so, run it for p in ps: plugin = p(args) if plugin.sentinel(): print(plugin.header) print(plugin.handle()) else: if args['--verbose']: print('Sentinel failed for {0}'.format(p.__name__)) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: stringinfo [options] [--] [STRING]... Options: STRING The strings for which you want information. If none are given, read from stdin upto EOF. --list List all plugins, with their descriptions and whether they're default or not --all Run all plugins, even the ones that aren't default --verbose Print debugging messages --file INFILE Read inputs from inputfile, removing trailing newlines. BEWARE: leading/trailing whitespace is preserved! Plugins: """ import colorama from docopt import docopt import sys import veryprettytable import plugins from plugins.util import color __author__ = 'peter' def main(): args = docopt(__doc__ + plugins.usage_table()) # Find plugins ps = plugins.get_plugins(args) if args['--list']: table = veryprettytable.VeryPrettyTable() table.field_names = ('Name', 'Default', 'Description') table.align = 'l' for p in ps: table.add_row((p.__name__, color(p.default), p.description)) print(table) return if args['--file']: args['STRING'] = [x.strip('\n\r') for x in open(args['--file'], 'r')] if not args['STRING']: args['STRING'] = [sys.stdin.read()] args['STRING'] = filter(None, args['STRING']) # Initialize colorama colorama.init() # For each plugin, check if it's applicable and if so, run it for p in ps: plugin = p(args) if plugin.sentinel(): print(plugin.header) print(plugin.handle()) else: if args['--verbose']: print('Sentinel failed for {0}'.format(p.__name__)) if __name__ == '__main__': main()
Python
0.000002
a6ac71c7a3c1ac1fd3794a55c47ad86fe014cf73
Update RateLimit.py
Cogs/RateLimit.py
Cogs/RateLimit.py
import asyncio import discord import os import time from datetime import datetime from discord.ext import commands def setup(bot): # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(RateLimit(bot, settings)) # This is the RateLimit module. It keeps users from being able to spam commands class RateLimit: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings self.commandCooldown = 5 # 5 seconds between commands - placeholder, overridden by settings self.maxCooldown = 10 # 10 seconds MAX between commands for cooldown def canRun( self, firstTime, threshold ): # Check if enough time has passed since the last command to run another currentTime = int(time.time()) if currentTime > (int(firstTime) + int(threshold)): return True else: return False async def test_message(self, message): # Implemented to bypass having this called twice return { "Ignore" : False, "Delete" : False } async def message(self, message): # Check the message and see if we should allow it - always yes. # This module doesn't need to cancel messages - but may need to ignore ignore = False # Get current delay try: currDelay = self.settings.serverDict['CommandCooldown'] except KeyError: currDelay = self.commandCooldown # Check if we can run commands lastTime = int(self.settings.getUserStat(message.author, message.guild, "LastCommand")) # None fix if lastTime == None: lastTime = 0 if not self.canRun( lastTime, currDelay ): # We can't run commands yet - ignore ignore = True return { 'Ignore' : ignore, 'Delete' : False } async def oncommand(self, ctx): # Let's grab the user who had a completed command - and set the timestamp self.settings.setUserStat(ctx.message.author, ctx.message.guild, "LastCommand", int(time.time())) @commands.command(pass_context=True) async def ccooldown(self, ctx, delay : int = None): """Sets the cooldown in seconds between each command (owner only).""" channel = ctx.message.channel author = ctx.message.author server = ctx.message.guild # Only allow owner isOwner = self.settings.isOwner(ctx.author) if isOwner == None: msg = 'I have not been claimed, *yet*.' await ctx.channel.send(msg) return elif isOwner == False: msg = 'You are not the *true* owner of me. Only the rightful owner can use this command.' await ctx.channel.send(msg) return # Get current delay try: currDelay = self.settings.serverDict['CommandCooldown'] except KeyError: currDelay = self.commandCooldown if delay == None: if currDelay == 1: await ctx.channel.send('Current command cooldown is *1 second.*') else: await ctx.channel.send('Current command cooldown is *{} seconds.*'.format(currDelay)) return try: delay = int(delay) except Exception: await ctx.channel.send('Cooldown must be an int.') return if delay < 0: await ctx.channel.send('Cooldown must be at least *0 seconds*.') return if delay > self.maxCooldown: if self.maxCooldown == 1: await ctx.channel.send('Cooldown cannot be more than *1 second*.') else: await ctx.channel.send('Cooldown cannot be more than *{} seconds*.'.format(self.maxCooldown)) return self.settings.serverDict['CommandCooldown'] = delay if delay == 1: await ctx.channel.send('Current command cooldown is now *1 second.*') else: await ctx.channel.send('Current command cooldown is now *{} seconds.*'.format(delay))
import asyncio import discord import os import time from datetime import datetime from discord.ext import commands def setup(bot): # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(RateLimit(bot, settings)) # This is the RateLimit module. It keeps users from being able to spam commands class RateLimit: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings self.commandCooldown = 5 # 5 seconds between commands - placeholder, overridden by settings self.maxCooldown = 10 # 10 seconds MAX between commands for cooldown def canRun( self, firstTime, threshold ): # Check if enough time has passed since the last command to run another currentTime = int(time.time()) if currentTime > (int(firstTime) + int(threshold)): return True else: return False async def test_message(self, message): # Implemented to bypass having this called twice return { "Ignore" : False, "Delete" : False } async def message(self, message): # Check the message and see if we should allow it - always yes. # This module doesn't need to cancel messages - but may need to ignore ignore = False # Get current delay try: currDelay = self.settings.serverDict['CommandCooldown'] except KeyError: currDelay = self.commandCooldown # Check if we can run commands lastTime = int(self.settings.getUserStat(message.author, message.guild, "LastCommand")) if not self.canRun( lastTime, currDelay ): # We can't run commands yet - ignore ignore = True return { 'Ignore' : ignore, 'Delete' : False } async def oncommand(self, ctx): # Let's grab the user who had a completed command - and set the timestamp self.settings.setUserStat(ctx.message.author, ctx.message.guild, "LastCommand", int(time.time())) @commands.command(pass_context=True) async def ccooldown(self, ctx, delay : int = None): """Sets the cooldown in seconds between each command (owner only).""" channel = ctx.message.channel author = ctx.message.author server = ctx.message.guild # Only allow owner isOwner = self.settings.isOwner(ctx.author) if isOwner == None: msg = 'I have not been claimed, *yet*.' await ctx.channel.send(msg) return elif isOwner == False: msg = 'You are not the *true* owner of me. Only the rightful owner can use this command.' await ctx.channel.send(msg) return # Get current delay try: currDelay = self.settings.serverDict['CommandCooldown'] except KeyError: currDelay = self.commandCooldown if delay == None: if currDelay == 1: await ctx.channel.send('Current command cooldown is *1 second.*') else: await ctx.channel.send('Current command cooldown is *{} seconds.*'.format(currDelay)) return try: delay = int(delay) except Exception: await ctx.channel.send('Cooldown must be an int.') return if delay < 0: await ctx.channel.send('Cooldown must be at least *0 seconds*.') return if delay > self.maxCooldown: if self.maxCooldown == 1: await ctx.channel.send('Cooldown cannot be more than *1 second*.') else: await ctx.channel.send('Cooldown cannot be more than *{} seconds*.'.format(self.maxCooldown)) return self.settings.serverDict['CommandCooldown'] = delay if delay == 1: await ctx.channel.send('Current command cooldown is now *1 second.*') else: await ctx.channel.send('Current command cooldown is now *{} seconds.*'.format(delay))
Python
0.000001
9e7cd9f13abb29ff8458407b905d522548eaf5c9
Refactor check_executables_have_shebangs for git ls-files reuse
pre_commit_hooks/check_executables_have_shebangs.py
pre_commit_hooks/check_executables_have_shebangs.py
"""Check that executable text files have a shebang.""" import argparse import shlex import sys from typing import Generator from typing import List from typing import NamedTuple from typing import Optional from typing import Sequence from typing import Set from pre_commit_hooks.util import cmd_output from pre_commit_hooks.util import zsplit EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7')) def check_executables(paths: List[str]) -> int: if sys.platform == 'win32': # pragma: win32 cover return _check_git_filemode(paths) else: # pragma: win32 no cover retv = 0 for path in paths: if not has_shebang(path): _message(path) retv = 1 return retv class GitLsFile(NamedTuple): mode: str filename: str def git_ls_files(paths: Sequence[str]) -> Generator[GitLsFile, None, None]: outs = cmd_output('git', 'ls-files', '-z', '--stage', '--', *paths) for out in zsplit(outs): metadata, filename = out.split('\t') mode, _, _ = metadata.split() yield GitLsFile(mode, filename) def _check_git_filemode(paths: Sequence[str]) -> int: seen: Set[str] = set() for ls_file in git_ls_files(paths): is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:]) if is_executable and not has_shebang(ls_file.filename): _message(ls_file.filename) seen.add(ls_file.filename) return int(bool(seen)) def has_shebang(path: str) -> int: with open(path, 'rb') as f: first_bytes = f.read(2) return first_bytes == b'#!' def _message(path: str) -> None: print( f'{path}: marked executable but has no (or invalid) shebang!\n' f" If it isn't supposed to be executable, try: " f'`chmod -x {shlex.quote(path)}`\n' f' If it is supposed to be executable, double-check its shebang.', file=sys.stderr, ) def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('filenames', nargs='*') args = parser.parse_args(argv) return check_executables(args.filenames) if __name__ == '__main__': exit(main())
"""Check that executable text files have a shebang.""" import argparse import shlex import sys from typing import List from typing import Optional from typing import Sequence from typing import Set from pre_commit_hooks.util import cmd_output from pre_commit_hooks.util import zsplit EXECUTABLE_VALUES = frozenset(('1', '3', '5', '7')) def check_executables(paths: List[str]) -> int: if sys.platform == 'win32': # pragma: win32 cover return _check_git_filemode(paths) else: # pragma: win32 no cover retv = 0 for path in paths: if not _check_has_shebang(path): _message(path) retv = 1 return retv def _check_git_filemode(paths: Sequence[str]) -> int: outs = cmd_output('git', 'ls-files', '-z', '--stage', '--', *paths) seen: Set[str] = set() for out in zsplit(outs): metadata, path = out.split('\t') tagmode = metadata.split(' ', 1)[0] is_executable = any(b in EXECUTABLE_VALUES for b in tagmode[-3:]) if is_executable and not _check_has_shebang(path): _message(path) seen.add(path) return int(bool(seen)) def _check_has_shebang(path: str) -> int: with open(path, 'rb') as f: first_bytes = f.read(2) return first_bytes == b'#!' def _message(path: str) -> None: print( f'{path}: marked executable but has no (or invalid) shebang!\n' f" If it isn't supposed to be executable, try: " f'`chmod -x {shlex.quote(path)}`\n' f' If it is supposed to be executable, double-check its shebang.', file=sys.stderr, ) def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('filenames', nargs='*') args = parser.parse_args(argv) return check_executables(args.filenames) if __name__ == '__main__': exit(main())
Python
0
5eeab4e458e7af3895525dcc08017eb855308723
remove extra s typo
autocms/stats.py
autocms/stats.py
"""Harvesting of persistent statsitical records.""" import os import time import importlib from .core import load_records def harvest_default_stats(records, config): """Add a row to the long term statistics record for a given test.""" now = int(time.time()) harvest_time = now - int(config['AUTOCMS_STAT_INTERVAL'])*3600 stat_records = [job for job in records if job.completed and job.end_time > harvest_time] runtimes = [job.run_time() for job in stat_records if job.is_success()] if len(runtimes) == 0: max_runtime = 0 min_runtime = 0 mean_runtime = 0 else: max_runtime = max(runtimes) min_runtime = min(runtimes) mean_runtime = sum(runtimes)/float(len(runtimes)) successes = sum(1 for job in stat_records if job.is_success()) failures = sum(1 for job in stat_records if not job.is_success()) return "{} {} {} {} {} {}".format(now, successes, failures, min_runtime, mean_runtime, max_runtime) def append_stats_row(row, testname, config): """Add a line to the persistent statistics log of a test.""" statfile = os.path.join(config['AUTOCMS_BASEDIR'], testname, 'statistics.dat') with open(statfile, 'a') as stat_handle: stat_handle.write(row + '\n') def perform_stats_harvesting(testname, config): """Analyze job records for given test and create row of statistics.""" records = load_records(testname, config) # use a custom row if the test has configured one harvest_stats = harvest_default_stats try: test_custom = importlib.import_module('autocms.custom.' + testname) if hasattr(test_custom, 'harvest_stats'): harvest_stats = getattr(test_custom, 'produce_webpage') except ImportError: pass row = harvest_stats(records, config) append_stats_row(row, testname, config)
"""Harvesting of persistent statsitical records.""" import os import time import importlib from .core import load_records def harvest_default_stats(records, config): """Add a row to the long term statistics record for a given test.""" now = int(time.time()) harvest_time = now - int(config['AUTOCMS_STAT_INTERVAL'])*3600 stat_records = [job for job in records if job.completed and job.end_time > harvest_time] runtimes = [job.run_time() for job in stat_records if job.is_success()] if len(runtimes) == 0: max_runtime = 0 min_runtime = 0 mean_runtime = 0 else: max_runtime = max(runtimes) min_runtime = min(runtimes) mean_runtime = sum(runtimes)/float(len(runtimes)) successes = sum(1 for job in stat_records if job.is_successs()) failures = sum(1 for job in stat_records if not job.is_successs()) return "{} {} {} {} {} {}".format(now, successes, failures, min_runtime, mean_runtime, max_runtime) def append_stats_row(row, testname, config): """Add a line to the persistent statistics log of a test.""" statfile = os.path.join(config['AUTOCMS_BASEDIR'], testname, 'statistics.dat') with open(statfile, 'a') as stat_handle: stat_handle.write(row + '\n') def perform_stats_harvesting(testname, config): """Analyze job records for given test and create row of statistics.""" records = load_records(testname, config) # use a custom row if the test has configured one harvest_stats = harvest_default_stats try: test_custom = importlib.import_module('autocms.custom.' + testname) if hasattr(test_custom, 'harvest_stats'): harvest_stats = getattr(test_custom, 'produce_webpage') except ImportError: pass row = harvest_stats(records, config) append_stats_row(row, testname, config)
Python
0.999176
c14b5ece7446bb88959b75281ba5dd30c66843ad
Change list command to optionally accept an alternate template directory to search
scriptorium/__main__.py
scriptorium/__main__.py
#!/usr/bin/env python #Script to build a scriptorium paper in a cross-platform friendly fashion import scriptorium import argparse import subprocess import os import os.path import glob import re import shutil import sys BIN_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.abspath(os.path.join(BIN_DIR, '..')) def make(args): """Creates PDF from paper in the requested location.""" pdf = scriptorium.to_pdf(args.paper, use_shell_escape=args.shell_escape) if args.output and pdf != args.output: shutil.move(pdf, args.output) def info(args): """Function to attempt to extract useful information from a specified paper.""" fname = scriptorium.paper_root(args.paper) if not fname: raise IOError('{0} does not contain a valid root document.'.format(args.paper)) if not fname: print('Could not find the root of the paper.') sys.exit(1) if args.template: template = scriptorium.get_template(os.path.join(args.paper, fname)) if not template: print('Could not find footer indicating template name.') sys.exit(2) print(template) def list_cmd(args): """Prints out all installed templates.""" templates = scriptorium.all_templates(args.template_dir) for template in templates: print('{0}'.format(template)) def create(args): """Creates a new paper given flags.""" if not scriptorium.create(args.output, args.template, force=args.force, config=args.config): sys.exit(3) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Make command make_parser = subparsers.add_parser("make") make_parser.add_argument("paper", default=".", help="Directory containing paper to make") make_parser.add_argument('-o', '--output', help='Filename to store resulting PDF as.') make_parser.add_argument('-s', '--shell-escape', action='store_true', help='Flag to indicate shell-escape should be used') make_parser.set_defaults(func=make) info_parser = subparsers.add_parser("info") info_parser.add_argument("paper", default=".", help="Directory containing paper to make") info_parser.add_argument('-t', '--template', action="store_true", help="Flag to extract template") info_parser.set_defaults(func=info) new_parser = subparsers.add_parser("new") new_parser.add_argument("output", help="Directory to create paper in.") new_parser.add_argument("-f", "--force", action="store_true", help="Overwrite files in paper creation.") new_parser.add_argument("-t", "--template", help="Template to use in paper.") new_parser.add_argument("-c", "--config", nargs=2, action='append', default=[], help='Flag to provide options for filling out variables in new papers, in the form key value') new_parser.set_defaults(func=create) list_parser = subparsers.add_parser("list") list_parser.add_argument("-t", "--template_dir", default=scriptorium.TEMPLATES_DIR, help="Overrides template directory used for listing templates") list_parser.set_defaults(func=list_cmd) args = parser.parse_args() if 'func' in args: args.func(args) else: parser.print_help() if __name__ == '__main__': main()
#!/usr/bin/env python #Script to build a scriptorium paper in a cross-platform friendly fashion import scriptorium import argparse import subprocess import os import os.path import glob import re import shutil import sys BIN_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.abspath(os.path.join(BIN_DIR, '..')) def make(args): """Creates PDF from paper in the requested location.""" pdf = scriptorium.to_pdf(args.paper, use_shell_escape=args.shell_escape) if args.output and pdf != args.output: shutil.move(pdf, args.output) def info(args): """Function to attempt to extract useful information from a specified paper.""" fname = scriptorium.paper_root(args.paper) if not fname: raise IOError('{0} does not contain a valid root document.'.format(args.paper)) if not fname: print('Could not find the root of the paper.') sys.exit(1) if args.template: template = scriptorium.get_template(os.path.join(args.paper, fname)) if not template: print('Could not find footer indicating template name.') sys.exit(2) print(template) def list_cmd(args): """Prints out all installed templates.""" templates = scriptorium.all_templates(TEMPLATES_DIR) for template in templates: print('{0}'.format(template)) def create(args): """Creates a new paper given flags.""" if not scriptorium.create(args.output, args.template, force=args.force, config=args.config): sys.exit(3) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Make command make_parser = subparsers.add_parser("make") make_parser.add_argument("paper", default=".", help="Directory containing paper to make") make_parser.add_argument('-o', '--output', help='Filename to store resulting PDF as.') make_parser.add_argument('-s', '--shell-escape', action='store_true', help='Flag to indicate shell-escape should be used') make_parser.set_defaults(func=make) info_parser = subparsers.add_parser("info") info_parser.add_argument("paper", default=".", help="Directory containing paper to make") info_parser.add_argument('-t', '--template', action="store_true", help="Flag to extract template") info_parser.set_defaults(func=info) new_parser = subparsers.add_parser("new") new_parser.add_argument("output", help="Directory to create paper in.") new_parser.add_argument("-f", "--force", action="store_true", help="Overwrite files in paper creation.") new_parser.add_argument("-t", "--template", help="Template to use in paper.") new_parser.add_argument("-c", "--config", nargs=2, action='append', default=[], help='Flag to provide options for filling out variables in new papers, in the form key value') new_parser.set_defaults(func=create) list_parser = subparsers.add_parser("list") list_parser.add_argument("-t", "--template_dir", default=scriptorium.TEMPLATES_DIR, help="Overrides template directory used for listing templates") list_parser.set_defaults(func=list_cmd) args = parser.parse_args() if 'func' in args: args.func(args) else: parser.print_help() if __name__ == '__main__': main()
Python
0
2d392d8c107c9055e6b62bb365158b1001872cde
Fix deprecation warnings.
emdp/analytic.py
emdp/analytic.py
""" Tools to get analytic solutions from MDPs """ import numpy as np def calculate_P_pi(P, pi): r""" calculates P_pi P_pi(s,t) = \sum_a pi(s,a) p(s, a, t) :param P: transition matrix of size |S|x|A|x|S| :param pi: matrix of size |S| x |A| indicating the policy :return: a matrix of size |S| x |S| """ return np.einsum('sat,sa->st', P, pi) def calculate_R_pi(R, pi): r""" calculates R_pi R_pi(s) = \sum_a pi(s,a) r(s,a) :param R: reward matrix of size |S| x |A| :param pi: matrix of size |S| x |A| indicating the policy :return: """ return np.einsum('sa,sa->s', R, pi) def calculate_successor_representation(P_pi, gamma): """ Calculates the successor representation (I- gamma*P_pi)^{-1} :param P_pi: :param gamma: :return: """ return np.linalg.inv(np.eye(P_pi.shape[0]) - gamma * P_pi) def calculate_V_pi_from_successor_representation(Phi, R_pi): return np.einsum('st,t->s', Phi, R_pi) def calculate_V_pi(P, R, pi, gamma): r""" Calculates V_pi from the successor representation using the analytic form: (I- gamma*P_pi)^{-1} * R_pi where P_pi(s,t) = \sum_a pi(s,a) p(s, a, t) and R_pi(s) = \sum_a pi(s,a) r(s,a) :param P: Transition matrix :param R: Reward matrix :param pi: policy matrix :param gamma: discount factor :return: """ P_pi = calculate_P_pi(P, pi) R_pi = calculate_R_pi(R, pi) Phi = calculate_successor_representation(P_pi, gamma) return calculate_V_pi_from_successor_representation(Phi, R_pi)
""" Tools to get analytic solutions from MDPs """ import numpy as np def calculate_P_pi(P, pi): """ calculates P_pi P_pi(s,t) = \sum_a pi(s,a) p(s, a, t) :param P: transition matrix of size |S|x|A|x|S| :param pi: matrix of size |S| x |A| indicating the policy :return: a matrix of size |S| x |S| """ return np.einsum('sat,sa->st', P, pi) def calculate_R_pi(R, pi): """ calculates R_pi R_pi(s) = \sum_a pi(s,a) r(s,a) :param R: reward matrix of size |S| x |A| :param pi: matrix of size |S| x |A| indicating the policy :return: """ return np.einsum('sa,sa->s', R, pi) def calculate_successor_representation(P_pi, gamma): """ Calculates the successor representation (I- gamma*P_pi)^{-1} :param P_pi: :param gamma: :return: """ return np.linalg.inv(np.eye(P_pi.shape[0]) - gamma * P_pi) def calculate_V_pi_from_successor_representation(Phi, R_pi): return np.einsum('st,t->s', Phi, R_pi) def calculate_V_pi(P, R, pi, gamma): """ Calculates V_pi from the successor representation using the analytic form: (I- gamma*P_pi)^{-1} * R_pi where P_pi(s,t) = \sum_a pi(s,a) p(s, a, t) and R_pi(s) = \sum_a pi(s,a) r(s,a) :param P: Transition matrix :param R: Reward matrix :param pi: policy matrix :param gamma: discount factor :return: """ P_pi = calculate_P_pi(P, pi) R_pi = calculate_R_pi(R, pi) Phi = calculate_successor_representation(P_pi, gamma) return calculate_V_pi_from_successor_representation(Phi, R_pi)
Python
0.000002
c8f774ea3455af057736166757f831407711ae67
Bump to 0.4.
emds/__init__.py
emds/__init__.py
__version__ = '0.4'
__version__ = '0.3'
Python
0.000001
033ec1c5c7d44c54136541aa0e1bd8c73e3c1163
update test_unitcell
test/test_unitCell.py
test/test_unitCell.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from udkm1Dsim.atoms import Atom from udkm1Dsim.unitCell import UnitCell from pint import UnitRegistry u = UnitRegistry() u.default_format = '~P' from numpy import array def test_unit_cell(): Fe = Atom('Fe') uc = UnitCell('uc', 'Unit Cell', 2.86*u.angstrom, heat_capacity=10*(u.J/u.kg/u.K), lin_therm_exp=1e-6/u.K, therm_cond=1*(u.W/u.m/u.K), opt_pen_depth=11*u.nm, sound_vel=5*(u.nm/u.ps)) uc.add_atom(Fe, 'lambda strain: 0*(strain+1)') uc.add_atom(Fe, 'lambda strain: 0.5*(strain+1)') assert uc.id == 'uc' assert uc.name == 'Unit Cell' assert uc.a_axis == 2.86*u.angstrom assert uc.b_axis == 2.86*u.angstrom assert uc.c_axis == 2.86*u.angstrom assert uc.heat_capacity[0](300) == 10 assert uc.int_heat_capacity[0](300) == 3000 assert uc.lin_therm_exp[0](300) == 1e-6 assert uc.int_lin_therm_exp[0](300) == 0.0003 assert uc.therm_cond[0](300) == 1 assert uc.opt_pen_depth == 11*u.nm assert uc.sound_vel == 5*(u.nm/u.ps)
#!/usr/bin/env python # -*- coding: utf-8 -*- from udkm1Dsim.atoms import Atom from udkm1Dsim.unitCell import UnitCell from pint import UnitRegistry u = UnitRegistry() u.default_format = '~P' from numpy import array def test_unit_cell(): Fe = Atom('Fe') uc = UnitCell('uc', 'Unit Cell', 2.86*u.angstrom, heat_capacity=10*(u.J/u.kg/u.K), lin_therm_exp=1e-6/u.K, therm_cond=1*(u.W/u.m/u.K), opt_pen_depth=11*u.nm, sound_vel=5*(u.nm/u.ps)) uc.add_atom(Fe, 'lambda strain: 0*(strain+1)') uc.add_atom(Fe, 'lambda strain: 0.5*(strain+1)') assert uc.id == 'uc' assert uc.name == 'Unit Cell' assert uc.a_axis == 2.86*u.angstrom assert uc.b_axis == 2.86*u.angstrom assert uc.c_axis == 2.86*u.angstrom assert uc.heat_capacity[0](300) == 10 assert uc.int_heat_capacity[0](300) == 3000 assert uc.lin_therm_exp[0](300) == 1e-6 assert uc.int_lin_therm_exp[0](300) == 0.0003 assert uc.therm_cond[0](300) == 1 assert uc.opt_pen_depth == 11*u.nm assert uc.sound_vel == 5*(u.nm/u.ps) assert uc.get_property_dict(types='phonon') == {'_c_axis': 2.86e-10, '_mass': 2.2674165653283783e-26, '_phonon_damping': 0.0, 'int_lin_therm_exp_str': ['lambda T : 1.0e-6*T'], 'spring_const': array([6]), 'num_sub_systems': 1}
Python
0.000001
b6d161e54e9b398f79f417ac14ec65e5fdb609d3
remove pre tag in emit init
emit/__init__.py
emit/__init__.py
__version__ = '0.4.0' from emit.router.core import Router
__version__ = '0.4.0pre' from emit.router.core import Router
Python
0
19fa44530adf1fd5456a0be93ea0dddd7e43eb8c
Remove junk import.
Cli_server_tcp.py
Cli_server_tcp.py
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved. # # 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 twisted.internet.protocol import Factory from twisted.internet import reactor from Cli_session import Cli_session class Cli_server_tcp(Factory): command_cb = None lport = None accept_list = None def __init__(self, command_cb, address): self.command_cb = command_cb self.protocol = Cli_session self.lport = reactor.listenTCP(address[1], self, interface = address[0]) def buildProtocol(self, addr): if self.accept_list != None and addr.host not in self.accept_list: return None p = Factory.buildProtocol(self, addr) p.command_cb = self.command_cb p.raddr = addr return p def shutdown(self): self.lport.stopListening() if __name__ == '__main__': def callback(clm, cmd): print cmd return False laddr = ('127.0.0.1', 12345) f = Cli_server_tcp(callback, laddr) reactor.run()
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved. # # 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 twisted.internet.protocol import Factory from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from Cli_session import Cli_session class Cli_server_tcp(Factory): command_cb = None lport = None accept_list = None def __init__(self, command_cb, address): self.command_cb = command_cb self.protocol = Cli_session self.lport = reactor.listenTCP(address[1], self, interface = address[0]) def buildProtocol(self, addr): if self.accept_list != None and addr.host not in self.accept_list: return None p = Factory.buildProtocol(self, addr) p.command_cb = self.command_cb p.raddr = addr return p def shutdown(self): self.lport.stopListening() if __name__ == '__main__': def callback(clm, cmd): print cmd return False laddr = ('127.0.0.1', 12345) f = Cli_server_tcp(callback, laddr) reactor.run()
Python
0
fbba7f7c32f4b587efba2e72c051996d4a69f567
Update example local_settings votigns per page
website/local_settings_example.py
website/local_settings_example.py
# user settings, included in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True # SECURITY WARNING: Make this unique, and don't share it with anybody. SECRET_KEY = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(BASE_DIR, 'openkamer.sqlite'), # Or path to database file if using sqlite3. } } LANGUAGE_CODE = 'nl-NL' TIME_ZONE = "Europe/Amsterdam" ALLOWED_HOSTS = ['*'] #STATIC_ROOT = '/home/username/webapps/openkamerstatic/' STATIC_ROOT = '' # URL prefix for static files. #STATIC_URL = '//www.openkamer.org/static/' STATIC_URL = '/static/' #MEDIA_ROOT = '/home/<username>/webapps/<projectstatic>/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'website/static/media/') #MEDIA_URL = '//www.<your-domain>.com/static/media/' MEDIA_URL = '/static/media/' # DBBACKUP DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': os.path.join(BASE_DIR, STATIC_ROOT, 'backup/')} # DJANGO-CRON CRON_LOCK_DIR = '/tmp' CRON_CLASSES = [ # 'website.cron.TestJob', 'website.cron.BackupDaily', 'website.cron.CleanUnusedPersons', # 'website.cron.UpdateSubmitters' # 'website.cron.UpdateParliamentAndGovernment', # 'website.cron.UpdateActiveDossiers', # 'website.cron.UpdateInactiveDossiers', # 'website.cron.UpdateVerslagenAlgemeenOverleg', # 'website.cron.UpdateKamervragenRecent', # 'website.cron.UpdateKamervragenAll', # 'oktwitter.cron.UpdateTwitterLists', # 'website.cron.UpdateStatsData', # 'website.cron.UpdateGifts', # 'website.cron.UpdateTravels', # 'website.cron.UpdateSearchIndex', ] # OPENKAMER CONTACT_EMAIL = 'info@openkamer.org' OK_TMP_DIR = os.path.join(BASE_DIR, 'data/tmp/') # DOCUMENT NUMBER_OF_LATEST_DOSSIERS = 6 AGENDAS_PER_PAGE = 50 DOSSIERS_PER_PAGE = 20 VOTINGS_PER_PAGE = 20 BESLUITENLIJSTEN_PER_PAGE = 200 # PIWIK PIWIK_URL = '' # optional, without trailing slash PIWIK_SITE_ID = 0 # TWEEDEKAMER DATA REPO GIT_AUTHOR_NAME = '' GIT_AUTHOR_EMAIL = '' DATA_REPO_DIR = '<path-to-repo>/ok-tk-data/' # TWITTER TWITTER_CONSUMER_KEY = '' TWITTER_CONSUMER_SECRET = '' TWITTER_ACCESS_TOKEN_KEY = '' TWITTER_ACCESS_TOKEN_SECRET = ''
# user settings, included in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True # SECURITY WARNING: Make this unique, and don't share it with anybody. SECRET_KEY = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(BASE_DIR, 'openkamer.sqlite'), # Or path to database file if using sqlite3. } } LANGUAGE_CODE = 'nl-NL' TIME_ZONE = "Europe/Amsterdam" ALLOWED_HOSTS = ['*'] #STATIC_ROOT = '/home/username/webapps/openkamerstatic/' STATIC_ROOT = '' # URL prefix for static files. #STATIC_URL = '//www.openkamer.org/static/' STATIC_URL = '/static/' #MEDIA_ROOT = '/home/<username>/webapps/<projectstatic>/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'website/static/media/') #MEDIA_URL = '//www.<your-domain>.com/static/media/' MEDIA_URL = '/static/media/' # DBBACKUP DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': os.path.join(BASE_DIR, STATIC_ROOT, 'backup/')} # DJANGO-CRON CRON_LOCK_DIR = '/tmp' CRON_CLASSES = [ # 'website.cron.TestJob', 'website.cron.BackupDaily', 'website.cron.CleanUnusedPersons', # 'website.cron.UpdateSubmitters' # 'website.cron.UpdateParliamentAndGovernment', # 'website.cron.UpdateActiveDossiers', # 'website.cron.UpdateInactiveDossiers', # 'website.cron.UpdateVerslagenAlgemeenOverleg', # 'website.cron.UpdateKamervragenRecent', # 'website.cron.UpdateKamervragenAll', # 'oktwitter.cron.UpdateTwitterLists', # 'website.cron.UpdateStatsData', # 'website.cron.UpdateGifts', # 'website.cron.UpdateTravels', # 'website.cron.UpdateSearchIndex', ] # OPENKAMER CONTACT_EMAIL = 'info@openkamer.org' OK_TMP_DIR = os.path.join(BASE_DIR, 'data/tmp/') # DOCUMENT NUMBER_OF_LATEST_DOSSIERS = 6 AGENDAS_PER_PAGE = 50 DOSSIERS_PER_PAGE = 20 VOTINGS_PER_PAGE = 25 BESLUITENLIJSTEN_PER_PAGE = 200 # PIWIK PIWIK_URL = '' # optional, without trailing slash PIWIK_SITE_ID = 0 # TWEEDEKAMER DATA REPO GIT_AUTHOR_NAME = '' GIT_AUTHOR_EMAIL = '' DATA_REPO_DIR = '<path-to-repo>/ok-tk-data/' # TWITTER TWITTER_CONSUMER_KEY = '' TWITTER_CONSUMER_SECRET = '' TWITTER_ACCESS_TOKEN_KEY = '' TWITTER_ACCESS_TOKEN_SECRET = ''
Python
0
0070417e170ff67248918243d6aaea248a5d024c
Fix Q3 in exercise 6 checking code
learntools/computer_vision/ex6.py
learntools/computer_vision/ex6.py
from learntools.core import * import tensorflow as tf # Free class Q1(CodingProblem): _solution = "" _hint = "" def check(self): pass class Q2A(ThoughtExperiment): _hint = "Remember that whatever transformation you apply needs at least to keep the classes distinct, but otherwise should more or less keep the appearance of the images the same. If you rotated a picture of a forest, would it still look like a forest?" _solution = """It seems to this author that any of the transformations from the first problem might be appropriate, provided the parameter values were reasonable. A picture of a forest that had been rotated or shifted or stretched would still look like a forest, and contrast adjustments could perhaps make up for differences in light and shadow. Rotations especially could be taken through the full range, since there's no real concept of "up or down" for pictures taken straight overhead.""" class Q2B(ThoughtExperiment): _hint = "Remember that whatever transformation you apply needs at least to keep the classes distinct, but otherwise should more or less keep the appearance of the images the same. If you rotated a picture of a forest, would it still look like a forest?" _solution = "It seems to this author that any of the transformations from the first problem might be appropriate, provided the parameter values were reasonable. A picture of a forest that had been rotated or shifted or stretched would still look like a forest, and contrast adjustments could perhaps make up for differences in light and shadow." Q2 = MultipartProblem(Q2A, Q2B) class Q3(CodingProblem): _solution = "" _hint = "" def check(self): pass qvars = bind_exercises(globals(), [ Q1, Q2, Q3, ], var_format='q_{n}', ) __all__ = list(qvars)
from learntools.core import * import tensorflow as tf # Free class Q1(CodingProblem): _solution = "" _hint = "" def check(self): pass class Q2A(ThoughtExperiment): _hint = "Remember that whatever transformation you apply needs at least to keep the classes distinct, but otherwise should more or less keep the appearance of the images the same. If you rotated a picture of a forest, would it still look like a forest?" _solution = """It seems to this author that any of the transformations from the first problem might be appropriate, provided the parameter values were reasonable. A picture of a forest that had been rotated or shifted or stretched would still look like a forest, and contrast adjustments could perhaps make up for differences in light and shadow. Rotations especially could be taken through the full range, since there's no real concept of "up or down" for pictures taken straight overhead.""" class Q2B(ThoughtExperiment): _hint = "Remember that whatever transformation you apply needs at least to keep the classes distinct, but otherwise should more or less keep the appearance of the images the same. If you rotated a picture of a forest, would it still look like a forest?" _solution = "It seems to this author that any of the transformations from the first problem might be appropriate, provided the parameter values were reasonable. A picture of a forest that had been rotated or shifted or stretched would still look like a forest, and contrast adjustments could perhaps make up for differences in light and shadow." Q2 = MultipartProblem(Q2A, Q2B) class Q3(CodingProblem): pass qvars = bind_exercises(globals(), [ Q1, Q2, Q3, ], var_format='q_{n}', ) __all__ = list(qvars)
Python
0.000001
f178b2378661a25cebe9753cf84d6ea9f3c081a8
Improve doc for MultivalueEnum.
enum34_custom.py
enum34_custom.py
from enum import Enum, EnumMeta from functools import total_ordering class _MultiValueMeta(EnumMeta): def __init__(self, cls, bases, classdict): # make sure we only have tuple values, not single values for member in self.__members__.values(): if not isinstance(member.value, tuple): raise TypeError('{} = {!r}, should be tuple!' .format(member.name, member.value)) def __call__(cls, value): """Return the appropriate instance with any of the values listed.""" for member in cls: if value in member.value: return member else: raise ValueError("%s is not a valid %s" % (value, cls.__name__)) class MultiValueEnum(Enum, metaclass=_MultiValueMeta): """Enum subclass where members can have multiple values. You can reference a member by any of its value in the associated tuple. """ @total_ordering class OrderableMixin: """Mixin for comparable Enums. The order is the definition order from smaller to bigger. """ def __eq__(self, other): if self.__class__ is other.__class__: return self.value == other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: names = self.__class__._member_names_ return names.index(self.name) < names.index(other.name) return NotImplemented
from enum import Enum, EnumMeta from functools import total_ordering class _MultiValueMeta(EnumMeta): def __init__(self, cls, bases, classdict): # make sure we only have tuple values, not single values for member in self.__members__.values(): if not isinstance(member.value, tuple): raise TypeError('{} = {!r}, should be tuple!' .format(member.name, member.value)) def __call__(cls, value): """Return the appropriate instance with any of the values listed.""" for member in cls: if value in member.value: return member else: raise ValueError("%s is not a valid %s" % (value, cls.__name__)) class MultiValueEnum(Enum, metaclass=_MultiMeta): """Enum subclass where members are declared as tuples.""" @total_ordering class OrderableMixin: """Mixin for comparable Enums. The order is the definition order from smaller to bigger. """ def __eq__(self, other): if self.__class__ is other.__class__: return self.value == other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: names = self.__class__._member_names_ return names.index(self.name) < names.index(other.name) return NotImplemented
Python
0
cf472cc43c4473ad7403bda64302d1170ee6874e
Save user timezone
controllers/preferences.py
controllers/preferences.py
from pytz.gae import pytz from bo import * from database.person import * class ShowPreferences(boRequestHandler): def get(self): self.view('preferences', 'preferences.html', { 'person': Person().current, 'preferences': UserPreferences().current, 'timezones': pytz.common_timezones, }) def post(self): field = self.request.get('field').strip() value = self.request.get('value').strip() UserPreferences().set(field, value) def main(): Route([ ('/preferences', ShowPreferences), ]) if __name__ == '__main__': main()
from bo import * from database import * class ShowPreferences(boRequestHandler): def get(self): self.view('preferences', 'preferences.html', { 'person': Person().current, 'preferences': UserPreferences().current, }) def post(self): UserPreferences().set_language(self.request.get('language')) def main(): Route([ ('/preferences', ShowPreferences), ]) if __name__ == '__main__': main()
Python
0.000001
ab4cc4fb85c8616de0be53d0a95ad8096ac0cc0c
set up the page and layout for Dashboard:Team Application Overview
Dashboard/urls.py
Dashboard/urls.py
from django.conf.urls import url # View Imports from . import views app_name = "dashboard" urlpatterns = [ url(r'^$', views.DashboardIndex.as_view(), name='index'), url(r'^experts/$', views.expert_management, name='manage_experts'), url(r'^experts/(?P<username>.+)/$', views.expert_management, name="expert_detail"), url(r'^sessions/$', views.SessionManagement.as_view(), name="manage_sessions"), url(r'^teams/$', views.applicationoverview_team, name='manage_teams'), url(r'^teams/(?P<slug>[-\w]+)/$', views.team_management, name='team_detail'), url(r'^venues/$', views.VenueManagement.as_view(), name='manage_venues'), url(r'^venues/(?P<slug>[-\w]+)/$', views.VenueManagement.as_view(), name='manage_venue_detail'), url(r'^shifts/$', views.ShiftManagement.as_view(), name='manage_shifts'), ]
from django.conf.urls import url # View Imports from . import views app_name = "dashboard" urlpatterns = [ url(r'^$', views.DashboardIndex.as_view(), name='index'), url(r'^experts/$', views.expert_management, name='manage_experts'), url(r'^experts/(?P<username>.+)/$', views.expert_management, name="expert_detail"), url(r'^sessions/$', views.SessionManagement.as_view(), name="manage_sessions"), url(r'^teams/$', views.applicationoverview_team, name='manage_teams'), url(r'^teams/(?P<slug>.+)/$', views.team_management, name='team_detail'), url(r'^venues/$', views.VenueManagement.as_view(), name='manage_venues'), url(r'^venues/(?P<slug>[-\w]+)/$', views.VenueManagement.as_view(), name='manage_venue_detail'), url(r'^shifts/$', views.ShiftManagement.as_view(), name='manage_shifts'), ]
Python
0
f0bec02a6e2516ffd11d43b089576c0463d8d51f
Update denormalizer
project/apps/api/management/commands/denormalize.py
project/apps/api/management/commands/denormalize.py
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Appearance, Performance, Group, Singer, Director, Judge, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v in vs: v.save() ts = Contest.objects.all() for t in ts: t.save() cs = Contestant.objects.all() for c in cs: c.save() as_ = Appearance.objects.all() for a in as_: a.save() ps = Performance.objects.all() for p in ps: p.save() ss = Singer.objects.all() for s in ss: s.save() js = Judge.objects.all() for j in js: j.save() ds = Director.objects.all() for d in ds: d.save() return "Done"
from django.core.management.base import ( BaseCommand, ) from apps.api.models import ( Convention, Contest, Contestant, Performance, Group, Person, Singer, Director, ) class Command(BaseCommand): help = "Command to denormailze data." def handle(self, *args, **options): vs = Convention.objects.all() for v in vs: v.save() ts = Contest.objects.all() for t in ts: t.save() cs = Contestant.objects.all() for c in cs: c.save() ps = Performance.objects.all() for p in ps: p.save() gs = Group.objects.all() for g in gs: g.save() rs = Person.objects.all() for r in rs: r.save() ss = Singer.objects.all() for s in ss: s.save() ds = Director.objects.all() for d in ds: d.save() return "Done"
Python
0.000027
eab481546044bc995eca3dc7d3094c7917d19c20
Remove hack to make test work on Jenkins, since it still fails.
src/zeit/content/article/edit/browser/tests/test_social.py
src/zeit/content/article/edit/browser/tests/test_social.py
import zeit.cms.testing import zeit.content.article.edit.browser.testing import zeit.content.article.testing class SocialFormTest(zeit.cms.testing.BrowserTestCase): layer = zeit.content.article.testing.LAYER def setUp(self): super(SocialFormTest, self).setUp() self.browser.open( 'http://localhost/++skin++vivi/repository/' 'online/2007/01/Somalia/@@checkout') def get_article(self): with zeit.cms.testing.site(self.getRootFolder()): with zeit.cms.testing.interaction(): return zeit.cms.interfaces.ICMSWCContent( 'http://xml.zeit.de/online/2007/01/Somalia') def open_form(self): # XXX A simple browser.reload() does not work, why? self.browser.open( 'http://localhost/++skin++vivi/workingcopy/zope.user/' 'Somalia/@@edit.form.social?show_form=1') def test_smoke_form_submit_stores_values(self): self.open_form() b = self.browser self.assertFalse(b.getControl('Enable Twitter', index=0).selected) b.getControl('Enable Twitter', index=0).selected = True b.getControl('Apply').click() article = self.get_article() push = zeit.push.interfaces.IPushMessages(article) self.assertIn( {'type': 'twitter', 'enabled': True, 'account': 'twitter-test'}, push.message_config) class SocialAMPTest(zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(SocialAMPTest, self).setUp() self.add_article() def test_AMP_is_disabled_after_choosing_non_free_access(self): s = self.selenium s.click('css=#edit-form-socialmedia .fold-link') s.waitForVisible('css=#social\.is_amp') self.assertEqual(True, s.isEditable('css=#social\.is_amp')) s.check('css=#social\.is_amp') s.click('css=#edit-form-metadata .fold-link') s.waitForVisible('css=#form-metadata-access select') s.select('css=#form-metadata-access select', 'label=abopflichtig') s.type('css=#form-metadata-access select', '\t') s.waitForElementNotPresent('css=#form-metadata-access .dirty') s.waitForElementPresent('css=.fieldname-is_amp .checkboxdisabled') self.assertEqual(False, s.isEditable('css=#social\.is_amp'))
import zeit.cms.testing import zeit.content.article.edit.browser.testing import zeit.content.article.testing class SocialFormTest(zeit.cms.testing.BrowserTestCase): layer = zeit.content.article.testing.LAYER def setUp(self): super(SocialFormTest, self).setUp() self.browser.open( 'http://localhost/++skin++vivi/repository/' 'online/2007/01/Somalia/@@checkout') def get_article(self): with zeit.cms.testing.site(self.getRootFolder()): with zeit.cms.testing.interaction(): return zeit.cms.interfaces.ICMSWCContent( 'http://xml.zeit.de/online/2007/01/Somalia') def open_form(self): # XXX A simple browser.reload() does not work, why? self.browser.open( 'http://localhost/++skin++vivi/workingcopy/zope.user/' 'Somalia/@@edit.form.social?show_form=1') def test_smoke_form_submit_stores_values(self): self.open_form() b = self.browser self.assertFalse(b.getControl('Enable Twitter', index=0).selected) b.getControl('Enable Twitter', index=0).selected = True b.getControl('Apply').click() article = self.get_article() push = zeit.push.interfaces.IPushMessages(article) self.assertIn( {'type': 'twitter', 'enabled': True, 'account': 'twitter-test'}, push.message_config) class SocialAMPTest(zeit.content.article.edit.browser.testing.EditorTestCase): def setUp(self): super(SocialAMPTest, self).setUp() self.add_article() def test_AMP_is_disabled_after_choosing_non_free_access(self): s = self.selenium s.click('css=#edit-form-socialmedia .fold-link') s.waitForVisible('css=#social\.is_amp') self.assertEqual(True, s.isEditable('css=#social\.is_amp')) s.check('css=#social\.is_amp') s.click('css=#edit-form-metadata .fold-link') s.waitForVisible('css=#form-metadata-access select') s.select('css=#form-metadata-access select', 'label=abopflichtig') s.type('css=#form-metadata-access select', '\t') # Autosave sometimes not triggered on Jenkins unless \t is typed twice try: s.waitForElementNotPresent('css=#form-metadata-access .dirty') except AssertionError: s.type('css=#form-metadata-access select', '\t') s.waitForElementNotPresent('css=#form-metadata-access .dirty') s.waitForElementPresent('css=.fieldname-is_amp .checkboxdisabled') self.assertEqual(False, s.isEditable('css=#social\.is_amp'))
Python
0
60e2503bde822fdcea91c3d0a8e6ddb0f67d0d79
update scripts
scripts/deploy_repos.py
scripts/deploy_repos.py
#!/usr/bin/env python import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, "core")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmudbac.settings") import django django.setup() from django.db.models import Q from library.models import * import utils def main(): if len(sys.argv) != 3: return deploy_id = int(sys.argv[1]) total_deployer = int(sys.argv[2]) database = Database.objects.get(name='MySQL') for repo in Repository.objects.filter(project_type = 3): # for repo in Repository.objects.filter(project_type = 1).filter(latest_attempt__result = 'OK').filter(latest_attempt__log__contains = "[Errno 13] Permission denied: '/var/log/mysql/mysql.log'"): if repo.id % total_deployer != deploy_id - 1: continue n = len(Attempt.objects.filter(repo = repo).filter(result = 'OK')) if n == 0: continue print 'Attempting to deploy {} using {} ...'.format(repo, repo.project_type.deployer_class) try: utils.vagrant_deploy(repo, deploy_id, database) except: pass if __name__ == '__main__': main()
#!/usr/bin/env python import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, "core")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmudbac.settings") import django django.setup() from django.db.models import Q from library.models import * import utils def main(): if len(sys.argv) != 3: return deploy_id = int(sys.argv[1]) total_deployer = int(sys.argv[2]) database = Database.objects.get(name='MySQL') for repo in Repository.objects.filter(project_type = 3).filter(Q(latest_attempt__result = 'DE') | Q(latest_attempt__result = 'OK')): # for repo in Repository.objects.filter(project_type = 1).filter(latest_attempt__result = 'OK').filter(latest_attempt__log__contains = "[Errno 13] Permission denied: '/var/log/mysql/mysql.log'"): if repo.id % total_deployer != deploy_id - 1: continue print 'Attempting to deploy {} using {} ...'.format(repo, repo.project_type.deployer_class) try: utils.vagrant_deploy(repo, deploy_id, database) except: pass if __name__ == '__main__': main()
Python
0.000001
bca6f6041e9f49d1d25d7a9c4cb88080d88c45b1
Comment concerning differences in keys per path
dumper/invalidation.py
dumper/invalidation.py
import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): ''' Each path can actually have multiple cached entries, varying based on different HTTP methods. So a GET request will have a different cached response from a HEAD request. In order to invalidate a path, we must first know all the different cache keys that the path might have been cached at. This returns those keys ''' return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
import dumper.utils def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): dumper.utils.cache.delete(key) def all_cache_keys_from_path(path): return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
Python
0
d649ff7c1d63c33c1ea25a1d3916b441e7ccc6ea
Add backwards compatible ctor for HttpChallange
azure-keyvault/azure/keyvault/custom/http_challenge.py
azure-keyvault/azure/keyvault/custom/http_challenge.py
#--------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #--------------------------------------------------------------------------------------------- try: import urllib.parse as parse except ImportError: import urlparse as parse # pylint: disable=import-error class HttpChallenge(object): def __init__(self, request_uri, challenge, response_headers=None): """ Parses an HTTP WWW-Authentication Bearer challenge from a server. """ self.source_authority = self._validate_request_uri(request_uri) self.source_uri = request_uri self._parameters = {} # get the scheme of the challenge and remove from the challenge string trimmed_challenge = self._validate_challenge(challenge) split_challenge = trimmed_challenge.split(' ', 1) self.scheme = split_challenge[0] trimmed_challenge = split_challenge[1] # split trimmed challenge into comma-separated name=value pairs. Values are expected # to be surrounded by quotes which are stripped here. for item in trimmed_challenge.split(','): # process name=value pairs comps = item.split('=') if len(comps) == 2: key = comps[0].strip(' "') value = comps[1].strip(' "') if key: self._parameters[key] = value # minimum set of parameters if not self._parameters: raise ValueError('Invalid challenge parameters') # must specify authorization or authorization_uri if 'authorization' not in self._parameters and 'authorization_uri' not in self._parameters: raise ValueError('Invalid challenge parameters') # if the response headers were supplied if response_headers: # get the message signing key and message key encryption key from the headers self.server_signature_key = response_headers.get('x-ms-message-signing-key', None) self.server_encryption_key = response_headers.get('x-ms-message-encryption-key', None) def is_bearer_challenge(self): """ Tests whether the HttpChallenge a Bearer challenge. rtype: bool """ if not self.scheme: return False return self.scheme.lower() == 'bearer' def is_pop_challenge(self): """ Tests whether the HttpChallenge is a proof of possession challenge. rtype: bool """ if not self.scheme: return False return self.scheme.lower() == 'pop' def get_value(self, key): return self._parameters.get(key) def get_authorization_server(self): """ Returns the URI for the authorization server if present, otherwise empty string. """ value = '' for key in ['authorization_uri', 'authorization']: value = self.get_value(key) or '' if value: break return value def get_resource(self): """ Returns the resource if present, otherwise empty string. """ return self.get_value('resource') or '' def get_scope(self): """ Returns the scope if present, otherwise empty string. """ return self.get_value('scope') or '' def supports_pop(self): """ Returns True if challenge supports pop token auth else False """ return self._parameters.get('supportspop', None) == 'true' def supports_message_protection(self): """ Returns True if challenge vault supports message protection """ return True if self.supports_pop() and self.server_encryption_key and self.server_signature_key else False def _validate_challenge(self, challenge): """ Verifies that the challenge is a valid auth challenge and returns the key=value pairs. """ bearer_string = 'Bearer ' if not challenge: raise ValueError('Challenge cannot be empty') return challenge.strip() # pylint: disable=no-self-use def _validate_request_uri(self, uri): """ Extracts the host authority from the given URI. """ if not uri: raise ValueError('request_uri cannot be empty') uri = parse.urlparse(uri) if not uri.netloc: raise ValueError('request_uri must be an absolute URI') if uri.scheme.lower() not in ['http', 'https']: raise ValueError('request_uri must be HTTP or HTTPS') return uri.netloc
#--------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #--------------------------------------------------------------------------------------------- try: import urllib.parse as parse except ImportError: import urlparse as parse # pylint: disable=import-error class HttpChallenge(object): def __init__(self, request_uri, challenge, response_headers): """ Parses an HTTP WWW-Authentication Bearer challenge from a server. """ self.source_authority = self._validate_request_uri(request_uri) self.source_uri = request_uri self._parameters = {} # get the scheme of the challenge and remove from the challenge string trimmed_challenge = self._validate_challenge(challenge) split_challenge = trimmed_challenge.split(' ', 1) self.scheme = split_challenge[0] trimmed_challenge = split_challenge[1] # split trimmed challenge into comma-separated name=value pairs. Values are expected # to be surrounded by quotes which are stripped here. for item in trimmed_challenge.split(','): # process name=value pairs comps = item.split('=') if len(comps) == 2: key = comps[0].strip(' "') value = comps[1].strip(' "') if key: self._parameters[key] = value # minimum set of parameters if not self._parameters: raise ValueError('Invalid challenge parameters') # must specify authorization or authorization_uri if 'authorization' not in self._parameters and 'authorization_uri' not in self._parameters: raise ValueError('Invalid challenge parameters') # get the message signing key and message key encryption key from the headers self.server_signature_key = response_headers.get('x-ms-message-signing-key', None) self.server_encryption_key = response_headers.get('x-ms-message-encryption-key', None) def is_bearer_challenge(self): """ Tests whether the HttpChallenge a Bearer challenge. rtype: bool """ if not self.scheme: return False return self.scheme.lower() == 'bearer' def is_pop_challenge(self): """ Tests whether the HttpChallenge is a proof of possession challenge. rtype: bool """ if not self.scheme: return False return self.scheme.lower() == 'pop' def get_value(self, key): return self._parameters.get(key) def get_authorization_server(self): """ Returns the URI for the authorization server if present, otherwise empty string. """ value = '' for key in ['authorization_uri', 'authorization']: value = self.get_value(key) or '' if value: break return value def get_resource(self): """ Returns the resource if present, otherwise empty string. """ return self.get_value('resource') or '' def get_scope(self): """ Returns the scope if present, otherwise empty string. """ return self.get_value('scope') or '' def supports_pop(self): """ Returns True if challenge supports pop token auth else False """ return self._parameters.get('supportspop', None) == 'true' def supports_message_protection(self): """ Returns True if challenge vault supports message protection """ return True if self.supports_pop() and self.server_encryption_key and self.server_signature_key else False def _validate_challenge(self, challenge): """ Verifies that the challenge is a valid auth challenge and returns the key=value pairs. """ bearer_string = 'Bearer ' if not challenge: raise ValueError('Challenge cannot be empty') return challenge.strip() # pylint: disable=no-self-use def _validate_request_uri(self, uri): """ Extracts the host authority from the given URI. """ if not uri: raise ValueError('request_uri cannot be empty') uri = parse.urlparse(uri) if not uri.netloc: raise ValueError('request_uri must be an absolute URI') if uri.scheme.lower() not in ['http', 'https']: raise ValueError('request_uri must be HTTP or HTTPS') return uri.netloc
Python
0.00025
2b7dbcd01a4d208f83204fc4323ddff055e4a87e
Move common tests to a base reusable class.
test_ngram_profile.py
test_ngram_profile.py
# -*- coding: utf-8 -*- import os import json import unittest import ngram_profile class CommonNGramProfileTests(object): profileClass = None def test_init(self): profile = self.profileClass() self.assertEqual(len(profile), 0) def test_json_roundtrip(self): json_profile = '{"a": 0.5, "b": 0.3, "c": 0.2}' tmp_file = 'test_json_roundtrip.json' with open(tmp_file, 'w') as fd: fd.write(json_profile) profile = self.profileClass.from_json(tmp_file) os.remove(tmp_file) self.assertEqual(len(profile), 3) self.assertEqual(profile[u'a'], 0.5) self.assertEqual(profile[u'b'], 0.3) self.assertEqual(profile[u'c'], 0.2) profile.save_as_json(tmp_file) with open(tmp_file, 'r') as fd: self.assertEqual(json.load(fd), json.loads(json_profile)) os.remove(tmp_file) def test_normalize_unicode_output(self): profile = self.profileClass() normalized = profile.normalize(u'abc') self.assertTrue(isinstance(normalized, unicode)) class TestNGramProfile(CommonNGramProfileTests, unittest.TestCase): profileClass = ngram_profile.NGramProfile def test_normalize(self): profile = self.profileClass() x = u'abc' y = profile.normalize(x) self.assertEqual(x, y) def test_tokenize(self): profile = ngram_profile.NGramProfile() self.assertRaises(NotImplementedError, profile.tokenize, u'') class TestCharNGramProfile(CommonNGramProfileTests, unittest.TestCase): profileClass = ngram_profile.CharNGramProfile def test_tokenize(self): self.fail('not yet implemented') if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import os import json import unittest from ngram_profile import NGramProfile, CharNGramProfile class TestNGramProfile(unittest.TestCase): def test_init(self): profile = NGramProfile() self.assertEqual(len(profile), 0) def test_json_roundtrip(self): json_profile = '{"a": 0.5, "b": 0.3, "c": 0.2}' tmp_file = 'test_json_roundtrip.json' with open(tmp_file, 'w') as fd: fd.write(json_profile) profile = NGramProfile.from_json(tmp_file) os.remove(tmp_file) self.assertEqual(len(profile), 3) self.assertEqual(profile[u'a'], 0.5) self.assertEqual(profile[u'b'], 0.3) self.assertEqual(profile[u'c'], 0.2) profile.save_as_json(tmp_file) with open(tmp_file, 'r') as fd: self.assertEqual(json.load(fd), json.loads(json_profile)) os.remove(tmp_file) def test_normalize(self): profile = NGramProfile() x = u'abc' y = profile.normalize(x) self.assertTrue(isinstance(y, unicode)) self.assertEqual(x, y) def test_tokenize(self): profile = NGramProfile() self.assertRaises(NotImplementedError, profile.tokenize, u'') if __name__ == '__main__': unittest.main()
Python
0
d1232473ecb31eb2b85b67e54d5939093233f2bf
Print client pk in list_sessions command
ncharts/management/commands/list_sessions.py
ncharts/management/commands/list_sessions.py
from django.core.management.base import NoArgsCommand from ncharts.models import ClientState from ncharts import views as nc_views from django.contrib.sessions.models import Session class Command(NoArgsCommand): def handle_noargs(self, **options): sessions = Session.objects.all() print("#sessions=%d" % len(sessions)) for sess in sessions: sess_dict = sess.get_decoded() print("session keys=%s" % (repr([k for k in sess_dict.keys()]))) for sessk in sess_dict: if len(sessk) > 5 and sessk[0:5] == "pdid_": print("session, sessk=%s, client_id=%d" % (sessk, sess_dict[sessk]))
from django.core.management.base import NoArgsCommand from ncharts.models import ClientState from ncharts import views as nc_views from django.contrib.sessions.models import Session class Command(NoArgsCommand): def handle_noargs(self, **options): sessions = Session.objects.all() print("#sessions=%d" % len(sessions)) for sess in sessions: sess_dict = sess.get_decoded() print("session keys=%s" % (repr([k for k in sess_dict.keys()]))) for sessk in sess_dict: if len(sessk) > 5 and sessk[0:5] == "pdid_": print("session, sessk=%s" % (sessk))
Python
0