code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if isinstance(task_id, RegisteredTask): task_id = task_id.id def cloud_delete(api): api.delete(task_id) if len(self._threads): self.put(cloud_delete) else: cloud_delete(self._api) return self
def delete(self, task_id)
Deletes a task from a TaskQueue.
4.971556
4.619484
1.076215
body = { "payload": task.payload(), "queueName": self._queue_name, "groupByTag": True, "tag": task.__class__.__name__ } def cloud_insertion(): self._api.insert(body, delay_seconds) self._pool.spawn(cloud_insertion) return self
def insert(self, task, args=[], kwargs={}, delay_seconds=0)
Insert a task into an existing queue.
7.031524
6.824255
1.030372
return 'r' in action.type._mode and (action.default is None or getattr(action.default, 'name') not in (sys.stderr.name, sys.stdout.name))
def is_upload(action)
Checks if this should be a user upload :param action: :return: True if this is a file we intend to upload from the user
10.314958
14.458588
0.713414
exclude = {'name', 'model'} field_module = 'models' django_kwargs = {} if self.node_attrs['model'] == 'CharField': django_kwargs['max_length'] = 255 django_kwargs['blank'] = not self.node_attrs['required'] try: django_kwargs['default'] = s...
def to_django(self)
This is a debug function to see what equivalent django models are being generated
3.242918
3.025565
1.071839
new_dict = {} for key in a_dict: if six.PY2 and isinstance(key, six.text_type): new_dict[str(key)] = a_dict[key] else: new_dict[key] = a_dict[key] return new_dict
def str_dict_keys(a_dict)
return a modified dict where all the keys that are anything but str get converted to str. E.g. >>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2}) >>> # can't compare whole dicts in doctests >>> result['name'] u'Peter' >>> result['age'] 99 >>> result[1] ...
1.949499
2.257578
0.863535
if not isinstance(input_str, six.string_types): raise ValueError(input_str) input_str = str_quote_stripper(input_str) return input_str.lower() in ("true", "t", "1", "y", "yes")
def str_to_boolean(input_str)
a conversion function for boolean
3.057488
3.169597
0.96463
if not input_str: return None if six.PY3 and isinstance(input_str, six.binary_type): input_str = to_str(input_str) if not isinstance(input_str, six.string_types): # gosh, we didn't get a string, we can't convert anything but strings # we're going to assume that what we g...
def str_to_python_object(input_str)
a conversion that will import a module and class name
3.399806
3.355053
1.013339
if not isinstance(input_str, six.string_types): raise ValueError(input_str) input_str = str_quote_stripper(input_str) result = [ item_converter(x.strip()) for x in input_str.split(item_separator) if x.strip() ] if list_to_collection_converter is not None: return ...
def str_to_list( input_str, item_converter=lambda x: x, item_separator=',', list_to_collection_converter=None, )
a conversion function for list
2.146008
2.146252
0.999886
# is it None? if a_thing is None: return '' # is it already a string? if isinstance(a_thing, six.string_types): return a_thing if six.PY3 and isinstance(a_thing, six.binary_type): try: return a_thing.decode('utf-8') except UnicodeDecodeError: ...
def arbitrary_object_to_string(a_thing)
take a python object of some sort, and convert it into a human readable string. this function is used extensively to convert things like "subject" into "subject_key, function -> function_key, etc.
2.82373
2.853901
0.989428
generator = SourceGenerator(indent_with, add_line_information) generator.visit(node) return ''.join(str(s) for s in generator.result)
def to_source(node, indent_with=' ' * 4, add_line_information=False)
This function can convert a node tree back into python sourcecode. This is useful for debugging purposes, especially if you're dealing with custom asts not generated by python itself. It could be that the sourcecode is evaluable when the AST itself is not compilable / evaluable. The reason for this is...
3.068927
4.694682
0.653703
if not name: name = threading.currentThread().getName() if name in self.pool: return self.pool[name] self.pool[name] = FakeDatabaseConnection(self.dsn) return self.pool[name]
def connection(self, name=None)
return a named connection. This function will return a named connection by either finding one in its pool by the name or creating a new one. If no name is given, it will use the name of the current executing thread as the name of the connection. parameters: name - ...
3.283142
3.297819
0.99555
if force: print('PostgresPooled - delegating connection closure') try: super(PostgresPooled, self).close_connection(connection, force) except self.operational_exceptions: ...
def close_connection(self, connection, force=False)
overriding the baseclass function, this routine will decline to close a connection at the end of a transaction context. This allows for reuse of connections.
5.085371
5.079271
1.001201
with self.config.db_transaction() as trans: function(trans, *args, **kwargs)
def do_transaction(self, function, *args, **kwargs)
execute a function within the context of a transaction
5.089314
5.104426
0.997039
for x in range(int(seconds)): if (self.config.wait_log_interval and not x % self.config.wait_log_interval): print('%s: %dsec of %dsec' % (wait_reason, x, seconds)) ...
def responsive_sleep(self, seconds, wait_reason='')
Sleep for the specified number of seconds, logging every 'wait_log_interval' seconds with progress info.
4.281519
3.610502
1.185852
for wait_in_seconds in self.backoff_generator(): try: with self.config.db_transaction() as trans: function(trans, *args, **kwargs) trans.commit() break except self.config.db_transaction.operational_excep...
def do_transaction(self, function, *args, **kwargs)
execute a function within the context of a transaction
5.303285
5.37901
0.985922
expanded_file_contents = [] with open(file_name) as f: for a_line in f: match = ConfigObjWithIncludes._include_re.match(a_line) if match: include_file = match.group(2) include_file = os.path.join( ...
def _expand_files(self, file_name, original_path, indent="")
This recursive function accepts a file name, opens the file and then spools the contents of the file into a list, examining each line as it does so. If it detects a line beginning with "+include", it assumes the string immediately following is a file name. Recursing, the file new file ...
2.286568
2.255592
1.013733
if isinstance(infile, (six.binary_type, six.text_type)): infile = to_str(infile) original_path = os.path.dirname(infile) expanded_file_contents = self._expand_files(infile, original_path) super(ConfigObjWithIncludes, self)._load( expanded_...
def _load(self, infile, configspec)
this overrides the original ConfigObj method of the same name. It runs through the input file collecting lines into a list. When completed, this method submits the list of lines to the super class' function of the same name. ConfigObj proceeds, completely unaware that it's input file ...
3.268887
3.076449
1.062552
if self.delayed_parser_instantiation: try: app = config_manager._get_option('admin.application') source = "%s%s" % (app.value.app_name, file_name_extension) self.config_obj = configobj.ConfigObj(source) self.delayed_parser_inst...
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict)
Return a nested dictionary representing the values in the ini file. In the case of this ValueSource implementation, both parameters are dummies.
6.558214
6.437114
1.018813
options = [ value for value in source_dict.values() if isinstance(value, Option) ] options.sort(key=lambda x: x.name) indent_spacer = " " * (level * indent_size) for an_option in options: print("%s# %s" % (indent_spacer, an...
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4, output_stream=sys.stdout)
this function prints the components of a configobj ini file. It is recursive for outputing the nested sections of the ini file.
2.568379
2.602199
0.987003
try: config_kwargs = {'mapping_class': kwargs.pop('mapping_class')} except KeyError: config_kwargs = {} cm = ConfigurationManager(*args, **kwargs) return cm.get_config(**config_kwargs)
def configuration(*args, **kwargs)
this function just instantiates a ConfigurationManager and returns the configuration dictionary. It accepts all the same parameters as the constructor for the ConfigurationManager class.
4.446777
3.474772
1.279732
if ( "not allowed" in message or "ignored" in message or "expected" in message or "invalid" in message or self.add_help ): # when we have "help" then we must also have proper error # processing. Without "help",...
def error(self, message)
we need to suppress errors that might happen in earlier phases of the expansion/overlay process.
14.294982
13.760295
1.038857
subordinate_mappings = [] for key, value in six.iteritems(a_mapping): if isinstance(value, collections.Mapping): subordinate_mappings.append((key, value)) if include_dicts: yield key, value else: yield key, value for key, a_map in subo...
def iteritems_breadth_first(a_mapping, include_dicts=False)
a generator that returns all the keys in a set of nested Mapping instances. The keys take the form X.Y.Z
1.980411
2.087779
0.948573
configmanized_keys_dict = DotDict() for k, v in iteritems_breadth_first(a_mapping): if '__' in k and k != k.upper(): k = k.replace('__', '.') configmanized_keys_dict[k] = v return configmanized_keys_dict
def configman_keys(a_mapping)
return a DotDict that is a copy of the provided mapping with keys transformed into a configman compatible form: if the key is not all uppercase then all doubled underscores will be replaced with the '.' character. This has a specific use with the os.environ. Linux shells generally do not ...
4.198634
3.892976
1.078515
#========================================================================== class DotDictWithKeyTranslations(base_class): def __init__(self, *args, **kwargs): self.__dict__['_translation_tuples'] = translation_tuples super(DotDictWithKeyTranslations, self).__init__(*args, *...
def create_key_translating_dot_dict( new_class_name, translation_tuples, base_class=DotDict )
this function will generate a DotDict derivative class that has key translation built in. If the key is not found, translations (as specified by the translation_tuples) are performed on the key and the lookup is tried again. Only on failure of this second lookup will the KeyError exception be raised. ...
1.798298
1.769778
1.016115
namespaces = [] for key in self._key_order: if isinstance(getattr(self, key), DotDict): namespaces.append(key) if include_dicts: yield key else: yield key for a_namespace in namespaces: ...
def keys_breadth_first(self, include_dicts=False)
a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z
2.823673
2.52653
1.117609
key_split = key.split('.') cur_dict = self for k in key_split[:-1]: try: cur_dict = cur_dict[k] except KeyError: cur_dict[k] = self.__class__() # so that derived classes # remain tru...
def assign(self, key, value)
an alternative method for assigning values to nested DotDict instances. It accepts keys in the form of X.Y.Z. If any nested DotDict instances don't yet exist, they will be created.
3.391995
3.063779
1.107128
parent_key = '.'.join(key.split('.')[:-1]) if not parent_key: return None else: return self[parent_key]
def parent(self, key)
when given a key of the form X.Y.Z, this method will return the parent DotDict of the 'Z' key.
3.250749
2.83217
1.147794
def wrapper(f): @wraps(f) def fn(*args, **kwargs): if kwargs: key = (args, tuple(kwargs.items())) else: key = args try: return fn.cache[key] except KeyError: if fn.count >= max_cache_...
def memoize(max_cache_size=1000)
Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cache_size - the size to w...
1.628307
1.780959
0.914286
if self.default is None or force: self.default = val self.set_value(val) self.has_changed = True else: raise OptionError( "cannot override existing default without using the 'force' " "option" )
def set_default(self, val, force=False)
this function allows a default to be set on an option that dosen't have one. It is used when a base class defines an Option for use in derived classes but cannot predict what value would useful to the derived classes. This gives the derived classes the opportunity to set a logical defa...
4.739007
4.587006
1.033137
o = Option( name=self.name, default=self.default, doc=self.doc, from_string_converter=self.from_string_converter, to_string_converter=self.to_string_converter, value=self.value, short_form=self.short_form, e...
def copy(self)
return a copy
2.949749
2.907945
1.014376
config = None try: config = self.get_config(mapping_class=mapping_class) yield config finally: if config: self._walk_and_close(config)
def context(self, mapping_class=DotDictWithAcquisition)
return a config as a context that calls close on every item when it goes out of scope
5.15729
3.614023
1.427022
if self.app_name or self.app_description: print('Application: ', end='', file=output_stream) if self.app_name: print(self.app_name, self.app_version, file=output_stream) if self.app_description: print(self.app_description, file=output_stream) ...
def output_summary(self, output_stream=sys.stdout)
outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a print function
4.079296
4.046088
1.008207
config_file_type = self._get_option('admin.print_conf').value @contextlib.contextmanager def stdout_opener(): yield sys.stdout skip_keys = [ k for (k, v) in six.iteritems(self.option_definitions) if isinstance(v, Option) and v.e...
def print_conf(self)
write a config file to the pathname specified in the parameter. The file extention determines the type of file written and must match a registered type. parameters: config_pathname - the full path and filename of the target config file.
5.641661
5.893188
0.957319
if not config_pathname: config_pathname = self._get_option('admin.dump_conf').value opener = functools.partial(open, config_pathname, 'w') config_file_type = os.path.splitext(config_pathname)[1][1:] skip_keys = [ k for (k, v) in six.iterite...
def dump_conf(self, config_pathname=None)
write a config file to the pathname specified in the parameter. The file extention determines the type of file written and must match a registered type. parameters: config_pathname - the full path and filename of the target config file.
3.824357
3.934266
0.972064
blocked_keys = self.keys_blocked_from_output if skip_keys: blocked_keys.extend(skip_keys) if blocked_keys: option_defs = self.option_definitions.safe_copy() for a_blocked_key in blocked_keys: try: del option_defs[...
def write_conf(self, config_file_type, opener, skip_keys=None)
write a configuration file to a file-like object. parameters: config_file_type - a string containing a registered file type OR a for_XXX module from the value_source package. Passing in an string that is u...
4.060795
4.14633
0.979371
logger.info("app_name: %s", self.app_name) logger.info("app_version: %s", self.app_version) logger.info("current configuration:") config = [(key, self.option_definitions[key].value) for key in self.option_definitions.keys_breadth_first() if k...
def log_config(self, logger)
write out the current configuration to a log-like object. parameters: logger - a object that implements a method called 'info' with the same semantics as the call to 'logger.info
3.563027
3.553238
1.002755
return [x for x in self.option_definitions.keys_breadth_first() if isinstance(self.option_definitions[x], Option)]
def get_option_names(self)
returns a list of fully qualified option names. returns: a list of strings representing the Options in the source Namespace list. Each item will be fully qualified with dot delimited Namespace names.
7.241497
8.191916
0.883981
# a set of known reference_value_from_links set_of_reference_value_option_names = set() for key in keys: if key in finished_keys: continue an_option = self.option_definitions[key] if an_option.reference_value_from: ful...
def _create_reference_value_options(self, keys, finished_keys)
this method steps through the option definitions looking for alt paths. On finding one, it creates the 'reference_value_from' links within the option definitions and populates it with copied options.
4.133586
3.790395
1.090542
for a_value_source in self.values_source_list: try: if a_value_source.always_ignore_mismatches: continue except AttributeError: # ok, this values source doesn't have the concept # always igoring mismatches, we w...
def _check_for_mismatches(self, known_keys)
check for bad options from value sources
4.813418
4.652338
1.034624
config = mapping_class() self._walk_config_copy_values( self.option_definitions, config, mapping_class ) return config
def _generate_config(self, mapping_class)
This routine generates a copy of the DotDict based config
8.578183
7.760006
1.105435
print("PGPooledTransaction - shutting down connection pool") for name, conn in self.pool.iteritems(): conn.close() print("PGPooledTransaction - connection %s closed" % name)
def close(self)
close all pooled connections
7.97668
6.274931
1.271198
target_type = type(target_action_instance) for key, value in six.iteritems(registry['action']): if value is target_type: if key is None: return 'store' return key return None
def find_action_name_by_value(registry, target_action_instance)
the association of a name of an action class with a human readable string is exposed externally only at the time of argument definitions. This routine, when given a reference to argparse's internal action registry and an action, will find that action and return the name under which it was registered.
4.025529
4.808742
0.837127
args = inspect.getargspec(an_action.__class__.__init__).args kwargs = dict( (an_attr, getattr(an_action, an_attr)) for an_attr in args if ( an_attr not in ('self', 'required') and getattr(an_action, an_attr) is not None ) ) action_name = find_...
def get_args_and_values(parser, an_action)
this rountine attempts to reconstruct the kwargs that were used in the creation of an action object
2.830444
2.7421
1.032218
#"""assume that source is of type argparse try: destination.update(source.get_required_config()) except AttributeError: # looks like the user passed in a real arpgapse parser rather than our # bastardized version of one. No problem, we can work with it, # though the tra...
def setup_definitions(source, destination)
this method stars the process of configman reading and using an argparse instance as a source of configuration definitions.
8.147935
7.792304
1.045639
# save a local copy of the namespace self.namespaces[name] = a_namespace # iterate through the namespace branding each of the options with the # name of the subparser to which they belong for k in a_namespace.keys_breadth_first(): an_option = a_namespace[k] ...
def add_namespace(self, name, a_namespace)
as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.
7.631522
6.162298
1.238422
command_name = args[0] new_kwargs = kwargs.copy() new_kwargs['configman_subparsers_option'] = self._configman_option new_kwargs['subparser_name'] = command_name subparsers = self._configman_option.foreign_data.argparse.subparsers a_subparser = super(ConfigmanSubP...
def add_parser(self, *args, **kwargs)
each time a subparser action is used to create a new parser object we must save the original args & kwargs. In a later phase of configman, we'll need to reproduce the subparsers exactly without resorting to copying. We save the args & kwargs in the 'foreign_data' section of the configm...
3.9779
2.990343
1.330249
required_config = Namespace() # add current options to a copy of required config for k, v in iteritems_breadth_first(self.required_config): required_config[k] = v # get any option found in any subparsers try: subparser_namespaces = ( ...
def get_required_config(self)
because of the exsistance of subparsers, the configman options that correspond with argparse arguments are not a constant. We need to produce a copy of the namespace rather than the actual embedded namespace.
7.04535
6.040234
1.166403
kwargs['parser_class'] = self.__class__ kwargs['action'] = ConfigmanSubParsersAction subparser_action = super(ArgumentParser, self).add_subparsers( *args, **kwargs ) self._argparse_subparsers = subparser_action if "dest" not in kwargs o...
def add_subparsers(self, *args, **kwargs)
When adding a subparser, we need to ensure that our version of the SubparserAction object is returned. We also need to create the corresponding configman Option object for the subparser and pack it's foreign data section with the original args & kwargs.
4.385029
3.720403
1.178643
# load the config_manager within the scope of the method that uses it # so that we avoid circular references in the outer scope from configman.config_manager import ConfigurationManager configuration_manager = ConfigurationManager( definition_source=[self.get_requir...
def parse_args(self, args=None, namespace=None)
this method hijacks the normal argparse Namespace generation, shimming configman into the process. The return value will be a configman DotDict rather than an argparse Namespace.
8.752536
8.40763
1.041023
# load the config_manager within the scope of the method that uses it # so that we avoid circular references in the outer scope from configman.config_manager import ConfigurationManager configuration_manager = ConfigurationManager( definition_source=[self.get_require...
def parse_known_args(self, args=None, namespace=None)
this method hijacks the normal argparse Namespace generation, shimming configman into the process. The return value will be a configman DotDict rather than an argparse Namespace.
8.487123
7.786192
1.090022
return "%s%s%s" % ( open_bracket_char, delimiter.join( local_to_str(x) for x in a_list ), close_bracket_char )
def sequence_to_string( a_list, open_bracket_char='[', close_bracket_char=']', delimiter=", " )
a dedicated function that turns a list into a comma delimited string of items converted. This method will flatten nested lists.
2.696515
2.728419
0.988307
t_as_string = to_str(t) if not is_identifier(t_as_string): # this class expanded into something other than a single identifier # we can ignore it. This is the case when we encounter something # like the configman.converter.str_to_classes_in_namespaces # InnerClassList. We ...
def get_import_for_type(t)
given a type, return a tuple of the (module-path, type_name) or (None, None) if it is a built in.
6.181697
5.862257
1.054491
try: return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') except ValueError: try: return datetime.datetime.strptime(s, '%Y-%m-%d') except ValueError: return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
def datetime_from_ISO_string(s)
Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S and convert it into an instance of datetime.datetime
1.459596
1.512805
0.964828
try: input_str = input_str.replace(' ', ':') except (TypeError, AttributeError): from configman.converters import to_str raise TypeError('%s should have been a string' % to_str(input_str)) days, hours, minutes, seconds = 0, 0, 0, 0 details = input_str.split(':') if len(d...
def str_to_timedelta(input_str)
a string conversion function for timedelta for strings in the format DD:HH:MM:SS or D HH:MM:SS
2.170573
2.172407
0.999156
days = aTimedelta.days temp_seconds = aTimedelta.seconds hours = int(temp_seconds / 3600) minutes = int((temp_seconds - hours * 3600) / 60) seconds = temp_seconds - hours * 3600 - minutes * 60 return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds)
def timedelta_to_str(aTimedelta)
a conversion function for time deltas to string in the form DD:HH:MM:SS
1.710615
1.743377
0.981208
with open(file_name, 'r') as f: s = f.read() nodes = ast.parse(s) module_imports = get_nodes_by_instance_type(nodes, _ast.Import) specific_imports = get_nodes_by_instance_type(nodes, _ast.ImportFrom) assignment_objs = get_nodes_by_instance_type(nodes, _ast.Assign) call_objects = ...
def parse_source_file(file_name)
Parses the AST of Python file for lines containing references to the argparse module. returns the collection of ast objects found. Example client code: 1. parser = ArgumentParser(desc="My help Message") 2. parser.add_argument('filename', help="Name of the file to load") 3. parser.add_ar...
3.141175
3.093374
1.015452
short_options_str, long_options_list = self.getopt_create_opts( config_manager.option_definitions ) try: if ignore_mismatches: fn = ValueSource.getopt_with_ignore else: fn = getopt.gnu_getopt # here getopt l...
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict)
This is the black sheep of the crowd of ValueSource implementations. It needs to know ahead of time all of the parameters that it will need, but we cannot give it. We may not know all the parameters because not all classes may have been expanded yet. The two parameters allow this Value...
4.007024
3.994838
1.00305
opts = [] prog_args = [] if isinstance(longopts, str): longopts = [longopts] else: longopts = list(longopts) while args: if args[0] == '--': prog_args += args[1:] break if args[0].startswith(...
def getopt_with_ignore(args, shortopts, longopts=[])
my_getopt(args, options[, long_options]) -> opts, args This function works like gnu_getopt(), except that unknown parameters are ignored rather than raising an error.
2.037348
2.058907
0.989529
if isinstance(name, Option): an_option = name name = an_option.name else: an_option = Option(name, *args, **kwargs) current_namespace = self name_parts = name.split('.') for a_path_component in name_parts[:-1]: if a_path_c...
def add_option(self, name, *args, **kwargs)
add an option to the namespace. This can take two forms: 'name' is a string representing the name of an option and the kwargs are its parameters, or 'name' is an instance of an Option object
2.111186
2.164821
0.975224
if y.ndim == 1: y = y.reshape(-1, 1) if x.ndim == 1: x = x.reshape(-1, 1) xscaled = self.x_scaler.fit_transform(x) yscaled = self.y_scaler.fit_transform(y) ssx_comp = list() ssy_comp = list() # Obtain residual sum of squares for...
def _cummulativefit(self, x, y)
Measure the cumulative Regression sum of Squares for each individual component. :param x: Data matrix to fit the PLS model. :type x: numpy.ndarray, shape [n_samples, n_features] :param y: Data matrix to fit the PLS model. :type y: numpy.ndarray, shape [n_samples, n_features] :re...
2.30857
2.233251
1.033726
plt.figure() lev = self.leverages() plt.xlabel('Sample Index') plt.ylabel('Leverage') plt.bar(left=range(lev.size), height=lev) plt.hlines(y=1/lev.size, xmin=0, xmax=lev.size, colors='r', linestyles='--') plt.show() return None
def plot_leverages(self)
Leverage (h) per observation, with a red line plotted at y = 1/Number of samples (expected :return: Plot with observation leverages (h)
3.150679
2.869222
1.098095
# if we are fitting on 1D arrays, scale might be a scalar if numpy.isscalar(scale): if scale == .0: scale = 1. return scale elif isinstance(scale, numpy.ndarray): if copy: # New array to avoid side-effects scale = scale.copy() scale[s...
def _handle_zeros_in_scale(scale, copy=True)
Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features.
3.64846
3.4364
1.06171
# Checking one attribute is enough, because they are all set together # in partial_fit if hasattr(self, 'scale_'): del self.scale_ del self.n_samples_seen_ del self.mean_ del self.var_
def _reset(self)
Reset internal data-dependent state of the scaler, if necessary. __init__ parameters are not touched.
7.073109
4.664693
1.516307
# Reset internal state before fitting self._reset() return self.partial_fit(X, y)
def fit(self, X, y=None)
Compute the mean and standard deviation from a dataset to use in future scaling operations. :param X: Data matrix to scale. :type X: numpy.ndarray, shape [n_samples, n_features] :param y: Passthrough for Scikit-learn ``Pipeline`` compatibility. :type y: None :return: Fitted obje...
5.817584
8.295847
0.701265
X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) # Even in the case of `with_mean=False`, we update the mean anyway # This is needed for the incremental computation of the var # See...
def partial_fit(self, X, y=None)
Performs online computation of mean and standard deviation on X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is read from a continuous stream. The algorithm ...
2.317875
2.362975
0.980914
check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy X = check_array(X, accept_sparse='csr', copy=copy, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_mean: ...
def transform(self, X, y=None, copy=None)
Perform standardization by centering and scaling using the parameters. :param X: Data matrix to scale. :type X: numpy.ndarray, shape [n_samples, n_features] :param y: Passthrough for scikit-learn ``Pipeline`` compatibility. :type y: None :param bool copy: Copy the X matrix. ...
2.231431
2.273724
0.981399
check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstri...
def inverse_transform(self, X, copy=None)
Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, ...
2.609232
2.722942
0.95824
# TODO check with matlab and simca try: if block == 'X': return np.dot(self.scores_t, np.dot(np.linalg.inv(np.dot(self.scores_t.T, self.scores_t), self.scores_t.T))) elif block == 'Y': return np.dot(self.scores_u, np.dot(np.linalg.inv(np.d...
def leverages(self, block='X')
Calculate the leverages for each observation :return: :rtype:
3.042248
2.979678
1.020999
if isinstance(obj, list): return [_recurse_replace(x, key, new_key, sub, remove) for x in obj] if isinstance(obj, dict): for k, v in list(obj.items()): if k == key and v in sub: obj[new_key] = sub[v] if remove: del obj[key] ...
def _recurse_replace(obj, key, new_key, sub, remove)
Recursive helper for `replace_by_key`
1.571859
1.585512
0.991389
if not new_key: new_key = key remove = False orig = pif.as_dictionary() new = _recurse_replace(orig, to_camel_case(key), to_camel_case(new_key), subs, remove) return pypif.pif.loads(json.dumps(new))
def replace_by_key(pif, key, subs, new_key=None, remove=False)
Replace values that match a key Deeply traverses the pif object, looking for `key` and replacing values in accordance with `subs`. If `new_key` is set, the replaced values are assigned to that key. If `remove` is `True`, the old `key` pairs are removed.
5.831777
6.064272
0.961661
warn("This method has been deprecated in favor of get_property_by_name") return next((x for x in pif.properties if x.name == name), None)
def get_propety_by_name(pif, name)
Get a property by name
5.160807
4.582904
1.1261
return next((x for x in pif.properties if x.name == name), None)
def get_property_by_name(pif, name)
Get a property by name
4.481555
4.237411
1.057616
if key in ambig: return if key in unambig and value != unambig[key]: ambig.add(key) del unambig[key] return unambig[key] = value return
def new_keypair(key, value, ambig, unambig)
Check new keypair against existing unambiguous dict :param key: of pair :param value: of pair :param ambig: set of keys with ambig decoding :param unambig: set of keys with unambig decoding :return:
3.184354
3.128762
1.017768
for k in child_ambig: ambig.add(k) if k in unambig: del unambig[k] for k, v in child_unambig.items(): new_keypair(k, v, ambig, unambig) return
def add_child_ambig(child_ambig, child_unambig, ambig, unambig)
Add information about decodings of a child object :param child_ambig: ambiguous set from child :param child_unambig: unambiguous set from child :param ambig: set of keys storing ambig decodings :param unambig: dictionary storing unambiguous decodings :return:
3.021266
3.355937
0.900275
if 'CITRINATION_API_KEY' not in environ: raise ValueError("'CITRINATION_API_KEY' is not set as an environment variable") if not site: site = environ.get("CITRINATION_SITE", "https://citrination.com") return CitrinationClient(environ['CITRINATION_API_KEY'], site)
def get_client(site=None)
Get a citrination client
2.767723
2.163822
1.27909
if not uids: uids = [str(hash(dumps(x))) for x in pifs] for pif, uid in zip(pifs, uids): pif.uid = uid return pifs
def set_uids(pifs, uids=None)
Set the uids in a PIF, explicitly if the list of UIDs is passed in :param pifs: to set UIDs in :param uids: to set; defaults to a hash of the object :return:
2.89048
3.184905
0.907556
return "{site}/datasets/{dataset}/version/{version}/pif/{uid}".format( uid=pif.uid, version=version, dataset=dataset, site=site )
def get_url(pif, dataset, version=1, site="https://citrination.com")
Construct the URL of a PIF on a site :param pif: to construct URL for :param dataset: the pif will belong to :param version: of the PIF (default: 1) :param site: for the dataset (default: https://citrination.com) :return: the URL as a string
4.47513
4.438865
1.00817
if not isinstance(pif, ChemicalSystem): return pif if not pif.chemical_formula: return pif else: expanded_formula_no_special_char = _expand_formula_( pif.chemical_formula) element_array = _create_emprical_compositional_array_( expanded_formula_no_...
def calculate_ideal_atomic_percent(pif)
Calculates ideal atomic percents from a chemical formula string from a pif. Returns an appended pif with composition elements modified or added. :param pif: a ChemicalSystem pif :return: modified pif object
3.729179
3.359209
1.110136
if not isinstance(pif, ChemicalSystem): return pif if not pif.chemical_formula: return pif else: expanded_formula_no_special_char = _expand_formula_( pif.chemical_formula) element_array = _create_emprical_compositional_array_( expanded_formula_no_...
def calculate_ideal_weight_percent(pif)
Calculates ideal atomic weight percents from a chemical formula string from a pif. Returns an appended pif with composition elements modified or added. :param pif: a ChemicalSystem pif :return: modified pif object
3.779255
3.427906
1.102497
formula_string = re.sub(r'[^A-Za-z0-9\(\)\[\]\·\.]+', '', formula_string) hydrate_pos = formula_string.find('·') if hydrate_pos >= 0: formula_string = _expand_hydrate_(hydrate_pos, formula_string) search_result = re.search( r'(?:[\(\[]([A-Za-z0-9]+)[\)\]](\d*))', formula_str...
def _expand_formula_(formula_string)
Accounts for the many ways a user may write a formula string, and returns an expanded chemical formula string. Assumptions: -The Chemical Formula string it is supplied is well-written, and has no hanging parethneses -The number of repeats occurs after the elemental symbol or ) ] character EXCEPT in the case...
2.459179
2.37036
1.037471
hydrate = formula_string[hydrate_pos + 1:] hydrate_string = "" multiplier = float(re.search(r'^[\d\.]+', hydrate).group()) element_array = re.findall('[A-Z][^A-Z]*', hydrate) for e in element_array: occurance_array = re.findall('[0-9][^0-9]*', e) if len(occurance_array) == 0: ...
def _expand_hydrate_(hydrate_pos, formula_string)
Handles the expansion of hydrate portions of a chemical formula, and expands out the coefficent to all elements :param hydrate_pos: the index in the formula_string of the · symbol :param formula_string: the unexpanded formula string :return: a formula string without the · character with the hydrate portion...
2.377455
2.429917
0.97841
element_array = re.findall( '[A-Z][^A-Z]*', expanded_chemical_formaula_string) split_element_array = [] for s in element_array: m = re.match(r"([a-zA-Z]+)([0-9\.]*)", s, re.I) if m: items = m.groups() if items[1] == "": items = (it...
def _create_compositional_array_(expanded_chemical_formaula_string)
Splits an expanded chemical formula string into an array of dictionaries containing information about each element :param expanded_chemical_formaula_string: a clean (not necessarily emperical, but without any special characters) chemical formula string, as returned by _expand_formula_() :return: an array of di...
2.978487
3.020912
0.985956
condensed_array = [] for e in elemental_array: exists = False for k in condensed_array: if k["symbol"] == e["symbol"]: exists = True k["occurances"] += e["occurances"] break if not exists: condensed_array.append...
def _consolidate_elemental_array_(elemental_array)
Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements :param elemental_array: an elemental array generated from _create_compositional_array_() :return: an array ...
2.311465
2.328144
0.992836
for a in elemental_array: this_atomic_weight = elements_data[a["symbol"]]["atomic_weight"] a["weight"] = a["occurances"] * this_atomic_weight return elemental_array
def _add_ideal_atomic_weights_(elemental_array)
Uses elements.json to find the molar mass of the element in question, and then multiplies that by the occurances of the element. Adds the "weight" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionaries containing information about the elements in the system ...
4.359716
3.570675
1.220978
t_mass = _calculate_total_mass_(elemental_array) for a in elemental_array: a["weight_percent"] = a["weight"] / t_mass * 100 return elemental_array
def _add_ideal_weight_percent_(elemental_array)
Adds the "weight_percent" property to each of the dictionaries in elemental_array :param elemental_array: an array of dictionaries containing information about the elements in the system :return: the appended elemental_array
3.056474
3.286702
0.929952
n_atoms = _calculate_n_atoms_(elemental_array) for e in elemental_array: e["atomic_percent"] = e["occurances"] / n_atoms * 100 return elemental_array
def _add_atomic_percents_(elemental_array)
Adds ideal atomic percents to a emperical compositional element array generated using _create_emprical_compositional_array_() :param elemental_array: an array of dictionaries containing information about the elements in the system :return: the elemental_array with the atomic percent of each element added
3.186079
3.257197
0.978166
if pif.composition is None: pif.composition = [] for i, c in enumerate(pif.composition): if c.element == elemental_symbol or c.element.lower( ) == elements_data[elemental_symbol]["name"].lower(): return [c, i] i += 1 return False
def _get_element_in_pif_composition_(pif, elemental_symbol)
If the element in question if in the composition array in the pif, it returns that Composition object and the position in the composition array otherwise it returns False :param pif: ChemicalSystem Pif in question :param elemental_symbol: string of the atomic symbol of the element in question :return: eith...
4.308942
3.5917
1.199694
name = Name() if "," in full_name: toks = full_name.split(",") name.family = toks[0] name.given = ",".join(toks[1:]).strip() else: toks = full_name.split() name.given = toks[0] name.family = " ".join(toks[1:]).strip() return name
def parse_name_string(full_name)
Parse a full name into a Name object :param full_name: e.g. "John Smith" or "Smith, John" :return: Name object
2.01458
2.029478
0.99266
name = Name() if "creatorName" in creator: name = parse_name_string(creator["creatorName"]) if "familyName" in creator: name.family = creator["familyName"] if "givenName" in creator: name.given = creator["givenName"] person = Person(name=name, tags=creator.get("affiliat...
def creator_to_person(creator)
Parse the creator block in datacite into a Person :param creator: block in datacite format :return: Person
2.960871
2.965219
0.998533
ref = Reference() if dc.get('identifier', {}).get('identifierType') == "DOI": ref.doi = dc.get('identifier', {}).get('identifier') ref.title = dc.get('title') ref.publisher = dc.get('publisher') ref.year = dc.get('publicationYear') ref.authors = [creator_to_person(x).name for x in ...
def datacite_to_pif_reference(dc)
Parse a top-level datacite dictionary into a Reference :param dc: dictionary containing datacite metadata :return: Reference corresponding to that datacite entry
2.694265
2.774379
0.971123
if not query and not dataset_id: raise ValueError("Either query or dataset_id must be specified") if query and dataset_id: raise ValueError("Both query and dataset_id were specified; pick one or the other.") if not query: query = PifSystemReturningQuery( query=DataQu...
def query_to_mdf_records(query=None, dataset_id=None, mdf_acl=None)
Evaluate a query and return a list of MDF records If a datasetID is specified by there is no query, a simple whole dataset query is formed for the user
3.497529
3.545161
0.986564
res = {} res["mdf"] = _to_meta_data(pif_obj, dataset_hit, mdf_acl) res[res["mdf"]["source_name"]] = _to_user_defined(pif_obj) return dumps(res)
def pif_to_mdf_record(pif_obj, dataset_hit, mdf_acl)
Convert a PIF into partial MDF record
4.83288
4.696744
1.028985
pif = pif_obj.as_dictionary() dataset = dataset_hit.as_dictionary() mdf = {} try: if pif.get("names"): mdf["title"] = pif["names"][0] else: mdf["title"] = "Citrine PIF " + str(pif["uid"]) if pif.get("chemicalFormula"): mdf["composition"] ...
def _to_meta_data(pif_obj, dataset_hit, mdf_acl)
Convert the meta-data from the PIF into MDF
2.531132
2.468193
1.0255
res = {} # make a read view to flatten the hierarchy rv = ReadView(pif_obj) # Iterate over the keys in the read view for k in rv.keys(): name, value = _extract_key_value(rv[k].raw) # add any objects that can be extracted if name and value is not None: res[n...
def _to_user_defined(pif_obj)
Read the systems in the PIF to populate the user-defined portion
4.846842
4.812161
1.007207
to_replace = ["/", "\\", "*", "^", "#", " ", "\n", "\t", ",", ".", ")", "(", "'", "`", "-"] to_remove = ["$", "{", "}"] cat = name if units: cat = "_".join([name, units]) for c in to_replace: cat = cat.replace(c, "_") for c in to_remove: cat = cat.replace(c, "") ...
def _construct_new_key(name, units=None)
Construct an MDF safe key from the name and units
3.995826
3.827089
1.04409
key = None; value = None # Parse a Value object, which includes Properties if isinstance(obj, Value): key = _construct_new_key(obj.name, obj.units) value = [] if obj.scalars: value = [(val.value if isinstance(val, Scalar) else val) for val in ob...
def _extract_key_value(obj)
Extract the value from the object and make a descriptive key
4.150035
4.095294
1.013367
from polysh.control_commands_helpers import handle_control_command data = the_stdin_thread.input_buffer.get() remote_dispatcher.log(b'> ' + data) if data.startswith(b':'): try: handle_control_command(data[1:-1].decode()) except UnicodeDecodeError as e: conso...
def process_input_buffer()
Send the content of the input buffer to all remote processes, this must be called in the main thread
4.095895
4.014865
1.020182
the_stdin_thread.socket_write.send(c) while True: try: the_stdin_thread.socket_write.recv(1) except socket.error as e: if e.errno != errno.EINTR: raise else: break
def write_main_socket(c)
Synchronous write to the main socket, wait for ACK
3.723359
3.534795
1.053345
if cached_result is None: try: tasks = os.listdir('/proc/self/task') except OSError as e: if e.errno != errno.ENOENT: raise cached_result = os.getpid() else: tasks.remove(str(os.getpid())) assert len(tasks) == 1...
def get_stdin_pid(cached_result=None)
Try to get the PID of the stdin thread, otherwise get the whole process ID
2.454861
2.40247
1.021807
dupped_stdin = os.dup(0) # Backup the stdin fd assert not the_stdin_thread.interrupt_asked # Sanity check the_stdin_thread.interrupt_asked = True # Not user triggered os.lseek(tempfile_fd, 0, 0) # Rewind in the temp file os.dup2(tempfile_fd, 0) # This will make raw_input() return pid =...
def interrupt_stdin_thread()
The stdin thread may be in raw_input(), get out of it
4.975932
4.707263
1.057076