content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def boyer_moore_voting_algorithm(arr: list) -> int: """ :param arr: list :return: int """ res = arr[0] # Initialization counter = 0 # Counter for i in range(len(arr)): if counter == 0: res = arr[i] counter = 1 elif res == arr[i]: counter...
9ab8e83b159955412e5860337fb3a83a458d2454
641,633
def isnamemacro(function): """Return whether the macro function `function` has been declared as an identifier macro.""" return hasattr(function, "_isnamemacro")
c859bffb1c85e207c5119f57bd1d11bd479ad1fd
641,634
def get_class_properties(class_name: str, vocab: dict) -> list: """ Return all the properties of the given class. """ properties = list() defines = vocab['@graph'] for obj in defines: if obj.get('propertyOf'): propertyof = obj['propertyOf'].split('#')[1] if proper...
a0f74c9d3bf78b821e5c1af19256628bdc3cecac
641,635
def updated_with(orig_dict, *new_values): """Return a copy of orig_dict updated with new_values. New keys are added, and the values of existing keys will take the values in new_values. You can specify more than one update dictionary. They are applied in order, so the values of any keys in later di...
eb32696da3d807804c4b1f8cf85405eac2c5ec5a
641,636
def add_three(one, two, three): """Adds three values together and returns it.""" return one + two + three
a35b80364cc823c4eb306d4a84bfa12db79252f6
641,637
def update(Se, Ie, mediator, weights, c): """ updates the weight on {Se,mediator} and {Ie,mediator} """ if (Se,mediator) not in weights: weights[(Se,mediator)] = 0 weights[(Se,mediator)] += float(1/c) if (Ie,mediator) not in weights: weights[(Ie,mediator)] = 0 weigh...
9b614ab13f6a1933e2c96bf13a8fb55d96468303
641,638
from typing import List def find_all_matchstrings_in_string(string: str, matchstrings: List[str]): """ check if string has all matchstrings in it """ return all([matchstring in string for matchstring in matchstrings])
60e8ba7f3ce3b63b0e380a536ded8bad58a0f53c
641,639
import torch def has_tensor(obj) -> bool: """ Given a possibly complex data structure, check if it has any torch.Tensors in it. """ if isinstance(obj, torch.Tensor): return True elif isinstance(obj, dict): return any(has_tensor(value) for value in obj.values()) elif isinsta...
ed70ce8443625ab66d7b36b3aa57c799855b7fc5
641,640
def first_not_none(itr): """ returns the first non-none result from an iterable, similar to any() but return value not true/false """ for x in itr: if x: return x return None
de04721394fd45f8d3886b6adb17a9db0893825b
641,641
def expected_data_no_trim(dict_, data): """ Generate test data for the trim test cases. """ data = data.sort_values(by="prop_score", ascending=True) X_expected = data[dict_["TREATED"]["order"]] Y_expected = data[[dict_["ESTIMATION"]["dependent"]]] prop_score_expected = data["prop_score"] ...
0469a92d7144174c59bb9b7852ce368dfa0075ba
641,642
def getDjangoURLPatterns(): """Returns the URL patterns for the tasks in this module. """ patterns = [ (r'^tasks/ghop/task/update$', 'soc.modules.ghop.tasks.task_update.updateGHOPTask'), (r'^tasks/ghop/task/mail/create$', 'soc.modules.ghop.tasks.task_update.createNotificationMail'), ...
d8e4afc48fd37301c3abaa433eb3423b605b818b
641,645
def delete_matched_sub_string(): """ Delete substring from original string, and return results.""" _originalString = input("The original string:") _subString = input("The sub-string:") while _subString in _originalString: # Delete the _substring from _oringinalString, and restore _originalStrin...
83467696e79f88a7876932bc3c2508b2c9ba85d0
641,646
def max_with_none(first, second): """Returns the maximum of the two inputs, ignoring Nones.""" if first is None: return second elif second is None: return first else: return max(first, second)
63c9ea7d9095994fe2ae8462501e785e8918a747
641,647
import numpy as np def scale_trends(array, scaling_percentile = None): """ Takes a linguistic sub-dataframe and applies a robust custom scaling in two steps: 1. log( x + 1 ) 2. Robust min-max scaling to [ 0, 99th percentile ] If scaling percentile is to be found (Train data), then a scalin...
7749258bed1e6cd411a1a815e41737eae3d87aa1
641,648
def get_worker(): """ Запросить данные о работнике. """ name = input("Фамилия и инициалы? ") post = input("Должность? ") year = int(input("Год поступления? ")) # Создать словарь. return { 'name': name, 'post': post, 'year': year, }
65ea94c30604dc349a3d7e83803451581cc978c8
641,649
def NestedQ(l): """Returns True if every item in List is a list or a tuple. l: a list.""" return {type(item) for item in l} in [{list}, {tuple}]
c8278af8f70f9401c753f74ddb54baec76fdb23b
641,651
import os import operator def get_item_cate(ave_score, input_file): """ Args: ave_score: a dict , key itemid value rating score input_file: item info file Return: 两个dict 对象: a dict: key itemid value a dict, key: cate value:ratio a dict: key cate value [itemid1, item...
d06a359de4f602e66994f3fc48f5653ec500dcb2
641,652
def outer(u, v): """ Compute the outer product of two tensors. For two tensors **u** of shape :math:`(k_1, k_2, ..., k_m)` and **v** of shape :math:`(l_1, l_2, ..., l_n)`, their outer product :math:`\mathbf{w} = \mathbf{u} \otimes \mathbf{v}` is defined such that :math:`\mathbf{w}[i_1, i_2, ..., i_...
487c0f56022c588be3a1c4913c055b3f577a531f
641,653
def _quote_filter_value(s): """Put a string in double quotes, escaping double quote characters""" return '"%s"' % s.replace('"', r'\"')
9a6961c731408759083fad399ea4a7250d052830
641,654
import base64 def generate_failed_answers_html(failed_answers): """Generates html for the failed answer tests This function creates a html and embeds the images (actual, expected, difference) in it for the failed answers. Parameters ---------- failed_answers : dict mapping string to dict ...
c47428a6adc34754726b3ce10973786966409298
641,655
import random def encode_string(value): """ Encode a string into it's equivalent html entity. The tag will randomly choose to represent the character as a hex digit or decimal digit. """ e_string = "" for a in value: e_type = random.randint(0, 1) if e_type: en...
76af82e3495c605a5ddaf3df9bdd352749856c07
641,657
def _default_kwargs_split_fn(kwargs): """Default `kwargs` `dict` getter.""" return (kwargs.get('distribution_kwargs', {}), kwargs.get('bijector_kwargs', {}))
3d39d73ba6d7bfd673fa7216f3e386e61abca795
641,658
def worker_process_control(_destination, _destination_process_id, _command, _reason, _message_id, _source, _source_process_id, _user_id): """ Creates a worker process control message. Tells a worker process to stop, kill, etcetera. """ return { "destination": _destinat...
3f54e25a6b97458176c30a1b0d4b36b3ff2b6688
641,659
def temp_get_users_with_permission_model( self, include_superusers=True, backend="django.contrib.auth.backends.ModelBackend", ): """Used to test that swapping the model method works""" # Search string: XYZ return ()
bdb5c485bb496cf0a554a6390ace8d9e2e85d4f9
641,660
def str_loads(data, content_type="application/json", encoding="utf-8"): """Returns the string instead of trying to convert it. """ return data
9d7bba3f04f659ec43e52681dbe23f4084b63a6f
641,661
import re def findWholeWord(word): """ Find one word inside another word. Arguments: :param word: word to check if is contained inside another word :type word: string Returns: :return is_contained: Returns "yes" if it's contained, "no" if not :rtype is_contained: bool...
f602f8697238a4671f0fcd38d8b410c2b84ebbc0
641,662
def recreate_shots_from_counts( counts ): """Recreate shots from job result counts Recreates the individual shot results for the number of times the quantum circuit is repeated Args: counts (dict): job result counts, e.g. For 1024 shots: {'000': 510, '111': 514} Returns: l...
6a6aef97d5b245e5d1afabdcc2c0131b48bfb064
641,663
def features(indel_class): """Manage feature names Args: indel_class (str): "s" for single-nucleotide indels (1-nt indels) "m" for multi-nucleotide indels (>1-nt indels) Returns: features (list): a list of feature names """ assert indel_class == "s" or in...
fcfbe4a4f5df5b25222d4d8a52a49d77849f9683
641,664
def get_var_names(variable): """ get the long variable names from 'flow' or 'temp' :param variable: [str] either 'flow' or 'temp' :return: [str] long variable names """ if variable == "flow": obs_var = "discharge_cms" seg_var = "seg_outflow" elif variable == "temp": o...
2d9298f9181cc3375039a75e0dff04050a3a138e
641,665
def replace_module_suffix(state_dict, suffix, replace_with=""): """ Replace suffixes in a state_dict Needed when loading DDP or classy vision models """ state_dict = { (key.replace(suffix, replace_with, 1) if key.startswith(suffix) else key): val for (key, val) in state_dict.items() ...
4c85e37bd8e871cfb71786839f1defe0bda23f7c
641,667
def inv(R): """Inverts the rotation""" Rinv = [R[0],R[3],R[6],R[1],R[4],R[7],R[2],R[5],R[8]] return Rinv
c903e93831a262ede390ab44a3b9d8789bd5c4d7
641,668
def check_response(response): """Check the status of responses from polyswarmd Args: response: Response dict parsed from JSON from polyswarmd Returns: (bool): True if successful else False """ status = response.get('status') return status and status == 'OK'
49ded72d3dda5c88add399923b0e14c5ec2ff89d
641,669
def _yes_or_no(): """ example: if _yes_or_no(): pass """ YORN = 'undefined' while YORN.lower()[0] not in ['y', 'n']: YORN = input("yes[y] or no[n]: ").strip() return YORN.lower()[0] == 'y'
68393ff65d0744489b70e917ff98b060f57c4dba
641,670
def celery_app(flask_app): """Create celery app. :param flask_app: Created flask app """ return flask_app.extensions['celery'].celery
d8e4986eb6688b7bd6d0bebc7167a549b821b0b6
641,671
from typing import List from typing import Tuple def get_time_series_data_slice(source_data_series: List[List[float]], target_data_series: List[float], start: int, stop: int) -> Tuple[List[List[float]], List[List[float]]]: """Get time series data slice for provided source and target...
a105de5c2f7f0957cf9e38cf0d2d6475bd12858e
641,673
def validar_codigo_aplicacion_descuento(codigo_aplicacion, descuento_codigo_aplicacion): """ validar que exista con digo de aplicacion :param codigo_aplicacion: :param descuento_dia_promocion: :return: """ if codigo_aplicacion and descuento_codigo_aplicacion: if codigo_aplicacion == ...
ca3fb1a9589bcdae90a12779eb330efb1b740840
641,674
def stations_level_over_threshold(stations,tol): """This function returns a list of tuples, where each tuple holds a station at which the latest relative water level is over tol and the relative water level at the station""" stations_over_threshold = [] for station in stations: relative_level = stat...
da6b32eaf4970ef8e4845aa292e0074a9cb3df08
641,675
def Collect(iterable, container=list): """ iterable >> Collect(container) Collects all elements of the iterable input in the given container. >>> range(5) >> Collect() [0, 1, 2, 3, 4] >>> [1, 2, 3, 2] >> Collect(set) # doctest: +SKIP {1, 2, 3} >>> [('one', 1), ('two', 2)] >> Collect...
7f69937badb3626c0b85fec8db6aab14887f19b2
641,676
def unread(thread, user): """ Check whether there are any unread messages for a particular thread for a user. """ return thread.user_threads.filter(user=user, is_read=False).exists()
e843005145e69261a2bebaee50443219d8f4b2e6
641,677
import torch def hard_example_mining(dist_mat, is_pos, return_indices=False, bound=9999.0): """For each anchor, find the hardest positive and negative sample. Args: dist_mat: pair wise distance between samples, shape [N, M] is_pos: positive index with shape [N, M] Returns: dist_ap: pytor...
f3d2825056ed8c49d7241155b685ccf893244a8a
641,678
def add(a, b): """ Return the addition of the arguments: a + b >>> add(1, 2) 3 >>> add(-1, 10) 9 >>> add('a', 'b') 'ab' >>> add(1, '2') Traceback (most recent call last): File "test.py", line 17, in <module> add(1, '2') File "test.py", line 14, in add ...
8c3bdaca7beea41ec661cabd075b5c2ef042c121
641,679
def height(studydata, column, context): """Please convert heights to inches.""" h = column.str.extract('^(?P<feet>[0-9.]+)(?:[^0-9.]+(?P<inches>[0-9.]+))?') h = 12 * h.feet.astype(float) + h.inches.astype(float) return h.fillna(0)
d4561cee81f68be6abb66cd76d9c651bc410116e
641,680
def _get_vector_identifier(line): """Return the identifier from the vector string. """ return line.split()[0]
f3d8dd43d1e49461474fe855fec1ecd7707d34f7
641,681
def get_applied_profiles(net, profile_type): """ Returns a list of unique profiles in element tables, e.g. net.sgen.profile. profile_type must be in ["load", "renewables", "powerplants", "storage"]. """ applied_profiles = [] if profile_type in ["renewables", "powerplants"]: phys_type = "RES"...
99d86df0b0bf55373506646ccc4a6d510a8d0a25
641,682
def user_event_week_top_voted(msg): """ week top voted """ isclick = msg['MsgType'] == 'event' \ and msg['Event'] == 'CLICK' and msg['EventKey'] == 'WEEK_TOP_VOTED' iscmd = msg['MsgType'] == 'text' and \ (msg['Content'].lower() == '2' \ or msg['Content'].lower() == 'wtv' \ ...
53c7271532dd976dea32c713f58a74368d05c271
641,683
import os def edit_text(text, prompt="Edit text"): """Run $EDITOR on text. Defaults to vim.""" fname = os.path.join(os.environ["HOME"], ".edit_text.txt") with open(fname, "w") as fo: fo.write(prompt + ":\n") fo.write(text) os.system('%s "%s"' % (os.environ.get("EDITOR", "/usr/bin/vim")...
0d7f49639d97f0fea58e83b0e1dc9cc8bab0a8e8
641,684
def format_address(address): """ """ return "'%s' %s" % (address[0], address[1])
a59ebc8cabea4746d064b10f94e68cc6b724405a
641,685
def fed_avg(weights, factors): """ compute FedAvg param::weights locally trained model weights param::factors factors determined by the number of data points collected """ fed_avg_wegiths = [] n_clients = len(weights) for w_index, w in enumerate(weights[0]): layer_fed_avg_weight ...
87762ddf27e9e020e79d6f45c5351f1b2410d7f7
641,686
def clip(data, start_idx): """Return data[start_idx:]""" return data[start_idx:]
90fa56f3bf5f95303274f052bcd3baf7518436a1
641,687
import os def get_size(fp): """ Retrieve the size of the file in KB. :param fp: file path :return: the size in KB of the file """ return os.path.getsize(fp) // 1024
bc318ffbbff1b90b0f9c0ba2b27da38bbf6079cf
641,688
def filter_list(*args,**kwargs): """Eager version of filter, returns list. May be slower or more resource hungry than builtin genrator/lazy version.""" #return list(filter(func, oplist)) return list(filter(*args,**kwargs))
66f8396fb54c4b12aa8b932bda5f3f1caa5693ce
641,689
def normalizeAudio(audio, width): """ Returns audio file that with range +/-1 :param audio: numpy array of audio samples :param width: sample width in bytes (1 = 8 bit, 2 = 16 bit...) :returns: noramlized audio file """ max_val = 2**(8*width-1) return audio/max_val
0210a4d1435577a6f30b009ee5b08917c8e0db29
641,690
def compare_versions(version1, version2, split_char="."): """ Compares two version strings. Each string is to be split into segments by the given string. Each segment is only compared by numerical character value (e.g. a, b, rc are ignored) Ordinality is determined by the first non equal numeric seg...
458eab960571a5acd9dae5729f6276e416651bcc
641,692
def get_cosine_from_similarity(similarity, dp=4): """ Converts the similarity distance metric into a cosine of the angle between the vectors Annoy uses Euclidean distance of normalized vectors for its angular distance, which for two vectors u,v is equal to sqrt(2(1-cos(u,v))) Returns a value betwe...
2e00d48f71e23fc9edec3a0f60a21a61e4a2dbac
641,693
def clean_data(df): """"Removes duplicates to-dos: - correct cat-values that is neither 0 nor 1 """ df = df.drop_duplicates() df = df.replace(2,1) df = df.drop('categories', axis =1) return df
e8efa1d39fdda5ddaa7ba0087317adb58912a029
641,694
def IsWithinTMRegion(pos, posTM):#{{{ """Check whether a residue position is within TM region """ isWithin = False for (b,e) in posTM: if pos >= b and pos < e: return True return False
e12106e8857809dbf31fd88a39e3ea38440a72d7
641,695
def pass_through(df): """ 直接返回参数Dataframe """ return df
ddc4ccea87a6ed76e59e1b510bf087d446d386c4
641,696
def evaluateUDGoogleSpecial(tokensArrayGT, tokensArrayProvider): """See evaluateUD, except we account for Google's service not being able to recognize the POS tags 'INTJ', 'SCONJ', and 'SYM'. The total count of ground-truth tokens is deducted by the occurence count of these three tags. Arguments: token...
e96131c1630edf53f4f20ff82aa23069161089d1
641,699
import numpy def linf_norm(u): """Compute and return the L_inf norm of the a given array u.""" return numpy.max(numpy.abs(u))
a74bf4972577ff839c15c6d2ed83f1be9268e1f5
641,700
def filter_private_methods(method): """Simple filter method. Ignores private functions""" return not method.startswith('_')
b9cd2881c70e340b0311d8ac349ea2d082d1c156
641,702
def _r(): """Return reset sequence""" return '\x01\x1b[0m\x02'
0186c8daa01b8d30eefaa00cf06282d29bdcdef8
641,703
def merge(l_left: list, l_right: list) -> list: """ Helper function to merge the left and right lists based on their order, so if we have [4, 2] on right and [3, 1] on left, the left part will: [2, 4] and [1, 3] finally, when merging these two [1, 2, 3, 4] :param l_left: a list from ...
57c545e847dfb4ae285a3f994588265976d21185
641,704
def trunc_time_minute(date): """ Truncate an object of type DateTime with time to 00:00:00 :param date: Date for truncate :return: Date truncated """ return date.replace(second=0, microsecond=0)
3d7345254f9e38bd8085b1de3adea1cbc5acd642
641,705
def fifo_path(dest, channel, epoch): """Construct full FIFO path. :param dest: Path to directory of FIFO :param channel: FIFO name :param epoch: Integer appended to FIFO name indicating the training epoch :return: full FIFO path """ return dest + '/' + channel + '_' + str(epoch)
9f4b2a1de8778646f639416f5d790231d206e3ca
641,706
def _area(bbox): """Computes area of a 2D bounding box. Args: bbox: A dict with keys 'x1', 'x2', 'y1', 'y2' encoding spatial co-ordinates. Returns: The area of the bounding box. """ return (bbox['x2'] - bbox['x1']) * (bbox['y2'] - bbox['y1'])
2df8bcb275f2592477dfcd08479df374b7a38874
641,707
import requests def get_alert(service, resource): """ Get an entry from alerta :param service: alerta service :param resource: unique resource id of required entry :return: dict """ resp = requests.get(service.data['url'] + "/alerts", params={'environment': service....
001f21c83ad085a27b25616b9a4d568eb5f6625b
641,708
import sys def is_darwin(): """All flavors of Mac (OS X) Returns: bool: True if :attr:`sys.platform` is Mac. """ return sys.platform.startswith('darwin')
c061c5e205bf2c6c6a2692f1a56392eec5fafcde
641,709
import requests def get_user_key(devkey, username, password): """This function retrives the user key of an account on pastebin.""" url = 'https://pastebin.com/api/api_login.php' data = {'api_dev_key': devkey, 'api_user_name': username, 'api_user_password': password} r = requests.post(url, data=dat...
e135d95e2fa859688d292d31f8780fa68d2e6657
641,710
from pathlib import Path def gen_geojson(conn, model_num): """ Queries postgres and returns a geoJSON file with boundary data and properties that give us demographics and transit access data. Parameters ---------- model_num: int The number of the model in question Returns ...
d6c308923776d3e8b1e6e182572b8cc0dc39176c
641,711
def find_vin_pointer_from_txs(txs): """ 找到交易的所有输入单元使用过的UTXO定位指针,并存储在列表中 :param txs: 交易列表 :return: 定位指针集合 """ return [vin.to_spend for tx in txs for vin in tx.tx_in]
145795295e7a6a4b27ab1550a497e1c9eda6c103
641,712
def in2m(inches): """inches -> meters""" return inches*0.0254
cf68093d62b3319a5806e057057676b05d1dc1d8
641,713
def mod10r(number): """ Input number : account or invoice number Output return: the same number completed with the recursive mod10 key """ codec=[0,9,4,6,8,2,7,1,3,5] report = 0 result="" for digit in number: result += digit if digit.isdigit(): report = co...
926eae1dbf1dde52c0fc6a8988bc6fefe7a5a60b
641,714
def get_member_hp(checks, member_uuid, pool_uuid): """Helper function to find a members health in a given pool :param checks list: https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Pool/#healthMonitor :param member_uuid: server UUID we are looking for :param pool_uuid: Connection p...
fca01210c9e0dc592be732dca926c3ef95282a25
641,715
import os import sys def get_path(*path): """Gets the path of the file, from a executable or python environment""" return os.path.join(getattr(sys, "_MEIPASS", os.getcwd()), *path)
e066717c131e4c9157ae7b67cbfe95f10591e2f3
641,716
def workload_job_iterator(workloads_versions, job_id): """ Build list of dicts, where each dict item has 3 key-value pairs, used in the playbook to iterate through 1) workload instances count, 2) workload versions, 3) job replica count. I suppose it does not really match what a jinja2 filter should...
9ed886a8c0b7b3cda08f4d47c16a991d0bd86a2e
641,718
def clip_candidates(a, b, numCandidates): """ Clip retrieved candidates to numCandidates or, in case one method retrieived a smaller list than numCandidates, clip retrieved candidates to the same number as the smaller list. """ a = a[:numCandidates] b = b[:numCandidates] if len(b) <=...
5016b96d1d1e62374f76179968d1b71f57b2619d
641,719
def _generate_automatic_headline(c): """The only field that maps closely to Open511 <headline>, a required field, is optional in TMDD. So we sometimes need to generate our own.""" # Start with the event type, e.g. "Incident" headline = c.data['event_type'].replace('_', ' ').title() if c.data['roads'...
3adee300392bb57457219a7f4eeb106be8997f98
641,720
def CEDecoder(decoder_dict): """Construct a custom decoder for to map the encoded data back to their natural scale (nominal values). Args: decoder_dict (dict): A nested dictionary of the form {col:{encoded_values:original_values}}. Returns: lambda function: A Decoder function. """ ...
2d27ce7105871b08237fb1a2bd03d9ceed53c965
641,721
def board(): """List the legal squares on the board. The board is a standard 8x8 chess board with the center 4 squares removed. """ b = set((x, y) for x in range(8) for y in range(8) if not (3 <= x < 5 and 3 <= y < 5)) return b
39932c141e8e32466ca601f7906d219d5b9ff886
641,722
def config_lower_get(tgt_dict, query, default=None): """ Case Insensitve dict get. :param tgt_dict: Dictionary :param query: String to look for key from :param default: Default value to return if not found. :return: Value in dict if found, otherwise default """ value = {k.lower(): v for ...
5cacbd397491c485804ef5e24cf053aef45e4a4d
641,723
def flatten_nested(iterable): """ Recursively flatten nested structure of tuples, list and dicts. """ result = [] if isinstance(iterable, (tuple, list)): for item in iterable: result.extend(flatten_nested(item)) elif isinstance(iterable, dict): for key, value in sorted(iterab...
794ef2d05fd9bd1541c3a267cdeefc4337d82584
641,724
import base64 def _b64decode(s: str) -> bytes: """ Base 64 decodes a string to bytes. """ return base64.b64decode(s.encode("utf-8"))
587918e0cce5712fdaa9093d14eb3814766fc566
641,725
def get_host_memory_status(ssh, unit=None): """unit: None or 'byte' or 'kilo' or 'mega' or 'giga' or 'human' """ mem_status = {} if unit is None: cmd = "free --kilo | grep -i --color=never mem" else: if unit in ['byte', 'kilo', 'mega', 'giga', 'human']: cmd ...
4fb39d77c9b81191be631c8237772035ce09b299
641,726
from typing import Tuple import logging import os import pathlib def table_ids_from_path(transform_path: str) -> Tuple[str, str]: """ To create the table ids the basename of the transform path is taken and file extensions are stripped. E.g.: /opt/observatory/ :param transform_path: The full path of a ...
ef25c9785f94edb3d1bc9727a491cd3987de2782
641,727
import os def find_latest_checkpoint(directory): """ Finds the latest checkpoint, based on how RLLib creates and names them. """ start = directory max_checkpoint_int = -1 checkpoint_path = "" # 1st layer: Check for the different run folders for f in os.listdir(start): if os.pa...
2b87ce233843f7a7f26aa9b256b0b9002cadc9dd
641,728
import os def get_file_ext(file_path): """ Return the name and extension of a file as a tuple :param file_path: :return: """ file_base = os.path.basename(file_path) name, ext = os.path.splitext(file_base) return name, ext
a41db33c836966a2adfdf87c81255f3aa54c98cc
641,729
def aes_raw_unpad(padded_raw): """Return original raw string from padded raw string.""" return padded_raw[:int(padded_raw[:3]) + 3][3:]
e1372d31e046b1ed9da317b7d5e5b4d79cf1795b
641,730
def mqtt_pipeline_manual_cb(mocker): """This fixture is for use in tests where manual triggering of a callback is required """ return mocker.MagicMock()
dd1db2ba4fda247680b42395af100cf5125ac914
641,731
def alias(aliases): """Decorator for slashcommand aliases that will add the same command but with different names. Parameters ---------- aliases: List[:class:`str`] | :class:`str` The alias(es) for the command with wich the command can be invoked with Usage: .. code-block:: ...
95c20f61348dc043ced53f4e95fac0fb24ee117f
641,732
from typing import Dict from typing import Any def response_state_from_mediation_record(record: Dict[str, Any]): """Maps from acapy mediation role and state to AATH state""" state = record["state"] mediator_states = { "request": "request-received", "granted": "grant-sent", "denied...
15062fc26f13d907299793df692bf1e39932691c
641,733
def data_fields(args, allowed_fields): """Generate data fields dictionary required by some client methods""" data = {} for field in allowed_fields: field_value = getattr(args, field, None) if field_value: data[field] = field_value return data
e141d136d3aeec5b1658cb7ae43c5095cc3ab163
641,734
import os def file_prefix(fn, with_path = False): """ extract the prefix of a file remove extensions .gz, .fq.gz """ assert isinstance(fn, str) p1 = os.path.splitext(fn)[0] px = os.path.splitext(fn)[1] if px.endswith('gz') or px.endswith('.bz'): px = os.path.splitext(p1)[1]...
e31775dd5b5380378db1b869aeed0c1b8b43f2d4
641,736
import os def find_exec(program, curdir=False, otherdirs=[]): """ Determine logical location of a given binary in PATH """ # program is the executable basename to look for # When curdir is True we also check the current directory # Returns fully qualified path to binary, None if not found ...
dbc5da0b5923c52ffefaa7f9f5caa4e8fda7a78f
641,737
def splitname(obj): """ Given an object that has a __module__ and __qualname__, return a list of name components from both. If __module__ is None, 'builtins' is used. """ modname = obj.__module__ or 'builtins' return modname.split('.') + obj.__qualname__.split('.')
2fb223234d01aefa6a9e70269aee36df770e6bae
641,738
def lattice_4square_communities(n_nodes): """ Breaks a square lattice and returns a dictionary of labeled indice lists containing the community labels as keys and the node indices per community as values. :param n_nodes: The number of nodes in the square lattice :return: the dictionary. """ ...
e44586391cacafd49d97d320867227b1910d5fc1
641,739
def double_quote(text): """double-quotes a text""" return '"{}"'.format(text)
def68008cda5f9cccbaf8d88b6f96df2076938bd
641,740
import numpy def genCmtx(sobmtxA, sobmtxB): """when passing the quasi-random sobol-treated A and B matrixes, this function iterates over all the possibilities and returns the C matrix for simulations. See e.g. Saltelli, Ratto, Andres, Campolongo, Cariboni, Gatelli, Saisana, Tarantola Global Sensitivity An...
76a2fdc191ff6e611d216b0fc076a2e4708d3ec9
641,741
def get_n_regions(grid_enc): """ Get the number of regions encoded by compress_background_smartgrid(). Parameters ---------- grid_enc: dict Output from compress_background_smartgrid() Returns ------- int Number of regions encoded """ regions = 0 for row in g...
f64e466752dc4c702423627113e9704c728a0d65
641,742
def get_user_fullname(user): """ログインユーザーの名称を取得する :param user: :return: """ if hasattr(user, 'member'): return user.member.full_name elif user.first_name or user.last_name: return '{}{}{}'.format(user.last_name, ' ' if user.last_name and user.first_name else '', user.first_name) ...
cb7f5b38908a537613fe737632f2ef3fb97abe48
641,743
def remove_chars(line, chars=' \t', quotes='\'\"', comments=None): """ Removes all specified characters but leaves quotes intact. Removes comments if comment character is specified. """ new_line = '' quote_stack = '' remove_comments = (type(comments) is list) or (type(comments) is str) for ...
5cb7ef977192d361f5d5fc4a3a3b3a9329439fba
641,744