code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
logger.debug("Documenting dataset structure") key = self.get_structure_key() text = json.dumps(self._structure_parameters, indent=2, sort_keys=True) self.put_text(key, text) key = self.get_dtool_readme_key() self.put_text(key, self._dtool_readme_txt)
def _document_structure(self)
Document the structure of the dataset.
4.778499
4.086667
1.16929
parsed_uri = generous_parse_uri(base_uri) uri_list = [] path = parsed_uri.path if IS_WINDOWS: path = unix_to_windows_path(parsed_uri.path, parsed_uri.netloc) for d in os.listdir(path): dir_path = os.path.join(path, d) if not os.pat...
def list_dataset_uris(cls, base_uri, config_path)
Return list containing URIs in location given by base_uri.
3.250117
3.191573
1.018344
with open(key, "w") as fh: fh.write(text)
def put_text(self, key, text)
Put the text into the storage associated with the key.
4.795571
4.862877
0.986159
fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
def get_size_in_bytes(self, handle)
Return the size in bytes.
4.549733
3.874699
1.174216
fpath = self._fpath_from_handle(handle) datetime_obj = datetime.datetime.utcfromtimestamp( os.stat(fpath).st_mtime ) return timestamp(datetime_obj)
def get_utc_timestamp(self, handle)
Return the UTC timestamp.
3.951422
3.59512
1.099107
fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
def get_hash(self, handle)
Return the hash.
14.18063
12.342454
1.148931
overlay_names = [] if not os.path.isdir(self._overlays_abspath): return overlay_names for fname in os.listdir(self._overlays_abspath): name, ext = os.path.splitext(fname) overlay_names.append(name) return overlay_names
def list_overlay_names(self)
Return list of overlay names.
2.421472
2.289545
1.057621
manifest = self.get_manifest() item = manifest["items"][identifier] item_abspath = os.path.join(self._data_abspath, item["relpath"]) return item_abspath
def get_item_abspath(self, identifier)
Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed
3.686886
4.370699
0.843546
# Ensure that the specified path does not exist and create it. if os.path.exists(self._abspath): raise(StorageBrokerOSError( "Path already exists: {}".format(self._abspath) )) # Make sure the parent directory exists. parent, _ = os.path....
def _create_structure(self)
Create necessary structure to hold a dataset.
3.433893
3.142665
1.092669
# Define the destination path and make any missing parent directories. dest_path = os.path.join(self._data_abspath, relpath) dirname = os.path.dirname(dest_path) mkdir_parents(dirname) # Copy the file across. shutil.copyfile(fpath, dest_path) return re...
def put_item(self, fpath, relpath)
Put item with content from fpath at relpath in dataset. Missing directories in relpath are created on the fly. :param fpath: path to the item on disk :param relpath: relative path name given to the item in the dataset as a handle :returns: the handle given to th...
3.805002
4.271207
0.890849
path = self._data_abspath path_length = len(path) + 1 for dirpath, dirnames, filenames in os.walk(path): for fn in filenames: path = os.path.join(dirpath, fn) relative_path = path[path_length:] if IS_WINDOWS: ...
def iter_item_handles(self)
Return iterator over item handles.
3.145091
2.972328
1.058124
if not os.path.isdir(self._metadata_fragments_abspath): os.mkdir(self._metadata_fragments_abspath) prefix = self._handle_to_fragment_absprefixpath(handle) fpath = prefix + '.{}.json'.format(key) with open(fpath, 'w') as fh: json.dump(value, fh)
def add_item_metadata(self, handle, key, value)
Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value
4.360334
4.70574
0.926599
if not os.path.isdir(self._metadata_fragments_abspath): return {} prefix = self._handle_to_fragment_absprefixpath(handle) def list_abspaths(dirname): for f in os.listdir(dirname): yield os.path.join(dirname, f) files = [f for f in list...
def get_item_metadata(self, handle)
Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata
3.681367
3.678454
1.000792
allowed = set([v[0] for v in _STRUCTURE_PARAMETERS.values()]) for d in os.listdir(self._abspath): if d not in allowed: msg = "Rogue content in base of dataset: {}".format(d) raise(DiskStorageBrokerValidationWarning(msg))
def pre_freeze_hook(self)
Pre :meth:`dtoolcore.ProtoDataSet.freeze` actions. This method is called at the beginning of the :meth:`dtoolcore.ProtoDataSet.freeze` method. It may be useful for remote storage backends to generate caches to remove repetitive time consuming calls
16.20195
15.554945
1.041595
if os.path.isdir(self._metadata_fragments_abspath): shutil.rmtree(self._metadata_fragments_abspath)
def post_freeze_hook(self)
Post :meth:`dtoolcore.ProtoDataSet.freeze` cleanup actions. This method is called at the end of the :meth:`dtoolcore.ProtoDataSet.freeze` method. In the :class:`dtoolcore.storage_broker.DiskStorageBroker` it removes the temporary directory for storing item metadata fragment files.
7.235794
4.536705
1.594945
payload = { 'aud': API_OAUTH, 'exp': time.time()+600, # 10 minutes 'sub': self.email } header = {'Content-type':'application/x-www-form-urlencoded'} assertion = jwt.encode(payload, self.private_key, algorithm='RS256') assertion = ass...
def get_token(self)
Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy cont...
2.546769
2.524832
1.008689
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
def get_model_info(self, model_id, token=None, url=API_GET_MODEL_INFO)
Gets information about a specific previously trained model, ie: stats and accuracy :param model_id: string, model_id previously supplied by the API returns: requests object
4.009694
4.076436
0.983627
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.get(the_url, headers=h) return r
def get_datasets_info(self, token=None, url=API_GET_DATASETS_INFO)
Gets information on all datasets for this account returns: requests object
4.689902
4.384107
1.069751
auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'sampleLocation':picture_url, 'modelId':model_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=...
def get_url_image_prediction(self, model_id, picture_url, token=None, url=API_GET_PREDICTION_IMAGE_URL)
Gets a prediction from a supplied picture url based on a previously trained model. :param model_id: string, once you train a model you'll be given a model id to use. :param picture_url: string, in the form of a url pointing to a publicly accessible image file. returns: re...
3.64192
3.854916
0.944747
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) m = MultipartEncoder(fields={'sampleBa...
def get_fileb64_image_prediction(self, model_id, filename, token=None, url=API_GET_PREDICTION_IMAGE_URL)
Gets a prediction from a supplied image on your machine, by encoding the image data as b64 and posting to the API. :param model_id: string, once you train a model you'll be given a model id to use. :param filename: string, the name of a file to be posted to the api. retur...
2.759342
2.836704
0.972728
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url encoded_string = b64_encoded_string m = MultipartEncoder(fields={'sampleBase64Content':encoded_string, 'modelId':model_id}) h = {'Au...
def get_b64_image_prediction(self, model_id, b64_encoded_string, token=None, url=API_GET_PREDICTION_IMAGE_URL)
Gets a prediction from a supplied image enconded as a b64 string, useful when uploading images to a server backed by this library. :param model_id: string, once you train a model you'll be given a model id to use. :param b64_encoded_string: string, a b64 enconded string representatio...
3.256409
3.540052
0.919876
auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'type':dataset_type, 'path':file_url}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) ...
def create_dataset_synchronous(self, file_url, dataset_type='image', token=None, url=API_CREATE_DATASET)
Creates a dataset so you can train models from it :param file_url: string, url to an accessible zip file containing the necessary image files and folder structure indicating the labels to train. See docs online. :param dataset_type: string, one of the dataset types, available options...
3.154415
3.316983
0.950989
auth = 'Bearer ' + self.check_for_token(token) m = MultipartEncoder(fields={'name':model_name, 'datasetId':dataset_id}) h = {'Authorization': auth, 'Cache-Control':'no-cache', 'Content-Type':m.content_type} the_url = url r = requests.post(the_url, headers=h, data=m) ...
def train_model(self, dataset_id, model_name, token=None, url=API_TRAIN_MODEL)
Train a model given a specifi dataset previously created :param dataset_id: string, the id of a previously created dataset :param model_name: string, what you will call this model attention: This may take a while and a response will be returned before the model has finish...
3.142146
3.307505
0.950005
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
def get_training_status(self, model_id, token=None, url=API_TRAIN_MODEL)
Gets status on the training process once you create a model :param model_id: string, id of the model to check returns: requests object
3.897344
4.178992
0.932604
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} if url != API_GET_MODELS: r = requests.get(the_url, headers=h) return r the_url = url.replace('<dataset_id>', dataset_id) r = requests.get(the_...
def get_models_info_for_dataset(self, dataset_id, token=None, url=API_GET_MODELS)
Gets metadata on all models available for given dataset id :param dataset_id: string, previously obtained dataset id warning: if providing your own url here, also include the dataset_id in the right place as this method will not include it for you. Otherwise use the dataset_id attrib...
3.503904
3.379451
1.036826
auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'type': (None, 'text-intent'), 'path':(None, file_url)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET)
Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: Google Drive by default gives you a link to a web ui that allows yo...
5.961133
6.58151
0.905739
auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'name': (None, name), 'datasetId':(None, dataset_id)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
def train_language_model_from_dataset(self, dataset_id, name, token=None, url=API_TRAIN_LANGUAGE_MODEL)
Trains a model given a dataset and its ID. :param dataset_id: string, the ID for a dataset you created previously. :param name: string, name for your model. returns: a request object
4.544331
4.722224
0.962329
auth = 'Bearer ' + self.check_for_token(token) h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url + '/' + model_id r = requests.get(the_url, headers=h) return r
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL)
Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object
4.190028
4.403889
0.951438
auth = 'Bearer ' + self.check_for_token(token) dummy_files = {'modelId': (None, model_id), 'document':(None, document)} h = {'Authorization': auth, 'Cache-Control':'no-cache'} the_url = url r = requests.post(the_url, headers=h, files=dummy_files) return r
def get_language_prediction_from_model(self, model_id, document, token=None, url=API_GET_LANGUAGE_PREDICTION)
Gets a prediction based on a body of text you send to a trained model you created previously. :param model_id: string, the ID for a model you created previously. :param document: string, a body of text to be classified. returns: a request object
4.497917
4.996996
0.900124
# get json files only files = [] files = [f for f in os.listdir() if f[-5:] == '.json'] if len(files) == 0: print('No json files found in this directory') return None max_boxes = 0 rows = [] for each_file in files: ...
def parse_rectlabel_app_output(self)
Internal use mostly, finds all .json files in the current folder expecting them to all have been outputted by the RectLabel app parses each file returning finally an array representing a csv file where each element is a row and the 1st element [0] is the column headers. Could be usef...
3.197909
3.021545
1.058369
result = self.parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
def save_parsed_data_to_csv(self, output_filename='output.csv')
Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience.
6.059842
3.007483
2.014921
result = self.XML_parse_rectlabel_app_output() ff = open(output_filename, 'w', encoding='utf8') for line in result: ff.write(line + '\n') ff.close()
def XML_save_parsed_data_to_csv(self, output_filename='output.csv')
Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files in the creation of an Object Detection dataset. :param output_filename string, default makes sense, but for your convenience.
5.906776
3.134707
1.884315
# make a list of all alphanumeric tokens toks = re.findall(r'[^\*\\\+\-\^\(\)]+\(?', istr) # remove the functions return [t for t in toks if not t.endswith('(')]
def tokens(istr)
Same as tokenize, but returns only tokens (and at all parantheses levels).
8.802848
8.208318
1.07243
data = set(i.rstrip('0123456789') for i in tokens(istr)) has_events = not data.isdisjoint(istr_type_evts) has_2d = not data.isdisjoint(istr_type_2d) has_1d = data.difference(istr_type_evts).difference(istr_type_2d) != set() if has_events and not (has_1d or has_2d): return 'events' ...
def istr_type(istr)
Given an "ion" specification, determine its "type", e.g. 1D, Events, etc.
2.817688
2.53552
1.111286
fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1 elif c == ')': plevel -= 1 if plevel == 0: return Fals...
def is_parans_exp(istr)
Determines if an expression is a valid function "call"
2.813985
2.621954
1.073239
if istr.strip() == '': return Trace() # remove (unnessary?) pluses from the front # TODO: plus should be abs? istr = istr.lstrip('+') # invert it if preceded by a minus sign if istr[0] == '-': return -parse_ion_string(istr[1:], analyses, twin) # this is a function or...
def parse_ion_string(istr, analyses, twin=None)
Recursive string parser that handles "ion" strings.
3.480383
3.482796
0.999307
if pedalboard is not None and pedalboard.bank is None: raise CurrentPedalboardError('Pedalboard {} has not added in any bank'.format(pedalboard)) if pedalboard == self.pedalboard and not force: return self._pedalboard = pedalboard self._device_controlle...
def set_pedalboard(self, pedalboard, notify=True, force=False)
Set the current :class:`.Pedalboard` for the pedalboard only if the ``pedalboard != current_pedalboard or force`` Is also possible unload the current pedalboard data with replacing it for ``None``:: >>> current_controller.set_pedalboard(None) .. warning:: Changing the...
3.908894
4.113119
0.950348
if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.pedalboard.index - 1 if before_index == -1: before_index = len(self.bank.pedalboards) - 1 self.set_pedalboard(self.bank.pedalboards[before_ind...
def to_before_pedalboard(self)
Change the current :class:`.Pedalboard` for the previous pedalboard. If the current pedalboard is the first in the current :class:`Bank`, the current pedalboard is will be the **last of the current Bank**. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.Cur...
2.922342
2.03755
1.434243
if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.pedalboard.index + 1 if next_index == len(self.bank.pedalboards): next_index = 0 self.set_pedalboard(self.bank.pedalboards[next_index])
def to_next_pedalboard(self)
Change the current :class:`.Pedalboard` for the next pedalboard. If the current pedalboard is the last in the current :class:`.Bank`, the current pedalboard is will be the **first of the current Bank** .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.Current...
2.626387
2.027873
1.295144
if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') before_index = self.bank.index - 1 if before_index == -1: before_index = len(self._manager.banks) - 1 self.set_bank(self._manager.banks[before_index])
def to_before_bank(self)
Change the current :class:`Bank` for the before bank. If the current bank is the first, the current bank is will be the last bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: ...
4.427752
2.797636
1.582676
if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.next_bank_index(self.bank.index) self.set_bank(self._manager.banks[next_index])
def to_next_bank(self)
Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: ...
6.352754
3.819523
1.663232
if bank not in self._manager: raise CurrentPedalboardError('Bank {} has not added in banks manager'.format(bank)) if self.bank == bank: return if bank.pedalboards: pedalboard = self._equivalent_pedalboard(bank) if try_preserve_index else bank.pedalb...
def set_bank(self, bank, try_preserve_index=False)
Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``...
4.619777
3.505934
1.317702
if isinstance(options, dict): has = lambda k: k in options get = lambda k: options[k] elif isinstance(options, object): has = lambda k: hasattr(options, k) get = lambda k: getattr(options, k) else: raise ImproperlyConfigured( '`{}` must be a dictionary-like object.'.format(options_n...
def _validate_and_get_value(options, options_name, key, _type)
Check that `options` has a value for `key` with type `_type`. Return that value. `options_name` is a string representing a human-readable name for `options` to be used when printing errors.
1.996221
1.993669
1.00128
event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not in (int, long): raise InvalidEventTime(event_time) # Generate a uuid1-like sequence from the event time with the non-time bytes # s...
def validate_event_and_assign_id(event)
Ensure that the event has a valid time. Assign a random UUID based on the event time.
5.030322
4.688457
1.072916
if not STREAM_REGEX.match(stream) or len(stream) > MAX_STREAM_LENGTH: raise InvalidStreamName(stream)
def validate_stream(stream)
Check that the stream name is well-formed.
5.057595
3.755653
1.346662
if not isinstance(settings, dict): raise ImproperlyConfigured( '{}: storage class settings must be a dict'.format(storage_class)) if not hasattr(storage_class, 'SETTINGS_VALIDATORS'): raise NotImplementedError( '{}: storage class must define `SETTINGS_VALIDATORS`'.format( storage_c...
def validate_storage_settings(storage_class, settings)
Given a `storage_class` and a dictionary of `settings` to initialize it, this method verifies that all the settings are valid.
2.374843
2.418254
0.982049
# Validate `storage` storage = _validate_and_get_value(settings, 'settings', 'storage', dict) for name, options in storage.iteritems(): if 'backend' not in options: raise ImproperlyConfigured( '`storage[\'{}\'] must contain a `backend` key'.format(name)) path = options['backend'] ...
def validate_settings(settings)
`settings` is either a dictionary or an object containing Kronos settings (e.g., the contents of conf/settings.py). This function checks that all required settings are present and valid.
2.490704
2.486002
1.001891
vals = cls.get_non_empty_vals({ cls._to_snake_case(k): v for k, v in kwargs.items() }) remove = [] for attr, val in vals.items(): try: vals[attr] = cls._parse_property(attr, val) except HelpScoutValidationException: ...
def from_api(cls, **kwargs)
Create a new instance from API arguments. This will switch camelCase keys into snake_case for instantiation. It will also identify any ``Instance`` or ``List`` properties, and instantiate the proper objects using the values. The end result being a fully Objectified and Pythonified API ...
4.602348
4.480952
1.027092
vals = {} for attribute, attribute_type in self._props.items(): prop = getattr(self, attribute) vals[self._to_camel_case(attribute)] = self._to_api_value( attribute_type, prop, ) return vals
def to_api(self)
Return a dictionary to send to the API. Returns: dict: Mapping representing this object that can be sent to the API.
4.354292
4.287166
1.015657
if not value: return None if isinstance(attribute_type, properties.Instance): return value.to_api() if isinstance(attribute_type, properties.List): return self._parse_api_value_list(value) return attribute_type.serialize(value)
def _to_api_value(self, attribute_type, value)
Return a parsed value for the API.
4.030901
3.576109
1.127175
try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values)
def _parse_api_value_list(self, values)
Return a list field compatible with the API.
8.215872
6.162808
1.333138
prop = cls._props.get(name) return_value = value if not prop: logger.debug( '"%s" with value "%s" is not a valid property for "%s".' % ( name, value, cls, ), ) return_value = None elif isi...
def _parse_property(cls, name, value)
Parse a property received from the API into an internal object. Args: name (str): Name of the property on the object. value (mixed): The unparsed API value. Raises: HelpScoutValidationException: In the event that the property name is not found. ...
3.040199
3.096486
0.981822
attributes = [] for v in value: try: attributes.append( prop.prop.instance_class.from_api(**v), ) except AttributeError: attributes.append(v) return attributes
def _parse_property_list(prop, value)
Parse a list property and return a list of the results.
5.995387
5.094081
1.176932
sub_string = r'\1_\2' string = REGEX_CAMEL_FIRST.sub(sub_string, string) return REGEX_CAMEL_SECOND.sub(sub_string, string).lower()
def _to_snake_case(string)
Return a snake cased version of the input string. Args: string (str): A camel cased string. Returns: str: A snake cased string.
4.426822
5.69977
0.776667
components = string.split('_') return '%s%s' % ( components[0], ''.join(c.title() for c in components[1:]), )
def _to_camel_case(string)
Return a camel cased version of the input string. Args: string (str): A snake cased string. Returns: str: A camel cased string.
3.750514
4.10665
0.913278
if output is None: if self.dbfile is None: return output = self.dbfile with open(output, 'w') as f: f.write(self._dump())
def save(self, output=None)
Save the database to a file. If ``output`` is not given, the ``dbfile`` given in the constructor is used.
3.439198
2.59251
1.32659
if text is not None: words = re.split(r'\s+', text) wlen = len(words) for i in range(wlen - 2): self._insert(words[i:i+3]) if source is not None: with open(source, 'r') as f: self.feed(f.read())
def feed(self, text=None, source=None)
Feed some text to the database, either from a string (``text``) or a file (``source``). >>> db = TrigramsDB() >>> db.feed("This is my text") >>> db.feed(source="some/file.txt")
2.723976
2.902528
0.938484
words = list(map(self._sanitize, kwargs.get('words', []))) max_wlen = kwargs.get('wlen', 70) wlen = len(words) if wlen < 2: if not self._db: return '' if wlen == 0: words = sample(self._db.keys(), 1)[0].split(self._WSEP)...
def generate(self, **kwargs)
Generate some text from the database. By default only 70 words are generated, but you can change this using keyword arguments. Keyword arguments: - ``wlen``: maximum length (words) - ``words``: a list of words to use to begin the text with
3.064003
2.956289
1.036436
if self.dbfile is not None: with open(self.dbfile, 'r') as f: self._db = json.loads(f.read()) else: self._db = {}
def _load(self)
Load the database from its ``dbfile`` if it has one
2.766692
2.020676
1.369192
key = self._WSEP.join([self._sanitize(word1), self._sanitize(word2)]) key = key.lower() if key not in self._db: return return sample(self._db[key], 1)[0]
def _get(self, word1, word2)
Return a possible next word after ``word1`` and ``word2``, or ``None`` if there's no possibility.
4.556732
4.774019
0.954486
words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) # we could use a set here, but sets are not serializables in JSON. This # is the same reason we use dicts instead of defaultdic...
def _insert(self, trigram)
Insert a trigram in the DB
5.853646
5.635564
1.038697
cohort = plan['cohort'] action = plan['action'] source = plan['source'] # Calculate the start and end dates, in Kronos time, of the # beginning and end of the cohort and action streams that will be # relevant. cohort_start = datetime_to_kronos_time(_date_to_datetime(cohort['start'])) cohort_span = t...
def cohort_queryplan(plan)
Input: { 'source': 'kronos', # Name of data source from settings 'cohort': {'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from. 'transform': lambda x: x, # Transformations on the kstream. 'start': date.now(), # The day of the first cohort. 'unit': ...
3.036096
2.700058
1.124456
if mass is np.nan: return None for massLimit, massType in planetAssumptions['massType']: if mass < massLimit: return massType
def planetMassType(mass)
Returns the planet masstype given the mass and using planetAssumptions['massType']
8.358798
4.67565
1.78773
if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
def planetRadiusType(radius)
Returns the planet radiustype given the mass and using planetAssumptions['radiusType']
8.956459
4.985932
1.796346
if mass is not np.nan: sizeType = planetMassType(mass) elif radius is not np.nan: sizeType = planetRadiusType(radius) else: return None return '{0} {1}'.format(planetTempType(temperature), sizeType)
def planetType(temperature, mass, radius)
Returns the planet type as 'temperatureType massType'
4.20654
3.708282
1.134363
columns = df.columns elif isinstance(columns, str): columns = [columns] for column in columns: expanded = np.repeat(df.values, df[column].apply(len).values, axis=0) expanded[:, df.columns.get_loc(column)] = np.concatenate(df[column].tolist()) df = pd.DataFrame(expanded, ...
def split_array_like(df, columns=None): #TODO rename TODO if it's not a big performance hit, just make them arraylike? We already indicated the column explicitly (sort of) so... ''' Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---...
Split cells with array-like values along row axis. Column names are maintained. The index is dropped. Parameters ---------- df : ~pandas.DataFrame Data frame ``df[columns]`` should contain :py:class:`~pytil.numpy.ArrayLike` values. columns : ~typing.Collection[str] or str or None ...
2.75648
3.530778
0.7807
''' mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing. ''' for row2 in values: mask = ma.getmaskarray(row2) a...
def _try_mask_first_row(row, values, all_close, ignore_order)
mask first row in 2d array values : 2d masked array Each row is either fully masked or not masked at all ignore_order : bool Ignore column order Return whether masked a row. If False, masked nothing.
7.187366
3.667745
1.959615
''' if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row ''' i...
def _try_mask_row(row1, row2, all_close, ignore_order)
if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instead of == Return whether masked the row
4.998352
2.179117
2.293751
''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): if _value_equals(value, value2, all_close): ...
def _try_mask_first_value(value, row, all_close)
mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value
7.827651
2.960005
2.644473
''' Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of == ''' if value1 is None: value1 = np.nan if value2 is None: value2 = np.nan are_floats = np.can_cast(type(value1), float) and np.can_cast(type(va...
def _value_equals(value1, value2, all_close)
Get whether 2 values are equal value1, value2 : ~typing.Any all_close : bool compare with np.isclose instead of ==
2.616504
1.894088
1.381406
''' Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df2 : ~pandas.DataFrame Expected data frame. ignore_order : ~t...
def assert_equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False)
Assert 2 data frames are equal A more verbose form of ``assert equals(df1, df2, ...)``. See `equals` for an explanation of the parameters. Parameters ---------- df1 : ~pandas.DataFrame Actual data frame. df2 : ~pandas.DataFrame Expected data frame. ignore_order : ~typing.Set[in...
3.255193
1.821534
1.787061
def is_equal_strings_ignore_case(first, second): if first and second: return first.upper() == second.upper() else: return not (first or second)
The function compares strings ignoring case
null
null
null
def find_dimension_by_name(self, dim_name): for dim in self.dimensions: if is_equal_strings_ignore_case(dim.name, dim_name): return dim return None
the method searching dimension with a given name
null
null
null
def find_dimension_by_id(self, dim_id): for dim in self.dimensions: if is_equal_strings_ignore_case(dim.id, dim_id): return dim return None
the method searching dimension with a given id
null
null
null
def save_to_json(self): requestvalues = { 'Dataset': self.dataset, 'Header' : self._get_item_array(self.header), 'Filter' : self._get_item_array(self.filter), 'Stub' : self._get_item_array(self.stub), 'Frequencies': self.frequencies ...
The method saves data to json from object
null
null
null
def save_to_json(self): requestvalues = { 'DatasetId': self.dataset, 'Name': self.name, 'Description': self.description, 'Source': self.source, 'PubDate': self.publication_date, 'AccessedOn': self.accessed_on, ...
The method saves DatasetUpload to json from object
null
null
null
def save_to_json(self): requestvalues = { 'id': self.dataset, 'publicationDate': self.publication_date.strftime('%Y-%m-%d'), 'source': self.source, 'refUrl': self.refernce_url, } return json.dumps(requestvalues)
The method saves data to json from object
null
null
null
if FORMAT_SPEC.search(keyspace): return KeyspacedProxy(self, keyspace) else: return KeyspacedProxy(self, self._keyspaces[keyspace])
def keyspace(self, keyspace)
Convenient, consistent access to a sub-set of all keys.
8.547849
7.32452
1.167018
compared = dircmp(dir1, dir2, IGNORED_FILES) # ignore the OS X file if compared.left_only or compared.right_only or compared.diff_files or compared.funny_files: return False for subdir in compared.common_dirs: if not is_same(os.path.join(dir1, subdir), os.path.join(dir2, subdir)): ...
def is_same(dir1, dir2)
Compare two directory trees content. Return False if they differ, True is they are the same. :param dir2: :param dir1:
2.446921
2.571762
0.951457
fcomp = filecmp.cmpfiles(self.left, self.right, self.common_files, shallow=False) self.same_files, self.diff_files, self.funny_files = fcomp
def phase3(self)
Find out differences between common files. Ensure we are using content comparison with shallow=False.
6.482083
3.839906
1.688084
index = self.index_manager.get_index(namespace) start_dts_to_add = set() def actions(): for _id, event in events: dt = kronos_time_to_datetime(uuid_to_kronos_time(_id)) start_dts_to_add.add(_round_datetime_down(dt)) event['_index'] = index event['_type'] = stream ...
def _insert(self, namespace, stream, events, configuration)
`namespace` acts as db for different streams `stream` is the name of a stream and `events` is a list of events to insert.
4.962294
5.096093
0.973745
start_time = uuid_to_kronos_time(start_id) body_query = { 'query': { 'filtered': { 'query': {'match_all': {}}, 'filter': { 'bool': { 'should': [ { 'range': {TIMESTAMP_FIELD: {'gt': start_time, ...
def _delete(self, namespace, stream, start_id, end_time, configuration)
Delete events with id > `start_id` and end_time <= `end_time`.
2.646576
2.630356
1.006166
indices = self.index_manager.get_aliases(namespace, uuid_to_kronos_time(start_id), end_time) if not indices: return end_id = uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST) end_id.descending = s...
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration)
Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`.
2.810645
2.79073
1.007136
cdir = os.path.dirname( os.path.realpath(__file__) ) # table schemas ------------------------------------- schema = os.path.join(cdir,"data","partsmaster.sql") if self.debug: print(self.hdr,"parts master schema is ",schema) self.populate(sch...
def create_tables(self)
create tables in database (if they don't already exist)
3.09985
3.033413
1.021902
# TODO: rewrite to use re library f.seek(0) try: p_rec_type = None while True: rec_off = f.tell() while True: if f.read(2) == b'\xff\xff': h = struct.unpack('<HH', f.read(4)) if h[1] < 64 and h[1] != 0: ...
def parse_c_serialized(f)
Reads in a binary file created by a C++ serializer (prob. MFC?) and returns tuples of (header name, data following the header). These are used by Thermo for *.CF and *.DXF files and by Agilent for new-style *.REG files.
2.731778
2.715522
1.005987
return self.data.scan(t, dt, aggfunc)
def scan(self, t, dt=None, aggfunc=None)
Returns the spectrum from a specific time or range of times.
5.327691
4.724894
1.127579
storage_broker_lookup = dict() for entrypoint in iter_entry_points("dtool.storage_brokers"): StorageBroker = entrypoint.load() storage_broker_lookup[StorageBroker.key] = StorageBroker return storage_broker_lookup
def _generate_storage_broker_lookup()
Return dictionary of available storage brokers.
3.044261
2.702513
1.126456
uri = dtoolcore.utils.sanitise_uri(uri) storage_broker_lookup = _generate_storage_broker_lookup() parsed_uri = dtoolcore.utils.generous_parse_uri(uri) StorageBroker = storage_broker_lookup[parsed_uri.scheme] return StorageBroker(uri, config_path)
def _get_storage_broker(uri, config_path)
Helper function to enable use lookup of appropriate storage brokers.
3.861232
3.337403
1.156957
uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) admin_metadata = storage_broker.get_admin_metadata() return admin_metadata
def _admin_metadata_from_uri(uri, config_path)
Helper function for getting admin metadata.
3.084269
2.912724
1.058895
uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) return storage_broker.has_admin_metadata()
def _is_dataset(uri, config_path)
Helper function for determining if a URI is a dataset.
5.055237
4.622539
1.093606
if not dtoolcore.utils.name_is_valid(name): raise(DtoolCoreInvalidNameError()) if creator_username is None: creator_username = dtoolcore.utils.getuser() datetime_obj = datetime.datetime.utcnow() admin_metadata = { "uuid": str(uuid.uuid4()), "dtoolcore_version": _...
def generate_admin_metadata(name, creator_username=None)
Return admin metadata as a dictionary.
2.99108
2.858716
1.046302
name = admin_metadata["name"] uuid = admin_metadata["uuid"] # storage_broker_lookup = _generate_storage_broker_lookup() # parse_result = urlparse(base_uri) # storage = parse_result.scheme StorageBroker = _get_storage_broker(base_uri, config_path=None) return StorageBroker.generate_uri(n...
def _generate_uri(admin_metadata, base_uri)
Return dataset URI. :param admin_metadata: dataset administrative metadata :param base_uri: base URI from which to derive dataset URI :returns: dataset URI
4.441984
4.521234
0.982472
uri = _generate_uri(admin_metadata, base_uri) return ProtoDataSet(uri, admin_metadata, config_path)
def generate_proto_dataset(admin_metadata, base_uri, config_path=None)
Return :class:`dtoolcore.ProtoDataSet` instance. :param admin_metadata: dataset administrative metadata :param base_uri: base URI for proto dataset :param config_path: path to dtool configuration file
4.014874
4.959552
0.809523
dataset = DataSet.from_uri(src_uri) proto_dataset = _copy_create_proto_dataset( dataset, dest_base_uri, config_path, progressbar ) _copy_content(dataset, proto_dataset, progressbar) proto_dataset.freeze(progressbar=progressbar) return proto_dataset.uri
def copy(src_uri, dest_base_uri, config_path=None, progressbar=None)
Copy a dataset to another location. :param src_uri: URI of dataset to be copied :param dest_base_uri: base of URI for copy target :param config_path: path to dtool configuration file :returns: URI of new dataset
4.002507
4.677073
0.855772
dataset = DataSet.from_uri(src_uri) # Generate the URI of the destination proto dataset. dest_uri = _generate_uri(dataset._admin_metadata, dest_base_uri) proto_dataset = ProtoDataSet.from_uri(dest_uri) _copy_content(dataset, proto_dataset, progressbar) proto_dataset.freeze(progressbar=pr...
def copy_resume(src_uri, dest_base_uri, config_path=None, progressbar=None)
Resume coping a dataset to another location. Items that have been copied to the destination and have the same size as in the source dataset are skipped. All other items are copied across and the dataset is frozen. :param src_uri: URI of dataset to be copied :param dest_base_uri: base of URI for co...
5.10766
5.026723
1.016101
if not dtoolcore.utils.name_is_valid(new_name): raise(DtoolCoreInvalidNameError()) self._admin_metadata['name'] = new_name if self._storage_broker.has_admin_metadata(): self._storage_broker.put_admin_metadata(self._admin_metadata)
def update_name(self, new_name)
Update the name of the proto dataset. :param new_name: the new name of the proto dataset
4.26869
4.506124
0.947309
if not isinstance(overlay, dict): raise TypeError("Overlay must be dict") if set(self._identifiers()) != set(overlay.keys()): raise ValueError("Overlay keys must be dataset identifiers") self._storage_broker.put_overlay(overlay_name, overlay)
def _put_overlay(self, overlay_name, overlay)
Store overlay so that it is accessible by the given name. :param overlay_name: name of the overlay :param overlay: overlay must be a dictionary where the keys are identifiers in the dataset :raises: TypeError if the overlay is not a dictionary, ValueErro...
5.138875
3.696524
1.390191
items = dict() if progressbar: progressbar.label = "Generating manifest" for handle in self._storage_broker.iter_item_handles(): key = dtoolcore.utils.generate_identifier(handle) value = self._storage_broker.item_properties(handle) items...
def generate_manifest(self, progressbar=None)
Return manifest generated from knowledge about contents.
4.316215
4.058037
1.063621
if self._manifest_cache is None: self._manifest_cache = self._storage_broker.get_manifest() return self._manifest_cache
def _manifest(self)
Return manifest content.
5.06621
4.000417
1.266421
for handle in self._storage_broker.iter_item_handles(): yield dtoolcore.utils.generate_identifier(handle)
def _identifiers(self)
Return iterable of dataset item identifiers.
14.907658
9.785495
1.523444