code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return db[collection].find_one(match_params if match_params else {}, {'_id': False})
def read_single(db, collection, match_params=None)
Wrapper for pymongo.find_one() :param db: db connection :param collection: collection to read data from :param match_params: a query that matches the documents to select :return: document ('_id' is excluded from result)
4.05023
4.517445
0.896575
return list(db[collection].find(match_params if match_params else {}, {'_id': False}))
def read_multi(db, collection, match_params=None)
Wrapper for pymongo.find() :param db: db connection :param collection: collection to read data from :param match_params: a query that matches the documents to select :return: list of documents ('_id' is excluded from result)
4.250542
4.539074
0.936434
return str(db[collection].update_one(match_params, {"$set": object}, upsert=True).upserted_id)
def upsert_single(db, collection, object, match_params=None)
Wrapper for pymongo.update_one() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the documents to update :return: id of updated document
3.026068
3.843419
0.787338
if isinstance(object, list) and len(object) > 0: return str(db[collection].insert_many(object).inserted_ids) elif isinstance(object, dict): return str(db[collection].update_many(match_params, {"$set": object}, upsert=False).upserted_id)
def upsert_multi(db, collection, object, match_params=None)
Wrapper for pymongo.insert_many() and update_many() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the documents to update :return: ids of inserted/updated document
2.297791
2.331212
0.985664
triggers_cfg = na3x_cfg[NA3X_TRIGGERS] if (collection in triggers_cfg) and (action in triggers_cfg[collection]): return obj_for_name(triggers_cfg[collection][action])(db, collection) else: return None
def factory(db, collection, action)
Instantiate trigger :param db: db descriptor :param collection: collection to be updated :param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE :return: trigger instance if trigger configured in triggers.json or None
5.957384
5.623876
1.059302
trigger = Trigger.factory(self.__db, collection, action) if trigger: self.__logger.info('exec trigger {} on {}'.format(action, collection)) # ToDo: catch exception trigger.execute(input_object, match_params)
def __exec_trigger(self, action, collection, input_object, match_params)
Executes trigger :param action: Trigger.ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE :param collection: see corresponding parameter in delete/update method :param input_object: see corresponding parameter in update method :param match_params: see c...
4.883787
5.687189
0.858735
collection = cfg[AccessParams.KEY_COLLECTION] match_params = cfg[AccessParams.KEY_MATCH_PARAMS] if AccessParams.KEY_MATCH_PARAMS in cfg else None target_type = cfg[AccessParams.KEY_TYPE] if AccessParams.KEY_TYPE in cfg else AccessParams.TYPE_MULTI if target_type == AccessParams...
def get(self, cfg)
Reads single document or list of documents from MongoDB collection :param cfg: { AccessParams.KEY_COLLECTION: <Collection to read data from>, AccessParams.KEY_MATCH_PARAMS: <A query that matches the documents to select>, AccessParams.KEY_TYPE: <AccessP...
2.683824
1.842008
1.45701
collection = cfg[AccessParams.KEY_COLLECTION] match_params = cfg[AccessParams.KEY_MATCH_PARAMS] if AccessParams.KEY_MATCH_PARAMS in cfg else {} target_type = cfg[AccessParams.KEY_TYPE] if AccessParams.KEY_TYPE in cfg else AccessParams.TYPE_MULTI if triggers_on: self....
def delete(self, cfg, triggers_on=True)
Deletes document(s) from MongoDB collection :param cfg: { AccessParams.KEY_COLLECTION: <Collection to update>, AccessParams.KEY_MATCH_PARAMS: <A query that matches the documents to delete>, AccessParams.KEY_TYPE: <AccessParams.TYPE_SINGLE or AccessPara...
2.403013
1.794698
1.338952
input_object = cfg[AccessParams.KEY_OBJECT] collection = cfg[AccessParams.KEY_COLLECTION] match_params = cfg[AccessParams.KEY_MATCH_PARAMS] if AccessParams.KEY_MATCH_PARAMS in cfg else {} if triggers_on: self.__exec_trigger(Trigger.ACTION_BEFORE_UPSERT, collection, i...
def upsert(self, cfg, triggers_on=True)
Updates or inserts single document or list of documents into MongoDB collection :param cfg: { AccessParams.KEY_COLLECTION: <Collection to update>, AccessParams.KEY_OBJECT: <The modifications to apply>, AccessParams.KEY_MATCH_PARAMS: <A query that match...
2.353442
1.839064
1.279695
# 1. Obtain the request token. oauth = OAuth1Session(client_key, client_secret=client_secret) request_token = oauth.fetch_request_token(OAUTH_REQUEST_TOKEN_URL) # 2. Authorize the user (in the browser). authorization_url = oauth.authorization_url(OAUTH_BASE_AUTHORIZE_URL, name=app, exp...
def authorize(client_key, client_secret, credfile=CONFIG_FILE, app='trlo.py', expiration='never', scope='read,write')
Authorize with Trello, saving creds to `credfile`.
2.677437
2.622448
1.020968
''' Performs the equivalent of `chmod +x` on the file at path_str. :returns: path_str if success, else None ''' try: mode = os.stat(path_str).st_mode os.chmod(path_str, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except Exception as e: print 'Exception: %s' % e return None return path...
def make_executable(path_str)
Performs the equivalent of `chmod +x` on the file at path_str. :returns: path_str if success, else None
2.691176
1.937225
1.389192
if not helpers.has_len(value): return False return COUNTRIES.get(str(value).lower(), False)
def getCountry(value)
returns the country name from country code @return string
8.152093
9.61053
0.848246
if not helpers.has_len(value): return False return COUNTRIES.has_key(str(value).lower())
def validate(value)
checks if given value is a valid country codes @param string value @return bool
9.456048
8.868646
1.066234
multipart_data = { 'files': {}, 'data': {} } if request.content_type == 'multipart/form-data': reader = MultipartReader.from_response(request) while True: part = await reader.next() if part is None: break if isinstance...
async def multipart_parser(request, file_handler=default_file_handler)
:param file_handler: callable to save file, this should always return the file path :return: dictionary containing files and data
3.734748
3.596175
1.038533
col = gtk.TreeViewColumn(self.title) col.set_data('pygtkhelpers::objectlist', objectlist) col.set_data('pygtkhelpers::column', self) col.props.visible = self.visible if self.expand is not None: col.props.expand = self.expand if self.resizable is not N...
def create_treecolumn(self, objectlist)
Create a gtk.TreeViewColumn for the configuration.
2.885354
2.839779
1.016049
if self.tooltip_attr: val = getattr(obj, self.tooltip_attr) elif self.tooltip_value: val = self.tooltip_value else: return False setter = getattr(tooltip, TOOLTIP_SETTERS.get(self.tooltip_type)) if self.tooltip_type in TOOLTIP_SIZED_TY...
def render_tooltip(self, tooltip, obj)
Render the tooltip for this column for an object
3.210766
3.152546
1.018468
tool_key = _choose_key(full_configuration.config, keys) if tool_key != keys[0]: full_configuration.executor.warning( "{} is deprecated; migrate to {}".format(tool_key, keys[0]) ) return tool_key
def choose_tool_key(full_configuration, keys)
Select the key for a tool from a list of supported tools. This function is designed to help when multiple keys can be used to specify an option (e.g., during migration from one name to another). The values in keys should be ordered based on preference, as that's the order they'll be checked. If anyth...
4.393798
6.276484
0.700041
# pylint: disable=protected-access tool_name = component.get(key) if tool_name: tool_fn = tool_map.get(tool_name) if tool_fn: return tool_fn[0](*args) raise Exception("Unknown {} '{}' for {}".format(key, tool_name, component.name)) raise MissingToolKey(key, compo...
def tool_builder(component, key, tool_map, *args)
This helper function initializes a tool with the given args.
3.300508
3.322462
0.993392
current_config = current_target.config for key, separator in args_dict.items(): option = "{}.{}".format(prefix, key) value = current_config.get_list(option) if value: if separator is None: separator = _NullJoiner(current_config.name, option) v...
def args_builder(prefix, current_target, args_dict, value_found_fn)
Process arguments a tool cares about. Since most tools require configuration, this function helps deal with the boilerplate. Each option will be processed based on all modifications supported by dev-pipeline (i.e., profiles and overrides) in the proper order. Arguments: prefix -- The prefix f...
4.727311
4.75798
0.993554
def _prepend_first(components, sub_components): ret = [] for first in components[0]: for sub_component in sub_components: ret.append("{}.{}".format(first, sub_component)) return ret if len(components) > 1: sub_components = build_flex_args_keys(c...
def build_flex_args_keys(components)
Helper function to build a list of options. Some tools require require variations of the same options (e.g., cflags for debug vs release builds), but manually creating those options is cumbersome and error-prone. This function handles that work by combining all possible comintations of the values in c...
2.556814
2.643891
0.967065
if len(vals) == 1: return vals[0] raise Exception( "Too many values for {}:{}".format(self._component_name, self._key) )
def join(self, vals)
Either return the non-list value or raise an Exception. Arguments: vals - a list of values to process
5.317382
5.337351
0.996259
if not simpleaudio: return obj fp = pkg_resources.resource_filename(obj.package, obj.resource) data = wave.open(fp, "rb") nChannels = data.getnchannels() bytesPerSample = data.getsampwidth() sampleRate = data.getframerate() nFrames = data.get...
def handle_audio(obj, wait=False)
Handle an audio event. This function plays an audio file. Currently only `.wav` format is supported. :param obj: An :py:class:`~turberfield.dialogue.model.Model.Audio` object. :param bool wait: Force a blocking wait until playback is complete. :return: The supplied ...
3.267831
3.540771
0.922915
if obj is None: return folder.metadata else: return obj(folder, index, ensemble, loop=loop, **kwargs)
def handle_interlude( self, obj, folder, index, ensemble, loop=None, **kwargs )
Handle an interlude event. Interlude functions permit branching. They return a folder which the application can choose to adopt as the next supplier of dialogue. This handler calls the interlude with the supplied arguments and returns the result. :param obj: A callable object....
5.479908
5.109163
1.072565
if obj.persona is None: return obj name = getattr(obj.persona, "_name", "") print( textwrap.indent( "{t.normal}{name}".format(name=name, t=self.terminal), " " * 2 ), end="\n", file=self.terminal...
def handle_line(self, obj)
Handle a line event. This function displays a line of dialogue. It generates a blocking wait for a period of time calculated from the length of the line. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Line` object. :return: The supplied object.
4.025871
3.765208
1.069229
if obj.subject is not None: with self.con as db: SchemaBase.note( db, obj.subject, obj.state, obj.object, text=obj.text, html=obj.html, ) ...
def handle_memory(self, obj)
Handle a memory event. This function accesses the internal database. It writes a record containing state information and an optional note. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Memory` object. :return: The supplied object.
8.686707
8.012691
1.084119
if obj.object is not None: try: setattr(obj.object, obj.attr, obj.val) except AttributeError as e: self.log.error(". ".join(getattr(e, "args", e) or e)) try: print( "{t.dim}{obj.object._name}.{obj.at...
def handle_property(self, obj)
Handle a property event. This function will set an attribute on an object if the event requires it. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Property` object. :return: The supplied object.
3.644886
3.567951
1.021563
print( "{t.dim}{scene}{t.normal}".format( scene=obj.scene.capitalize(), t=self.terminal ), end="\n" * 3, file=self.terminal.stream ) time.sleep(self.pause) return obj
def handle_scene(self, obj)
Handle a scene event. This function applies a blocking wait at the start of a scene. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Shot` object. :return: The supplied object.
6.60425
7.195069
0.917886
print( "{t.dim}{shot}{t.normal}".format( shot=obj.name.capitalize(), t=self.terminal ), end="\n" * 3, file=self.terminal.stream ) return obj
def handle_shot(self, obj)
Handle a shot event. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Shot` object. :return: The supplied object.
8.446772
8.500747
0.993651
value = session.query(ProgramInformation.value).filter(ProgramInformation.name == "db_version").scalar() return int(value)
def get_db_version(session)
:param session: actually it is a sqlalchemy session :return: version number
5.785336
6.069602
0.953166
if parser in PARSERS: if coverage_report: return PARSERS[parser].parse_coverage_report(coverage_report) return None return NotImplemented
def parse_coverage(coverage_report, parser)
:param coverage_report: A string with the contents of a coverage file :type coverage_report: String :param parser: A string with name of the parser to use :type parser: String :return: Total coverage
4.520775
5.70518
0.792398
try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): self.workerpool.run(self.process_request_thread, **{'request': request, ...
def handle_request(self)
simply collect requests and put them on the queue for the workers.
3.783986
3.602793
1.050292
life_time = time.time() nb_requests = 0 while not mainthread.killed(): if self.max_life_time > 0: if (time.time() - life_time) >= self.max_life_time: mainthread.add_worker(1) return try: ...
def process_request_thread(self, mainthread)
obtain request from queue instead of directly from server socket
2.74865
2.698057
1.018751
try: request, client_address = self.get_request() except socket.error: return if self.verify_request(request, client_address): self.requests.put((request, client_address))
def handle_request(self)
simply collect requests and put them on the queue for the workers.
3.143269
2.638427
1.191342
result = invoke.run('python setup.py sdist bdist_egg bdist_wheel', warn=True, hide=True) if result.ok: print("[{}GOOD{}] Distribution built without errors." .format(GOOD_COLOR, RESET_COLOR)) else: print('[{}ERROR{}] Something broke trying to package...
def build_distribution()
Build distributions of the code.
4.315817
4.110314
1.049997
if 'extra_packages' in ctx.releaser: server = server.lower() extra_pkgs = [] if server in ["local"]: if 'local' in ctx.releaser.extra_packages: extra_pkgs.extend(ctx.releaser.extra_packages.local) elif server in ["testpypi", "pypitest"]: #...
def other_dependencies(ctx, server, environment)
Install things that need to be in place before installing the main package.
3.506882
3.454587
1.015138
here = Path(ctx.releaser.here).resolve() dist_dir = here / 'dist' all_files = list(dist_dir.glob('*.{}'.format(ext))) the_file = all_files[0] for f in all_files[1:]: if f.stat().st_mtime > the_file.stat().st_mtime: the_file = f # this is the latest generated fil...
def check_local_install(ctx, version, ext, server="local")
Upload and install works? Uploads a distribution to PyPI, and then tests to see if I can download and install it. Returns: str: string summazing operation
3.789346
3.775311
1.003718
current = self.metadata for k in string.split(keypath, "."): if not current.has_key(k): current[k] = {} current = current[k] current.update(data)
def iscm_md_update_dict(self, keypath, data)
Update a metadata dictionary entry
2.911053
2.772803
1.049859
array_path = string.split(arraypath, ".") array_key = array_path.pop() current = self.metadata for k in array_path: if not current.has_key(k): current[k] = {} current = current[k] if not current.has_key(array_key): curr...
def iscm_md_append_array(self, arraypath, member)
Append a member to a metadata array entry
2.198202
2.136568
1.028847
while isinstance(vars, IscmExpr): vars = vars.resolve(self.context) # for (k,v) in vars.items(): if isinstance(v, IscmExpr): vars[k] = v.resolve(self.context) return vars
def context_lookup(self, vars)
Lookup the variables in the provided dictionary, resolve with entries in the context
4.109672
3.93891
1.043353
# Update user data if launchable.get_property("UserData") is not None: raise NotImplementedError("It's not yet supported to append SCM to existing userdata") user_data = { "Fn::Base64" : { "Fn::Join" : ["", [ "\n".join([ ...
def apply_to(self, launchable)
Apply this ISCM configuration into a launchable resource, such as an EC2 instance or an AutoScalingGroup LaunchConfig.
5.404624
5.098448
1.060053
self.log.info('starting the ``refresh`` method') astorbgz = self._download_astorb() astorbDictList = self._parse_astorb_database_file(astorbgz) self._import_astorb_to_database(astorbDictList) self.log.info('completed the ``refresh`` method') return None
def refresh(self)
*refresh the orbital elements in the astorb.dat database table* **Return:** - ``astorb`` **Usage:** See class docstring
7.522002
4.747708
1.584344
self.log.info('starting the ``_download_astorb`` method') # DOWNLOAD ASTORB url = self.settings["astorb"]["url"] print "Downloading orbital elements from '%(url)s'" % locals() response = urllib2.urlopen(url) data = response.read() astorbgz = "/tmp/astor...
def _download_astorb( self)
*download the astorb database file* **Key Arguments:** - ``astorbgz`` -- path to the downloaded astorb database file
3.79025
3.276253
1.156886
self.log.info('starting the ``_import_astorb_to_database`` method') print "Refreshing the orbital elements database table" dbSettings = self.settings["database settings"]["atlasMovers"] insert_list_of_dictionaries_into_database_tables( dbConn=self.atlasMoversDBCon...
def _import_astorb_to_database( self, astorbDictList)
*import the astorb orbital elements to database* **Key Arguments:** - ``astorbDictList`` -- the astorb database parsed as a list of dictionaries **Return:** - None
4.341148
4.018674
1.080244
try: delta_api = __compare_api_level(module.apilevel, any_apilevel) mod_paramstyle = module.paramstyle mod_threadsafety = module.threadsafety except NameError: raise NotImplementedError("This module does not support registration " "of non D...
def register_uri_backend(uri_scheme, create_method, module, c14n_uri_method, escape, cast, is_connected)
This method is intended to be used by backends only. It lets them register their services, identified by the URI scheme, at import time. The associated method create_method must take one parameter: the complete requested RFC 3986 compliant URI. The associated module must be compliant with DBAPI v2.0 b...
4.014679
3.932507
1.020896
uri_c14n_method = _get_methods_by_uri(sqluri)[METHOD_C14N_URI] if not uri_c14n_method: return sqluri return uri_c14n_method(sqluri)
def c14n_uri(sqluri)
Ask the backend to c14n the uri. See register_uri_backend() for details. If no backend is found for this uri method, a NotImplementedError will be raised.
3.354957
3.685748
0.910251
if columns: if "${columns}" not in sql_query: raise TypeError("received columns but ${columns} not in query") escape = self.__methods[METHOD_ESCAPE] self.__col2idx_map = {} col_list = [] for idx, col in enumerate(columns): ...
def __preparequery(self, sql_query, columns)
WARNING: You can't both pass a ${columns} literal to the underlying .execute() method and use the columns escaping, injection and symbolic access mechanism. WARNING: It is not recommended to SELECT *
3.840726
3.610571
1.063745
tmp_query = self.__preparequery(sql_query, columns) if self.__methods[METHOD_MODULE].paramstyle in ('format', 'pyformat'): tmp_query = qmark_to_format(tmp_query) try: if parameters is None: self.__dbapi2_cursor.execute(tmp_query) ...
def query(self, sql_query, columns = None, parameters = None)
If columns evaluates to true, sql_query must contain "${columns}" (only once) and this substring will be replaced by an SQL representation of the list of columns, correctly escaped for the backend. The resulting string is passed to the DBAPI2.0 .execute() method of the underlying...
3.505113
3.316569
1.056849
tmp_query = self.__preparequery(sql_query, columns) if self.__methods[METHOD_MODULE].paramstyle == "qmark": raise NotImplementedError, "qmark isn't fully supported" try: self.__dbapi2_cursor.executemany(tmp_query, seq_of_parameters) except Exception, e:...
def querymany(self, sql_query, columns, seq_of_parameters)
Same as .query() but eventually call the .executemany() method of the underlying DBAPI2.0 cursor instead of .execute()
4.539284
4.092731
1.109109
try: result = self.__dbapi2_cursor.fetchone() except Exception, e: self.__connection.reconnect(None, self.__log_reconnect) self.__dbapi2_cursor = self.__connection._get_raw_cursor() result = self.__dbapi2_cursor.fetchone() if not result:...
def fetchone(self)
As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behaviour of raising an exception). Additionally every row returned by this class is addressable by column name besides the column position in the query.
4.494915
4.117591
1.091637
try: if size is None: manyrows = self.__dbapi2_cursor.fetchmany() else: manyrows = self.__dbapi2_cursor.fetchmany(size) except Exception, e: self.__connection.reconnect(None, self.__log_reconnect) self.__dbapi2_curs...
def fetchmany(self, size = None)
As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behavior that would be that an exception would have been raised) Additionally every row returned by this class is addressable by column name besides...
2.76424
2.636108
1.048606
try: allrows = self.__dbapi2_cursor.fetchall() except Exception, e: self.__connection.reconnect(None, self.__log_reconnect) self.__dbapi2_cursor = self.__connection._get_raw_cursor() allrows = self.__dbapi2_cursor.fetchall() if not allro...
def fetchall(self)
As in DBAPI2.0 (except the fact rows are not tuples but lists so if you try to modify them, you will succeed instead of the correct behavior that would be that an exception would have been raised) Additionally every row returned by this class is addressable by column name besides...
4.339839
3.994992
1.08632
"As in DBAPI2.0" if column is None: self.__dbapi2_cursor.setoutputsize(size) else: self.__dbapi2_cursor.setoutputsize(size, column)
def setoutputsize(self, size, column = None)
As in DBAPI2.0
3.993474
2.722031
1.467093
self.__methods = _get_methods_by_uri(self.sqluri) uri_connect_method = self.__methods[METHOD_CONNECT] self.__dbapi2_conn = uri_connect_method(self.sqluri)
def __connect(self)
Connect to the database.
10.537785
9.531665
1.105556
uri = list(urisup.uri_help_split(self.sqluri)) if uri[1]: authority = list(uri[1]) if authority[1]: authority[1] = None uri[1] = authority if log_reconnect: LOG.warning('reconnecting to %r database (query: %r)', uri...
def reconnect(self, query = None, log_reconnect = False)
Reconnect to the database.
7.765686
7.411987
1.04772
try: self.__dbapi2_conn.commit() except Exception, e: # try to reconnect self.reconnect(None) self.__dbapi2_conn.commit()
def commit(self)
As in DBAPI2.0: Commit any pending transaction to the database. Note that if the database supports an auto-commit feature, this must be initially off. An interface method may be provided to turn it back on. Database modules that do not support transactions should impleme...
5.43103
4.527704
1.199511
for request in self._cfg[Integrator._CFG_KEY_REQUESTS]: request_type = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_TYPE] request_cfg_file = self._cfg[Integrator._CFG_KEY_REQUESTS][request][Integrator._CFG_KEY_REQUEST_CFG_FILE] self._l...
def perform(self)
Performs bulk operation
2.745029
2.706
1.014423
if hasattr(g, 'session'): return g.session sess = create_session(bind=current_app.config['DATABASE_ENGINE']) try: g.session = sess except RuntimeError: pass return sess
def get_session()
Gets a session. If there's no yet, creates one. :returns: a session
3.174376
3.847697
0.825007
engine = create_engine(uri, **kwargs) base.metadata.create_all(engine) return engine
def init_db(uri, base, **kwargs)
Create engine and tables :param uri: db uri :param base: declarative base :returns: an engine
2.465251
2.670648
0.923091
def _validate_inputs(actual_inputs, required_inputs, keypath=None): actual_keys = set(actual_inputs.keys()) required_keys = set(required_inputs.keys()) if actual_keys.intersection(required_keys) != required_keys: prefix = '%s.' if keypath else '' output_keys = {'%s%s' % (prefix, k...
Validate inputs. Raise exception if something is missing. args: actual_inputs: the object/dictionary passed to a subclass of PublishablePayload required_inputs: the object/dictionary containing keys (and subkeys) for required fields. (See get_common_payload_templat...
null
null
null
def _citation_to_string(citation): output = '' sep = '. ' if 'authors' in citation: authors = [] for author in citation['authors']: if 'family_name' not in author: continue author_name = author['family_name'] if 'given_name...
Convert citation object to a string, using standard citation formatting. args: citation: a dictionary potentially containing all fields from pypif.obj.Reference, and possibly a few others TODO: This is tedious and fragile. Find a better way to get 'er done. TODO: This funct...
null
null
null
def get_common_payload_template(services=None): available_services = {'citrine', 'materials_commons', 'materials_data_facility'} if services is None: services = list(available_services) else: services = [service for service in services if service in available_services] if...
Get a template dictionary that can be used to create a payload object. TODO: services s/b a list. Specify required fields for each service in list. None means all services.
null
null
null
if not plugin_name: return None, u"Plugin name not set" for plugin in self.controller.plugins: if not isinstance(plugin, SettablePlugin): continue if plugin.name == plugin_name: return plugin, "" return None, u"Settable...
def _plugin_get(self, plugin_name)
Find plugins in controller :param plugin_name: Name of the plugin to find :type plugin_name: str | None :return: Plugin or None and error message :rtype: (settable_plugin.SettablePlugin | None, str)
3.633381
2.794652
1.300119
tool_key = devpipeline_core.toolsupport.choose_tool_key( current_target, _BUILD_TOOL_KEYS ) return devpipeline_core.toolsupport.tool_builder( config, tool_key, devpipeline_build.BUILDERS, current_target )
def _make_builder(config, current_target)
Create and return a Builder for a component. Arguments component - The component the builder should be created for.
7.783144
9.807649
0.793579
target = current_target.config try: builder = _make_builder(target, current_target) build_path = _get_build_path(target, builder) if not os.path.exists(build_path): os.makedirs(build_path) builder.configure(src_dir=target.get("dp.src_dir"), build_dir=build_path)...
def build_task(current_target)
Build a target. Arguments target - The target to build.
3.73472
3.85024
0.969997
'''Return the profile with the received ID as a dict If a local copy of the profile exists, it'll be returned. If not, it'll be downloaded from the web. The results are cached, so any subsequent calls won't hit the filesystem or the web. This method raises DataPackageRegistryEx...
def get(self, profile_id)
Return the profile with the received ID as a dict If a local copy of the profile exists, it'll be returned. If not, it'll be downloaded from the web. The results are cached, so any subsequent calls won't hit the filesystem or the web. This method raises DataPackageRegistryException if ...
4.503706
1.693919
2.65875
'''Return the profile with the received ID as a dict''' profile_metadata = self._registry.get(profile_id) if not profile_metadata: return path = self._get_absolute_path(profile_metadata.get('schema_path')) if path and os.path.isfile(path): return self._lo...
def _get_profile(self, profile_id)
Return the profile with the received ID as a dict
3.693544
3.032877
1.217835
'''Return a dict with objects mapped by their id from a CSV endpoint''' if os.path.isfile(registry_path_or_url): with open(registry_path_or_url, 'r') as f: reader = compat.csv_dict_reader(f.readlines()) else: res = requests.get(registry_path_or_url) ...
def _get_registry(self, registry_path_or_url)
Return a dict with objects mapped by their id from a CSV endpoint
3.383267
2.243817
1.507818
'''Return the JSON at the local path or URL as a dict This method raises DataPackageRegistryException if there were any errors. ''' try: if os.path.isfile(json_path_or_url): with open(json_path_or_url, 'r') as f: result = json.load...
def _load_json_file_or_url(self, json_path_or_url)
Return the JSON at the local path or URL as a dict This method raises DataPackageRegistryException if there were any errors.
3.176302
1.8879
1.682453
if self._is_already_processed(file_info): self.log.debug("Content file already processed '%s'", str(file_info)) self.fire(events.FilteredFile(file_info)) self.fire(events.FileInfoAlreadyProcessed(file_info)) else: return file_info return N...
def process_data(self, file_info)
expects FileInfo
6.186975
5.895893
1.04937
self.count_lock.acquire() if nb > self.workers: nb = self.workers self.count_lock.release() for x in xrange(nb): self.tasks.put(WorkerExit())
def kill(self, nb = 1)
Kill one or many workers.
4.341375
3.757519
1.155383
self.count_lock.acquire() self.max_workers = nb if self.workers > self.max_workers: self.kill(self.workers - self.max_workers) self.count_lock.release()
def set_max_workers(self, nb)
Set the maximum workers to create.
3.042896
3.002988
1.013289
for x in xrange(nb): self.count_lock.acquire() if self.workers >= self.max_workers: self.count_lock.release() continue self.workers += 1 if xid is None: xid = self.workers self.count_lock.release...
def add(self, nb = 1, name = None, xid = None)
Create one or many workers.
2.969254
2.733407
1.086283
self.count_lock.acquire() if not self.workers: self.count_lock.release() self.add(name = name) else: self.count_lock.release() self.tasks.put((target, callback, name, complete, args, kargs))
def run(self, target, callback = None, name = None, complete = None, *args, **kargs)
Start task. @target: callable to run with *args and **kargs arguments. @callback: callable executed after target. @name: thread name @complete: complete executed after target in finally
3.324827
3.445537
0.964966
with self.tasks.mutex: self.tasks.queue.clear() self.count_lock.acquire() self.kill(self.workers) self.count_lock.release() self.kill_event.wait(wait)
def killall(self, wait = None)
Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever.
5.087863
4.726449
1.076466
POST = urlencode({ "blog": settings.AKISMET_BLOG.encode("utf-8"), "user_ip": comment.ip_address, "user_agent": request.META.get('HTTP_USER_AGENT', ""). encode("utf-8"), "referrer": r...
def allow(self, comment, content_object, request)
Moderates comments.
2.36923
2.349402
1.00844
import hashlib from copy import copy phases = self.phases pending_list = copy(phases) must_run_list = [] stages = [ dict(status_id="", must_run=copy(must_run_list), pending=copy(pending_list)) ] hashsum = hashlib.sha256() status_id_after ...
def get_possible_builds(self, purpose=PURPOSE_RUN)
Returns a list of possible status ids that are valid entry points into this ISCM. For each status, there is a list of phases that need to be executed, i.e.: [ { status_id: "ykyk...", run_phases: [ ] }, { status_id: "znzn...", run_phases: [ <phase3> ] }, { status_id: "...
3.755943
3.406238
1.102666
return dict( phase_name = self.phase_name, phase_type = self.phase_type, actions = self.actions )
def get_dict_repr(self)
Return a dictionary representation of this phase. This will be used for checksumming, in order to uniquely compare instance images against their requirements
5.059906
3.794097
1.333626
elements = [] for i in indices: elements.append(self[i]) return elements
def discrete_index(self, indices)
get elements by discrete indices :param indices: list discrete indices :return: elements
4.153283
4.646182
0.893913
# sanitize input im0 = np.asarray(im0, dtype=np.float32) im1 = np.asarray(im1, dtype=np.float32) if rmMean: # remove mean im0 = im0 - im0.mean() im1 = im1 - im1.mean() # Compute DFT (THe images are resized to the same size) f0, f1 = dft_optsize_same(im0, im1) # G...
def register_images(im0, im1, *, rmMean=True, correctScale=True)
Finds the rotation, scaling and translation of im1 relative to im0 Parameters ---------- im0: First image im1: Second image rmMean: Set to true to remove the mean (Default) Returns ------- angle: The angle difference scale: The scale difference [y, x]: The offset im2: The r...
3.984085
3.633095
1.096609
# sanitize input im0 = np.asarray(im0, dtype=np.float32) im1 = np.asarray(im1, dtype=np.float32) truesize = None # if ccs, convert to shifted dft before giving to polar_fft if isccs: truesize = im0.shape im0 = centered_mag_sq_ccs(im0) im1 = centered_mag_sq_ccs(im1) ...
def find_rotation_scale(im0, im1, isccs=False)
Compares the images and return the best guess for the rotation angle, and scale difference. Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: boolean, default False Set to True if the images are alredy DFT and in CCS representation Re...
4.864443
4.534379
1.072792
# sanitize input im0 = np.asarray(im0, dtype=np.float32) im1 = np.asarray(im1, dtype=np.float32) # check input if not isccs: im0, im1 = dft_optsize_same(im0, im1) else: # Work only if the shapes are the same assert(im0.shape == im1.shape) # f0*conj(f1) mulS...
def find_shift_dft(im0, im1, isccs=False, subpix=True)
Find the shift between two images using the DFT method Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: Boolean, default false Set to True if the images are alredy DFT and in CCS representation subpix: boolean, default True Set to...
3.930596
3.97451
0.988951
# sanitize input im0 = np.asarray(im0, dtype=np.float32) im1 = np.asarray(im1, dtype=np.float32) # Remove mean im0 = im0 - np.nanmean(im0) im1 = im1 - np.nanmean(im1) # Save shapes as np array shape0 = np.asarray(im0.shape) shape1 = np.asarray(im1.shape) # Compute the offse...
def find_shift_cc(im0, im1, ylim=None, xlim=None, subpix=True)
Finds the best shift between im0 and im1 using cross correlation Parameters ---------- im0: 2d array First image im1: 2d array Second image ylim: 2 numbers, optional The y limits of the search (if None full range is searched) xlim: 2 numbers, optional Ibidem with...
3.818407
3.815704
1.000708
imgs = np.asarray(imgs, dtype="float") if register: for i in range(1, imgs.shape[0]): ret = register_images(imgs[0, :, :], imgs[i, :, :]) imgs[i, :, :] = rotate_scale_shift(imgs[i, :, :], *ret[:3], np.nan) return np.mean(imgs, 0)
def combine_images(imgs, register=True)
Combine similar images into one to reduce the noise Parameters ---------- imgs: list of 2d array Series of images register: Boolean, default False True if the images should be register before combination Returns ------- im: 2d array The result image Notes -...
3.426355
3.926029
0.872728
im = np.asarray(im) # If we rotate the image first if rotateAngle is not None and not isshiftdft: # compute the scale corresponding to the image scale = np.sqrt(.5 * (1 + (np.tan(rotateAngle) - 1)**2 / (np.tan(rotateAngle) + 1)**2)) # rotate the im...
def orientation_angle(im, approxangle=None, *, isshiftdft=False, truesize=None, rotateAngle=None)
Give the highest contribution to the orientation Parameters ---------- im: 2d array The image approxangle: number, optional The approximate angle (None if unknown) isshiftdft: Boolean, default False True if the image has been processed (DFT, fftshift) truesize: 2 numbers...
5.412102
5.537873
0.977289
im = np.asarray(im, dtype=np.float32) # If we rotate the image first if rotateAngle is not None and not isshiftdft: # compute the scale corresponding to the image scale = np.sqrt(.5 * (1 + (np.tan(rotateAngle) - 1)**2 / (np.tan(rotateAngle) + 1)**2)) ...
def orientation_angle_2(im, nangle=None, isshiftdft=False, rotateAngle=None)
Give the highest contribution to the orientation Parameters ---------- im: 2d array The image nangle: number, optional The number of angles checked for isshiftdft: Boolean, default False True if the image has been processed (DFT, fftshift) rotateAngle: number, optional ...
5.502937
5.552378
0.991095
im = np.asarray(im) # save shape initshape = im.shape # get optimal size if shape is None: ys = cv2.getOptimalDFTSize(initshape[0]) xs = cv2.getOptimalDFTSize(initshape[1]) shape = [ys, xs] # Add zeros to go to optimal size im = cv2.copyMakeBorder(im, 0, shape[0]...
def dft_optsize(im, shape=None)
Resize image for optimal DFT and computes it Parameters ---------- im: 2d array The image shape: 2 numbers, optional The shape of the output image (None will optimize the shape) Returns ------- dft: 2d array The dft in CCS representation Notes ----- Th ...
3.505636
3.560629
0.984555
im0 = np.asarray(im0) im1 = np.asarray(im1) # save shape shape0 = im0.shape shape1 = im1.shape # get optimal size ys = max(cv2.getOptimalDFTSize(shape0[0]), cv2.getOptimalDFTSize(shape1[0])) xs = max(cv2.getOptimalDFTSize(shape0[1]), cv2.getOptimalDFTSize(s...
def dft_optsize_same(im0, im1)
Resize 2 image same size for optimal DFT and computes it Parameters ---------- im0: 2d array First image im1: 2d array Second image Returns ------- dft0: 2d array The dft of the first image dft1: 2d array The dft of the second image Notes ----- ...
1.994241
2.037106
0.978958
im = np.asarray(im, dtype=np.float32) rows, cols = im.shape M = cv2.getRotationMatrix2D( (cols / 2, rows / 2), -angle * 180 / np.pi, 1 / scale) im = cv2.warpAffine(im, M, (cols, rows), borderMode=cv2.BORDER_CONSTANT, flags=interp, ...
def rotate_scale(im, angle, scale, borderValue=0, interp=cv2.INTER_CUBIC)
Rotates and scales the image Parameters ---------- im: 2d array The image angle: number The angle, in radians, to rotate scale: positive number The scale factor borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ...
2.323201
2.569684
0.90408
im = np.asarray(im, dtype=np.float32) rows, cols = im.shape M = np.asarray([[1, 0, shift[1]], [0, 1, shift[0]]], dtype=np.float32) return cv2.warpAffine(im, M, (cols, rows), borderMode=cv2.BORDER_CONSTANT, flags=cv2.INTER_CUBIC, ...
def shift_image(im, shift, borderValue=0)
shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ------- im: 2d array The shifted image ...
1.897049
2.019621
0.939309
im = np.asarray(im) pad = np.asarray(pad) # get shape shape = im.shape # extract offset from padding offset = -pad[::2] # if the padding is negatif, cut the matrix cut = pad < 0 if cut.any(): # Extract value for pad cut *= pad # the left/top components sh...
def pad_img(im, pad)
Pad positively with 0 or negatively (cut) Parameters ---------- im: 2d array The image pad: 4 numbers (ytop, ybottom, xleft, xright) or (imin, imax, jmin, jmax) Returns ------- im: 2d array The padded (or cropped) image offset: 2 numbers The offset relat...
5.377387
5.123876
1.049476
compIM = np.asarray(compIM) ccsnorm = np.asarray(ccsnorm) ys = ccsnorm.shape[0] xs = ccsnorm.shape[1] # start with first column ccsnorm[2::2, 0] = ccsnorm[1:ys - 1:2, 0] # continue with middle columns ccsnorm[:, 2::2] = ccsnorm[:, 1:xs - 1:2] # finish whith last row if even ...
def ccs_normalize(compIM, ccsnorm)
normalize the ccs representation Parameters ---------- compIM: 2d array The CCS image in CCS representation ccsnorm: 2d array The normalization matrix in ccs representation Returns ------- compIM: 2d array The normalized CCS image Notes ----- (basically...
2.99806
3.021138
0.992361
X = np.asarray(X) Y = np.asarray(Y) # Can not have negative values Y[Y < 0] = 0 # define gauss function def gauss(x, a, x0, sigma): return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) # get first estimation for parameter mean = (X * Y).sum() / Y.sum() sigma = np.sqrt((Y * ...
def gauss_fit(X, Y)
Fit the function to a gaussian. Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- (The return from scipy.optimize.curve_fit) popt : array Optimal values for the parameters pcov : 2d array The estimated covariance of popt...
2.865679
2.885819
0.993021
X = np.asarray(X) Y = np.asarray(Y) # take log data Data = np.log(Y) # Get Di and Xi D = [(Data * X**i).sum() for i in range(3)] X = [(X**i).sum() for i in range(5)] # compute numerator and denominator for mean and variance num = (D[0] * (X[1] * X[4] - X[2] * X[3]) + ...
def gauss_fit_log(X, Y)
Fit the log of the input to the log of a gaussian. Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- mean: number The mean of the gaussian curve var: number The variance of the gaussian curve Notes ----- The lea...
2.57851
2.5709
1.00296
X = np.asarray(X) Y = np.asarray(Y) return (X * Y).sum() / Y.sum()
def center_of_mass(X, Y)
Get center of mass Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- res: number The position of the center of mass in X Notes ----- Uses least squares
2.627266
3.488808
0.753055
im = np.asarray(im) # remove invalid values (assuming im>0) im[np.logical_not(np.isfinite(im))] = 0 # remove mean im = im - im.mean() # get maximum value argmax = im.argmax() dsize = im.size # get cut value (30% biggest peak) # TODO: choose less random value cut = .3 * i...
def get_peak_pos(im, wrap=False)
Get the peak position with subpixel precision Parameters ---------- im: 2d array The image containing a peak wrap: boolean, defaults False True if the image reoresents a torric world Returns ------- [y,x]: 2 numbers The position of the highest peak with subpixel pre...
5.185395
5.45204
0.951093
im = np.asarray(im) # multiply image by image* to get squared magnitude im = cv2.mulSpectrums(im, im, flags=0, conjB=True) ys = im.shape[0] xs = im.shape[1] # get correct size return ret = np.zeros((ys, xs // 2 + 1)) # first column: # center ret[ys // 2, 0] = im[0, 0] ...
def centered_mag_sq_ccs(im)
return centered squared magnitude Parameters ---------- im: 2d array A CCS DFT image Returns ------- im: 2d array A centered image of the magnitude of the DFT Notes ----- Check doc Intel* Image Processing Library https://www.comp.nus.edu.sg/~cs4243/doc/ipl.pdf ...
3.362775
3.284364
1.023874
if len(np.shape(ims)) == 3: return [is_overexposed(im) for im in ims] ims = np.array(ims, int) diffbincount = np.diff(np.bincount(np.ravel(ims))) overexposed = diffbincount[-1] > np.std(diffbincount) return overexposed
def is_overexposed(ims)
Simple test to check if image is overexposed Parameters ---------- im: 2d array integer the image Returns ------- overexposed: Bool Is the image overexposed
3.324899
3.626508
0.916832
request = requests.get('https://www.taps-aff.co.uk/api/%s' % self.location) if request.status_code == 200: try: taps = request.json()['taps']['status'] if taps == 'aff': return True elif taps == 'oan': ...
def is_taps_aff(self)
Returns True if taps aff for this location
4.338229
3.839102
1.130011
rotator = Rotator(pyes.ES(hosts), **kwargs) for prefix in prefixes: rotator.rotate(prefix)
def rotate(prefixes, hosts, **kwargs)
Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight.
5.921565
6.05638
0.97774
''' Compare actual and expected using == >>> expect = Expector([]) >>> expect(1).to_not(equal, 2) (True, 'equal: expect 1 == 2') >>> expect(1).to(equal, 1) (True, 'equal: expect 1 == 1') ''' is_passing = (actual == expected) types_to_diff = (str, dict, list, tuple) if not ...
def equal(actual, expected)
Compare actual and expected using == >>> expect = Expector([]) >>> expect(1).to_not(equal, 2) (True, 'equal: expect 1 == 2') >>> expect(1).to(equal, 1) (True, 'equal: expect 1 == 1')
3.453582
2.28065
1.514297