code
stringlengths
1
18.2k
def create_from_item(self, languages, item, fields, trans_instance=None): """ Creates tasks from a model instance "item" (master) Used in the api call :param languages: :param item: :param fields: :param trans_instance: determines if we are in bulk mode or not. If it has a value we're processing by the signal trigger, ...
= getattr(trans, field) # if object_field_value is None or object_field_value == '': # object_field_value = getattr(self.instance, field, '') self.log('object_field_value for {} - .{}.'.format(object_field_label, object_field_value)) if object_field_value == '' or object_field_value is None: continue for lang in langua...
= ob_class_name.lower() ct = ContentType.objects.get_by_natural_key(app_label, model) try: task, created = TransTask.objects.get_or_create( content_type=ct, object_class=ob_class_name, object_pk=item.pk, object_field=field, language=language, user=user, defaults={ 'object_name': '{} - {}'.format(app_label, item._meta.v...
def get_field_label(self, trans, field): """ Get the field label from the _meta api of the model :param trans: :param field: :return: """ try: # get from the instance object_field_label = trans._meta.get_field_by_name(field)[0].verbose_name except Exception: try: # get from the class object_field_label = self.sender._m...
def get_translatable_children(self, obj): """ Obtain all the translatable children from "obj" :param obj: :return: """ collector = NestedObjects(using='default') collector.collect([obj]) object_list = collector.nested() items = self.get_elements(object_list) # avoid first object because it's the main object return item...
def get_elements(self, object_list): """ Recursive method to iterate the tree of children in order to flatten it :param object_list: :return: """ result = [] for item in object_list: if isinstance(item, list): result += self.get_elements(item) elif isinstance(item, TranslatableModel): result.append(item) return result
def update_model_languages(self, model_class, languages): """ Update the TransModelLanguages model with the selected languages :param model_class: :param languages: :return: """ # get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) new_langs = [lang for lang in q...
def add_item_languages(self, item, languages): """ Update the TransItemLanguage model with the selected languages :param item: :param languages: :return: """ # get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) new_langs = [lang for lang in qs] if not new_langs:...
def remove_item_languages(self, item, languages): """ delete the selected languages from the TransItemLanguage model :param item: :param languages: :return: """ # get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) remove_langs = [lang for lang in qs] if not remo...
def get_translation_from_instance(instance, lang): """ Get the translation from the instance in a specific language, hits the db :param instance: :param lang: :return: """ try: translation = get_translation(instance, lang) except (AttributeError, ObjectDoesNotExist): translation = None return translation
def create_translations_for_item_and_its_children(self, item, languages=None): """ Creates the translations from an item and defined languages and return the id's of the created tasks :param item: (master) :param languages: :return: """ if not self.master: self.set_master(item) if not languages: languages = self.get_la...
def delete_translations_for_item_and_its_children(self, item, languages=None): """ deletes the translations task of an item and its children used when a model is not enabled anymore :param item: :param languages: :return: """ self.log('--- Deleting translations ---') if not self.master: self.set_master(item) object_nam...
def blast(request, blast_form, template_init, template_result, blast_commandline, sample_fasta_path, extra_context=None): """ Process blastn/tblastn (blast+) query or set up initial blast form. """ if request.method == 'POST': form = blast_form(request.POST) if form.is_valid(): query_file_object_tmp = form.cleaned_data...
modify blast results # e.g. join blast results with external database in template if extra_context is not None: blast_records_in_object_and_list = extra_context(blast_records_in_object_and_list) return render(request=request, template_name=template_result, context={'application': blast_records_in_object_and_list[0].app...
def keys(self): """Iterates over the hive's keys. Yields WinRegKey namedtuples containing: path: path of the key "RootKey\\Key\\..." timestamp: date and time of last modification values: list of values (("ValueKey", "ValueType", ValueValue), ... ) """ for node in self.node_children(self.root()): yield from self._visit_...
def _value_data(self, value): """Parses binary and unidentified values.""" return codecs.decode( codecs.encode(self.value_value(value)[1], 'base64'), 'utf8')
def intersection(*args): """ Return the intersection of lists, using the first list to determine item order """ if not args: return [] # remove duplicates from first list whilst preserving order base = list(OrderedDict.fromkeys(args[0])) if len(args) == 1: return base else: others = set(args[1]).intersection(*args[2:])...
def union(*args): """ Return the union of lists, ordering by first seen in any list """ if not args: return [] base = args[0] for other in args[1:]: base.extend(other) return list(OrderedDict.fromkeys(base))
def random_string(length): """ Generates a random alphanumeric string """ # avoid things that could be mistaken ex: 'I' and '1' letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" return "".join([random.choice(letters) for _ in range(length)])
def filter_dict(d, keys): """ Creates a new dict from an existing dict that only has the given keys """ return {k: v for k, v in d.items() if k in keys}
def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False): """ Gets the result of a method call, using the given key and TTL as a cache """ if not recalculate: cached = cache.get(cache_key) if cached is not None: return json.loads(cached) calculated = calculate() cache.set(cache_key, json.dumps(calculated),...
def get_obj_cacheable(obj, attr_name, calculate, recalculate=False): """ Gets the result of a method call, using the given object and attribute name as a cache """ if not recalculate and hasattr(obj, attr_name): return getattr(obj, attr_name) calculated = calculate() setattr(obj, attr_name, calculated) return calculate...
def datetime_to_ms(dt): """ Converts a datetime to a millisecond accuracy timestamp """ seconds = calendar.timegm(dt.utctimetuple()) return seconds * 1000 + int(dt.microsecond / 1000)
def ms_to_datetime(ms): """ Converts a millisecond accuracy timestamp to a datetime """ dt = datetime.datetime.utcfromtimestamp(ms / 1000) return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
def get_month_range(d=None): """ Gets the start (inclusive) and end (exclusive) datetimes of the current month in the same timezone as the given date """ if not d: d = timezone.now() start = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0) end = start + relativedelta(months=1) return start, end
def chunks(iterable, size): """ Splits a very large list into evenly sized chunks. Returns an iterator of lists that are no more than the size passed in. """ it = iter(iterable) item = list(islice(it, size)) while item: yield item item = list(islice(it, size))
def is_dict_equal(d1, d2, keys=None, ignore_none_values=True): """ Compares two dictionaries to see if they are equal :param d1: the first dictionary :param d2: the second dictionary :param keys: the keys to limit the comparison to (optional) :param ignore_none_values: whether to ignore none values :return: true if the...
def command_locate(options): """Command launched by CLI.""" matches = find_owners(options.file.name) if matches: print(*matches, sep='\n')
def find_owners(path): """Return the package(s) that file belongs to.""" abspath = os.path.abspath(path) packages = search_packages_info( sorted((d.project_name for d in get_installed_distributions(user_only=ENABLE_USER_SITE)), key=lambda d: d.lower())) return [p['name'] for p in packages if is_owner(p, abspath)]
def is_owner(package, abspath): """Determine whether `abspath` belongs to `package`.""" try: files = package['files'] location = package['location'] except KeyError: return False paths = (os.path.abspath(os.path.join(location, f)) for f in files) return abspath in paths
def _get_subfolder(self, foldername, returntype, params=None, file_data=None): """Return an object of the requested type with the path relative to the current object's URL. Optionally, query parameters may be set.""" newurl = compat.urljoin(self.url, compat.quote(foldername), False) params = params or {} file_data = fi...
strings can't be quoted/escaped at the # top level elif isinstance(val, gptypes.GPString): query_dict[key] = val.value # Just use the wkid of SpatialReferences elif isinstance(val, geometry.SpatialReference): query_dict[key] = val.wkid # If it's a list, make it a comma-separated string elif isinstance(val, (list, tuple...
RestURL or subclass rt = returntype(newurl, file_data) # Remind the resource where it came from try: rt.parent = self except: rt._parent = self return rt
def url(self): """The URL as a string of the resource.""" urlparts = self._url if self.__post__: urlparts = list(urlparts) urlparts[3] = '' # Clear out query string on POST if self.__token__ is not None: # But not the token urlparts[3] = compat.urlencode({'token': self.__token__}) return compat.urlunsplit(urlparts)
def _contents(self): """The raw contents of the URL as fetched, this is done lazily. For non-lazy fetching this is accessed in the object constructor.""" if self.__urldata__ is Ellipsis or self.__cache_request__ is False: if self._file_data: # Special-case: do a multipart upload if there's file data self.__post__ = Tru...
"--\r\n\r\n" req_dict = {'User-Agent' : USER_AGENT, 'Content-Type': 'multipart/form-data; boundary='+boundary[2:], 'Content-Length': str(len(multipart_data)) } if self._referer: req_dict['Referer'] = self._referer request = compat.urllib2.Request(self.url, multipart_data, req_dict) else: req_dict = {'User-Agent' : USER...
def _json_struct(self): """The json data structure in the URL contents, it will cache this if it makes sense so it doesn't parse over and over.""" if self.__has_json__: if self.__cache_request__: if self.__json_struct__ is Ellipsis: if self._contents is not Ellipsis: self.__json_struct__ = json.loads( compat.ensure_str...
def parent(self): "Get this object's parent" if self._parent: return self._parent # auto-compute parent if needed elif getattr(self, '__parent_type__', None): return self._get_subfolder('..' if self._url[2].endswith('/') else '.', self.__parent_type__) else: raise AttributeError("%r has no parent attribute" % type(self...
def _register_service_type(cls, subclass): """Registers subclass handlers of various service-type-specific service implementations. Look for classes decorated with @Folder._register_service_type for hints on how this works.""" if hasattr(subclass, '__service_type__'): cls._service_type_mapping[subclass.__service_type__...
def servicenames(self): "Give the list of services available in this folder." return set([service['name'].rstrip('/').split('/')[-1] for service in self._json_struct.get('services', [])])
def services(self): "Returns a list of Service objects available in this folder" return [self._get_subfolder("%s/%s/" % (s['name'].rstrip('/').split('/')[-1], s['type']), self._service_type_mapping.get(s['type'], Service)) for s in self._json_struct.get('services', [])]
def url(self): """The URL as a string of the resource.""" if not self._url[2].endswith('/'): self._url[2] += '/' return RestURL.url.__get__(self)
def save(self, outfile): """Save the image data to a file or file-like object""" if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') outfile.write(self._contents)
def QueryLayer(self, text=None, Geometry=None, inSR=None, spatialRel='esriSpatialRelIntersects', where=None, outFields=None, returnGeometry=None, outSR=None, objectIds=None, time=None, maxAllowableOffset=None, returnIdsOnly=None): """The query operation is performed on a layer resource. The result of this operation is ...
def timeInfo(self): """Return the time info for this Map Service""" time_info = self._json_struct.get('timeInfo', {}) if not time_info: return None time_info = time_info.copy() if 'timeExtent' in time_info: time_info['timeExtent'] = utils.timetopythonvalue( time_info['timeExtent']) return time_info
def save(self, outfile): """Save the image data to a file or file-like object""" if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') assert hasattr(outfile, 'write') and callable(outfile.write), \ "Expect a file or file-like object with a .write() method" outfile.write(self.data)
def candidates(self): """A list of candidate addresses (as dictionaries) from a geocode operation""" # convert x['location'] to a point from a json point struct def cditer(): for candidate in self._json_struct['candidates']: newcandidate = candidate.copy() newcandidate['location'] = \ geometry.fromJson(newcandidate['lo...
def results(self): "Returns a dict of outputs from the GPTask execution." if self._results is None: results = self._json_struct['results'] def result_iterator(): for result in results: datatype = None conversion = None for param in self.parent.parameters: if param['name'] == result['paramName']: datatype = param['datat...
def Execute(self, *params, **kw): """Synchronously execute the specified GP task. Parameters are passed in either in order or as keywords.""" fp = self.__expandparamstodict(params, kw) return self._get_subfolder('execute/', GPExecutionResult, fp)
def SubmitJob(self, *params, **kw): """Asynchronously execute the specified GP task. This will return a Geoprocessing Job object. Parameters are passed in either in order or as keywords.""" fp = self.__expandparamstodict(params, kw) return self._get_subfolder('submitJob/', GPJob, fp)._jobstatus
def save(self, outfile): """Save the image data to a file or file-like object""" if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') outfile.write(compat.urllib2.urlopen(self.href).read())
def SolveClosestFacility(self, facilities=None, incidents=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, returnDirections=None, directionsLanguage=None, directionsStyleName=None, directionsLengthUnits=None, directionsTimeAttributeName=None, returnCFRoutes=None, returnFa...
def SolveServiceArea(self, facilities=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, defaultBreaks=None, excludeSourcesFromPolygons=None, mergeSimilarPolygonRanges=None, outputLines=None, outputPolygons=None, overlapLines=None, overlapPolygons=None, splitLinesAtBreaks=N...
def Solve(self, stops=None, barriers=None, returnDirections=None, returnRoutes=None, returnStops=None, returnBarriers=None, outSR=None, ignoreInvalidLocations=None, outputLines=None, findBestSequence=None, preserveFirstStop=None, preserveLastStop=None, useTimeWindows=None, startTime=None, accumulateAttributeNames=None,...
'returnRoutes': returnRoutes, 'returnStops': returnStops, 'returnBarriers': returnBarriers, 'outSR': outSR, 'ignoreInvalidLocations': ignoreInvalidLocations, 'outputLines': outputLines, 'findBestSequence': findBestSequence, 'preserveFirstStop': preserveFirstStop, 'preserveLastStop': preserveLastStop, 'useTimeWindows': ...
def QueryRelatedRecords(self, objectIds=None, relationshipId=None, outFields=None, definitionExpression=None, returnGeometry=None, outSR=None): """The query operation is performed on a feature service layer resource. The result of this operation are featuresets grouped by source layer / table object IDs. Each featurese...
def UpdateFeatures(self, features): """This operation updates features to the associated feature layer or table (POST only). The update features operation is performed on a feature service layer resource. The result of this operation is an array of edit results. Each edit result identifies a single feature and indicate...
def DeleteFeatures(self, objectIds=None, where=None, geometry=None, inSR=None, spatialRel=None): """This operation deletes features in a feature layer or table (POST only). The delete features operation is performed on a feature service layer resource. The result of this operation is an array of edit results. Each edit...
def ApplyEdits(self, adds=None, updates=None, deletes=None): """This operation adds, updates and deletes features to the associated feature layer or table in a single call (POST only). The apply edits operation is performed on a feature service layer resource. The result of this operation are 3 arrays of edit results (...
def save(self, **kwargs): """ Method that creates the translations tasks for every selected instance :param kwargs: :return: """ try: # result_ids = [] manager = Manager() for item in self.model_class.objects.language(manager.get_main_language()).filter(pk__in=self.ids).all(): create_translations_for_item_and_its_child...
def get_version(): """ Gets the current version of the package. """ version_py = os.path.join(os.path.dirname(__file__), 'deepgram', 'version.py') with open(version_py, 'r') as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip().replace('"', '') raise ValueError('Failed to parse ve...
def config(env=DEFAULT_ENV, default=None, **overrides): """Returns configured REDIS dictionary from REDIS_URL.""" config = {} s = os.environ.get(env, default) if s: config = parse(s) overrides = dict([(k.upper(), v) for k, v in overrides.items()]) config.update(overrides) return config
def parse(url): """Parses a database URL.""" config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] # Update with environment configuration. config.update({ "DB": int(path or 0), "PASSWORD": url.password or None, "HOST": url.hostname or "localhost", "PORT": int...
def hash_filesystem(filesystem, hashtype='sha1'): """Utility function for running the files iterator at once. Returns a dictionary. {'/path/on/filesystem': 'file_hash'} """ try: return dict(filesystem.checksums('/')) except RuntimeError: results = {} logging.warning("Error hashing disk %s contents, iterating over files...
def fsroot(self): """Returns the file system root.""" if self.osname == 'windows': return '{}:\\'.format( self._handler.inspect_get_drive_mappings(self._root)[0][0]) else: return self._handler.inspect_get_mountpoints(self._root)[0][0]
def mount(self, readonly=True): """Mounts the given disk. It must be called before any other method. """ self._handler.add_drive_opts(self.disk_path, readonly=True) self._handler.launch() for mountpoint, device in self._inspect_disk(): if readonly: self._handler.mount_ro(device, mountpoint) else: self._handler.mount(de...
def _inspect_disk(self): """Inspects the disk and returns the mountpoints mapping as a list which order is the supposed one for correct mounting. """ roots = self._handler.inspect_os() if roots: self._root = roots[0] return sorted(self._handler.inspect_get_mountpoints(self._root), key=lambda m: len(m[0])) else: raise R...
def download(self, source, destination): """Downloads the file on the disk at source into destination.""" self._handler.download(posix_path(source), destination)
def nodes(self, path): """Iterates over the files and directories contained within the disk starting from the given path. Yields the path of the nodes. """ path = posix_path(path) yield from (self.path(path, e) for e in self._handler.find(path))
def checksum(self, path, hashtype='sha1'): """Returns the checksum of the given path.""" return self._handler.checksum(hashtype, posix_path(path))
def checksums(self, path, hashtype='sha1'): """Iterates over the files hashes contained within the disk starting from the given path. The hashtype keyword allows to choose the file hashing algorithm. Yields the following values: "C:\\Windows\\System32\\NTUSER.DAT", "hash" for windows "/home/user/text.txt", "hash" for o...
def listen(self): """ Listen/Connect to message service loop to start receiving messages. Do not include in constructor, in this way it can be included in tasks """ self.listening = True try: self.service_backend.listen() except AuthenticationError: self.listening = False raise else: self.listening = False
def attend_pendings(self): """ Check all chats created with no agent assigned yet. Schedule a timer timeout to call it. """ chats_attended = [] pending_chats = Chat.pending.all() for pending_chat in pending_chats: free_agent = self.strategy.free_agent() if free_agent: pending_chat.attend_pending(free_agent, self) pendi...
def terminate_obsolete(self): """ Check chats can be considered as obsolete to terminate them """ chats_terminated = [] live_chats = Chat.live.all() for live_chat in live_chats: if live_chat.is_obsolete(self.time_obsolete_offset): live_chat.terminate() live_chat.save() chats_terminated.append(live_chat) return chats_te...
def on_message(self, message_id_service, contact_id_service, content): """ To use as callback in message service backend """ try: live_chat = Chat.live.get( Q(agent__id_service=contact_id_service) | Q(asker__id_service=contact_id_service)) except ObjectDoesNotExist: self._new_chat_processing(message_id_service, contact...
def decode_path(file_path): """Turn a path name into unicode.""" if file_path is None: return if isinstance(file_path, six.binary_type): file_path = file_path.decode(sys.getfilesystemencoding()) return file_path
def read_command(self): """ Attempt to read the next command from the editor/server :return: boolean. Did we actually read a command? """ # Do a non-blocking read here so the demo can keep running if there is no data comm = self.reader.byte(blocking=False) if comm is None: return False cmds = { SET_KEY: self.handle_set...
def handle_set_key(self): """Read incoming key from server""" track_id = self.reader.int() row = self.reader.int() value = self.reader.float() kind = self.reader.byte() logger.info(" -> track=%s, row=%s, value=%s, type=%s", track_id, row, value, kind) # Add or update track value track = self.tracks.get_by_id(track_id) ...
def handle_delete_key(self): """Read incoming delete key event from server""" track_id = self.reader.int() row = self.reader.int() logger.info(" -> track=%s, row=%s", track_id, row) # Delete the actual track value track = self.tracks.get_by_id(track_id) track.delete(row)
def handle_set_row(self): """Read incoming row change from server""" row = self.reader.int() logger.info(" -> row: %s", row) self.controller.row = row
def handle_pause(self): """Read pause signal from server""" flag = self.reader.byte() if flag > 0: logger.info(" -> pause: on") self.controller.playing = False else: logger.info(" -> pause: off") self.controller.playing = True
def get_choices_for_models(): """ Get the select choices for models in optgroup mode :return: """ result = {} apps = [item.model.split(' - ')[0] for item in TransModelLanguage.objects.all()] qs = ContentType.objects.exclude(model__contains='translation').filter(app_label__in=apps).order_by( 'app_label', 'model' ) for c...
def search(self, lat_range=None, long_range=None, variance=None, bssid=None, ssid=None, last_update=None, address=None, state=None, zipcode=None, on_new_page=None, max_results=100): """ Search the Wigle wifi database for matching entries. The following criteria are supported: Args: lat_range ((float, float)): latitude ...
'netid': bssid or "", 'ssid': ssid or "", 'lastupdt': last_update.strftime("%Y%m%d%H%M%S") if last_update else "", 'addresscode': address or "", 'statecode': state or "", 'zipcode': zipcode or "", 'Query': "Query", } wifis = [] while True: if on_new_page: on_new_page(params.get('first', 1)) resp = self._authenticated_r...
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Overwrite of the save method in order that when setting the language as main we deactivate any other model selected as main before :param force_insert: :param force_update: :param using: :param update_fields: :return: """ super(...
def trigger_org_task(task_name, queue="celery"): """ Triggers the given org task to be run for all active orgs :param task_name: the full task name, e.g. 'myproj.myapp.tasks.do_stuff' :param queue: the name of the queue to send org sub-tasks to """ active_orgs = apps.get_model("orgs", "Org").objects.filter(is_active=Tr...
def org_task(task_key, lock_timeout=None): """ Decorator to create an org task. :param task_key: the task key used for state storage and locking, e.g. 'do-stuff' :param lock_timeout: the lock timeout in seconds """ def _org_task(task_func): def _decorator(org_id): org = apps.get_model("orgs", "Org").objects.get(pk=org_...
def maybe_run_for_org(org, task_func, task_key, lock_timeout): """ Runs the given task function for the specified org provided it's not already running :param org: the org :param task_func: the task function :param task_key: the task key :param lock_timeout: the lock timeout in seconds """ r = get_redis_connection() ke...
results = task_func(org) else: raise ValueError("Task signature must be foo(org) or foo(org, since, until)") # pragma: no cover state.ended_on = timezone.now() state.last_successfully_started_on = this_started_on state.last_results = json.dumps(results) state.is_failing = False state.save(update_fields=("ended_on", "la...
def check_data_type(self): """Check the type of the transformer and column match. Args: column_metadata(dict): Metadata of the column. Raises a ValueError if the types don't match """ metadata_type = self.column_metadata.get('type') if self.type != metadata_type and metadata_type not in self.type: raise ValueError('Typ...
def fit(self, col): """Prepare the transformer to convert data. Args: col(pandas.DataFrame): Data to transform. Returns: None """ dates = self.safe_datetime_cast(col) self.default_val = dates.groupby(dates).count().index[0].timestamp() * 1e9
def transform(self, col): """Prepare the transformer to convert data and return the processed table. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ out = pd.DataFrame() out[self.col_name] = self.safe_datetime_cast(col) out[self.col_name] = self.to_timestamp(out) return out
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ if isinstance(col, pd.Series): col = col.to_frame() output = pd.DataFrame(index=col.index) output[self.col_name] = col.apply(self.safe_date, axis=1) return output
def safe_datetime_cast(self, col): """Parses string values into datetime. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.Series """ casted_dates = pd.to_datetime(col[self.col_name], format=self.date_format, errors='coerce') if len(casted_dates[casted_dates.isnull()]): # This will raise an error for bad...
def to_timestamp(self, data): """Transform a datetime series into linux epoch. Args: data(pandas.DataFrame): DataFrame containins a column named as `self.col_name`. Returns: pandas.Series """ result = pd.Series(index=data.index) _slice = ~data[self.col_name].isnull() result[_slice] = data[_slice][self.col_name].astype(...
def safe_date(self, x): """Transform x[self.col_name] into a date string. Args: x(dict like / pandas.Series): Row containing data to cast safely. Returns: str """ t = x[self.col_name] if np.isnan(t): return t elif np.isposinf(t): t = sys.maxsize elif np.isneginf(t): t = -sys.maxsize tmp = time.localtime(float(t) / 1e9)...
def long_description(): """Return the contents of README.rst (with badging removed).""" # use re.compile() for flags support in Python 2.6 pattern = re.compile(r'\n^\.\. start-badges.*^\.\. end-badges\n', flags=re.M | re.S) return pattern.sub('', read('README.rst'))
def send_message(self, id_service, content): """Write all messages to the stream in a thread-safe way.""" if not content: return with self._lock: try: message = "Message: %s to %s" % (content, id_service) self.write_message(message) self.stream.flush() # flush after each message return "message_id" except Exception: if...
def chop_sequence(sequence, limit_length): """Input sequence is divided on smaller non-overlapping sequences with set length. """ return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)]
def get_tabular_str(self): """Creates table-like string from fields. """ hsp_string = "" try: hsp_list = [ {"length": self.align_length}, {"e-value": self.expect}, {"score": self.score}, {"identities": self.identities}, {"positives": self.positives}, {"bits": self.bits}, {"query start": self.query_start}, {"query end":...