content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import time def gettime(): """return timestamp""" return time.time()
38ac710463f03780c7289fd7746d137c51d6466e
8,231
def abs_of_difference(num1: int, num2: int) -> int: """ precondition: parameters must be numbers calculate difference between num1 and num2 and compute absolute value of the result >>> abs_of_difference(-4,5) 9 >>> abs_of_difference(1,-3) 4 >>> abs_of_difference(2,2) 0 """ return abs(num1 - num2)
6cb2ead6a3ed5899a84280f7356a44d515952c7b
8,232
import os def get_gpus(): """ Get the number of gpus per node. Args: None Returns: num_gpus (int): number of gpus per node """ gpu_var = os.environ["SLURM_GPUS_PER_NODE"] num_gpus = int(gpu_var) return num_gpus
667a2be1daf3472a1a30801936d635f8fdcb0a1d
8,233
def int_to_float(value: int) -> float: """Converts a uniformly random [[64-bit computing|64-bit]] integer to uniformly random floating point number on interval <math>[0, 1)</math>. """ fifty_three_ones = 0xFFFFFFFFFFFFFFFF >> (64 - 53) fifty_three_zeros = float(1 << 53) return (value & fifty_three_ones) / fifty_three_zeros
7619ec8d0987d9cac06655cab4e2d0787f1e3232
8,237
def import_(path): """ Import string format module, e.g. 'uliweb.orm' or an object return module object and object """ if isinstance(path, str): v = path.split(':') if len(v) == 1: x = path.rsplit('.', 1) if len(x) == 2: module, func = x else: module, func = x[0], '' else: module, func = v mod = __import__(module) f = mod if func: for x in func.split('.'): f = getattr(f, x) else: f = path return f
70327d474a10f1860012cad0de1bbe934840d9b2
8,240
import sys def get_config_options(): """ get config options list """ result = [] for class_name in dir(sys.modules['RepositoryModule']): if class_name[0].isupper() and class_name != 'Repository': result.append(class_name) return result
ebbf9076b771a2522e4fdafee2e40749815d7251
8,241
def validate(value, ceiling): """ Checks if val is positive and less than the ceiling value. :param value: The value to be checked (usually an int) :param ceiling: The highest value "val" can be. (usually an int) :return: True if val is less than ceiling and not negative """ value = int(value) return 0 <= value < ceiling
0736674f74a38e0a583eeb2fae2ee1f441c1fda7
8,243
def erratum_check(agr_data, value): """ future: check a database reference has comment_and_corrections connection to another reference :param agr_data: :param value: :return: """ # when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8 return 'Success: Errata references created, but connections not created yet, add to sample_reference_populate_load.sh later'
f05b6835db3410b6e3705aab226571d916948594
8,245
def longestConsecutive3(list,missing=1): """ assume list is a list budget missing """ if len(list) == 0: return 0 longest = 0 # print(range(len(list)-1)) starts = [ x for x in range(len(list)) ] # print(starts) for sindex in starts: currentlen = 0 allow = missing # print(sindex) # print(sindex,list[sindex:]) for element in list[sindex:]: if element == 1: currentlen += 1 else: allow -= 1 if allow < 0: break starts[sindex] = currentlen if currentlen > longest: longest = currentlen # print(sindex,currentlen) return longest
52420837ee40be40e8d8d6ea9a6f25372bed8d55
8,246
def gen_vocab_dict(train_data): """ generate dict from training set's caption file (txt) format of txt file: id1 video_id1 caption1 id2 video_id2 caption2 ... """ vocab = {} inv_vocab = {} vocab[''] = len(vocab) inv_vocab[len(vocab) - 1] = '' for line in train_data: words = line['caption'].strip().split() for word in words: if word not in vocab: vocab[word] = len(vocab) inv_vocab[len(vocab) - 1] = word vocab['BOS'] = len(vocab) inv_vocab[len(vocab) - 1] = 'BOS' vocab['EOS'] = len(vocab) inv_vocab[len(vocab) - 1] = 'EOS' # vocab_size = len(vocab) # with open('vocab_natsuda.json', 'w') as f: # json.dump(vocab , f) return vocab, inv_vocab
56e7e596f20e2da81f1e40a059fca1bc80d21bde
8,247
from typing import Dict def calculate_frequency(lst: list) -> Dict[str, int]: """Calculate the frequency from a list.""" frequencies = {} for item in lst: if item in frequencies: frequencies[item] += 1 else: frequencies[item] = 1 return frequencies
b38deeddca3d57a9e4545a51feec0c245adce9b8
8,248
import numpy def getelts(nda, indices): """From the given nda(ndarray, list, or tuple), returns the list located at the given indices""" ret = []; for i in indices: ret.extend([nda[i]]); return numpy.array(ret);
91383b0b40d33f3c197bcb5b9d20900ae963cc47
8,249
def _RoundTowardZero(value, divider): """Truncates the remainder part after division.""" # For some languanges, the sign of the remainder is implementation # dependent if any of the operands is negative. Here we enforce # "rounded toward zero" semantics. For example, for (-5) / 2 an # implementation may give -3 as the result with the remainder being # 1. This function ensures we always return -2 (closer to zero). result = value // divider remainder = value % divider if result < 0 and remainder > 0: return result + 1 else: return result
2c9d70c30d135684b3016584ab9c61aad32b3f7d
8,250
import os def should_stop(experiment_path): """ Checks if liftoff should exit no mather how much is left to run. """ return os.path.exists(os.path.join(experiment_path, ".STOP"))
bb3f52a9560d42c52cedaea9ea8a1f848b64d4b7
8,251
def first_dup(s): """ Find the first character that repeats in a String and return that character. :param s: :return: """ for char in s: if s.count(char) > 1: return char return None
300d9c60123bbceff8efde84be43c26f527f2fc0
8,252
def type_check(tags): """Perform a type check on a list of tags""" if type(tags) in (list, tuple): single = False elif tags == None: tags = [] single = False else: tags = [tags] single = True if len([t for t in tags if type(t) not in (str,bytes)]) == 0: valid = True else: valid = False return tags, single, valid
519fb2bcf0b8c8792465cc2e057e3dea8f611841
8,253
def input_position(): """ input the position option for pasted QR code """ option = input('Please select the position (1:left-top, 2:right-top, 3:left-bottom, 4:right-bottom, 5:left-middle, 6:right-middle) for QR code: ') if option == '': pos = 1 print(' Use the default position, option 1: left-top on background.') else: pos = int(option) if pos > 6 or pos < 1: pos = 1 return pos
80e2b69d04991781515790c4fd0fbb6719d3e6d4
8,254
def return_countries(): """ Get the countries available :return: country JSON """ with open("country.json", "r") as country: return country.read()
b927b6b4b6797a76fd047ed88c2809b66df206b9
8,256
def get_pbs_node_requirements(sys_settings,node_count): """Get the cpu and memory requirements for a given number of nodes Args: sys_settings (dict): System settings dict, as supplied from config_manager node_count (int): Number of whole nodes on target system Returns: dict: ncpus and mem for target number of nodes """ ncpus = node_count * sys_settings['REMOTE_SETTINGS']['PBS_SETTINGS']['CORES_PER_NODE'] mem_per_node = sys_settings['REMOTE_SETTINGS']['PBS_SETTINGS']['MEM_PER_NODE'] mem = '%s%s' % (int(node_count * mem_per_node[0]), mem_per_node[1]) return dict(ncpus=ncpus,mem=mem)
f4fd12dee6608a87e6c8b0f2f56e245e6be7c0fc
8,257
from unittest.mock import Mock def api_fixture(): """Define a fixture for simplisafe-python API object.""" api = Mock() api.refresh_token = "token123" api.user_id = "12345" return api
2270391b02dd02de71a312ed6d6edd780c5bdff2
8,258
def select_table_value_from_page(**params): """从画面上选择出一个列表的数据""" return """\ with open('../script_lib/parse_table_value.js', encoding='utf-8') as file: script = file.read() header = driver.execute_script(script, '{header_selector}')[0] result = driver.execute_script(script, '{data_selector}') input_indexs = '{except_column_indexs}' except_column_indexs = sorted([int(d.replace(' ', '')) for d in input_indexs.split(',')]) page_data = format_to_df(result, columns=header) for col in except_column_indexs: del page_data[header[col]] """.format(**params)
d9e5087b50188b6c4e4125bfa396ae2e9b02a6db
8,259
def families_lens(): """.""" return ['Lens', 'LensRev']
dd1c39ca606f100fc3efbf22be2a402507d262de
8,260
def myreplace(old, new, s): """Replace all occurrences of old with new in s.""" result = " ".join(s.split()) # firsly remove any multiple spaces " ". return new.join(result.split(old))
4355251d3c52424041ce86b2449843c565beb301
8,262
def cookie_session_name() -> str: """ Retorna o nome do cookie para a sessão. """ return "ticket_session"
eaa4517b0635ea8e57d07a46d90c6bcdc3d044e8
8,264
def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy): """Attempt to insert padding around the result of a regex draw while preserving the match.""" result = draw(strategy) left_pad = draw(left_pad_strategy) if left_pad and regex.search(left_pad + result): result = left_pad + result right_pad = draw(right_pad_strategy) if right_pad and regex.search(result + right_pad): result += right_pad return result
6e3a6f1481e9d432b63cc237e68f89035aa56588
8,265
def even(value): """Simple validator defined for test purpose""" return not (int(value) % 2)
1774e55ef53799ff16f232c3ca51c322cadf1d54
8,266
def find_permutation(s, pattern): """Find presence of any permutation of pattern in the text as a substring. >>> find_permutation("oidbcaf", "abc") True >>> find_permutation("odicf", "dc") False >>> find_permutation("bcdxabcdy", "bcdxabcdy") True >>> find_permutation("aaacb", "abc") True """ k = len(pattern) if k > len(s): return False count = {} for c in pattern: count[c] = count.get(c, 0) + 1 matches = 0 win_start = 0 for win_end, next_char in enumerate(s): if next_char in count: count[next_char] -= 1 if count[next_char] == 0: matches += 1 if win_end >= k - 1: if matches == len(count): return True first_char = s[win_start] if first_char in count: if count[first_char] == 0: matches -= 1 count[first_char] += 1 win_start += 1 return False
ba823208ed92fc3da9725081f3dfca87c5a47875
8,268
def thermal_conductivity_carbon_steel(temperature): """ DESCRIPTION: [BS EN 1993-1-2:2005, 3.4.1.3] PARAMETERS: OUTPUTS: REMARKS: """ temperature += 273.15 if 20 <= temperature <= 800: return 54 - 0.0333 * temperature elif 800 <= temperature <= 1200: return 27.3 else: return 0
cfeb40bcff2b2acb6bf8c60f1bea2b00f323207a
8,270
def putListIntoInt(inList, base = 2): """takes a list of values and converts it into an int""" string = "".join(str(i) for i in inList) return int(string, base)
a73c3f64e44962a34d974098e0b04fe92395adc8
8,272
def false_pred(): """Returns a predicate that always returns ``False``.""" def new_pred(*args): return False return new_pred
07dcd2e8594bd27eb4d520b240a0e3e722c7bc79
8,273
import random def __random_positions(max_position): """Generates two random different list positions given a max position. The max position is exclusive. ... Args: max_position(integer): The maximum position """ [lhs, rhs] = random.sample(range(0, max_position - 1), 2) return (lhs, rhs)
ee35a6ed30400c885b7769962de483c34cc0ab41
8,274
def create_deployment(inputs, labels, blueprint_id, deployment_id, rest_client): """Create a deployment. :param inputs: a list of dicts of deployment inputs. :type inputs: list :param labels: a list of dicts of deployment labels. :type labels: list :param blueprint_id: An existing blueprint ID. :type blueprint_id: str :param deployment_id: The deployment ID. :type deployment_id: str :param rest_client: A Cloudify REST client. :type rest_client: cloudify_rest_client.client.CloudifyClient :return: request's JSON response :rtype: dict """ return rest_client.deployments.create( blueprint_id, deployment_id, inputs, labels=labels)
84b7a13c0ef6b67b20755bc92ecc6814db0be5b0
8,275
import re def split_sentences(text, delimiter="\n"): """ Split a text into sentences with a delimiter""" return re.sub(r"(( /?[.!?])+ )", rf"\1{delimiter}", text)
7f69afaa8add8947073d1bf4133da145fba81cac
8,276
def items_iterator(dictionary): """Add support for python2 or 3 dictionary iterators.""" try: gen = dictionary.iteritems() # python 2 except: gen = dictionary.items() # python 3 return gen
e3da23ad32f491958887f14aae1f4d34a5d58c4e
8,277
def control_game(cmd): """ returns state based on command """ if cmd.lower() in ("y", "yes"): action = "pictures" else: action = "game" return action
669a7b4a9335719aa9176c32c9891f6d017a1bc0
8,278
import timeit def run_trial(rep, num): """Sleep for 100 milliseconds, 'num' times; repeat for 'rep' attempts.""" sleep = 'sleep(0.1)' return min(timeit.repeat(stmt=sleep, setup = 'from time import sleep', repeat=rep, number=num))
fcdcea9e63531b7de12ccbf27ab584829b8354b9
8,279
def git_errors_message(git_info): """Format a list of any git errors to send as slack message""" git_msg = [ { "color": "#f2c744", "blocks": [ { "type": "divider" }, { "type": "section", "text": {"type": "mrkdwn", "text": ":github: *Git errors*"} } ] } ] for item in git_info: name = item['branch'] info = item['error'] git_info = [ { "type": "section", "text": {"type": "mrkdwn", "text": f"error pushing branch: {name} ```{info}```"} } ] git_msg[0]['blocks'].extend(git_info) return git_msg
192c1f5c85c4615828873795eb8f71d8ced4080e
8,280
def Distribution_of_masses(**kwds): """ 输出双黑洞质量的分布。(ratio_step 不能小于 0.01,可以通过增大 doa=100 提高精度) Input: 共有三种输入方式,如下面的例子: Eg1: mass1_scope = (5,75), mass2_scope = (5,75), mass_step = 2 Eg2: mass1_scope = (5,75), mass_step = 2, ratio_scope = (0.1,1), ratio_step = 0.1 Eg3: Mass_scope = (5, 300), Mass_step = 1, ratio_scope = (0.01, 1), ratio_step = 0.05 Output: A list of tuples with masses in it. """ doa = 100 # ratio 的精度设计 if 'mass1_scope' in kwds and 'mass2_scope' in kwds and 'mass_step' in kwds and 'ratio_scope' not in kwds: (m1s, m1e), (m2s, m2e), m_step = kwds['mass1_scope'], kwds['mass2_scope'], kwds['mass_step'] return sorted([(m1, m2) for m1 in range(m1s, m1e +m_step, m_step) for m2 in range(m2s, m2e +m_step, m_step) if m1 >= m2]) elif 'mass1_scope' in kwds and 'mass_step' in kwds and 'ratio_scope' in kwds and 'ratio_step' in kwds and 'Mass_scope' not in kwds: (m1s, m1e), m_step = kwds['mass1_scope'], kwds['mass_step'] (rs, re), r_step = kwds['ratio_scope'], kwds['ratio_step'] return sorted([(m1, m1*ratio/doa) for m1 in range(m1s, m1e +m_step, m_step) for ratio in range(int(rs*doa), int(re*doa+r_step*doa), int(r_step*doa)) if m1 + m1*ratio/doa <= m1e ]) elif 'Mass_scope' in kwds and 'Mass_step' in kwds and 'ratio_scope' in kwds and 'ratio_step' in kwds and 'mass1_scope' not in kwds: (Ms, Me), M_step = kwds['Mass_scope'], kwds['Mass_step'] (rs, re), r_step = kwds['ratio_scope'], kwds['ratio_step'] return sorted([(doa*M/(doa+ratio), ratio*M/(doa+ratio)) for M in range(Ms, Me, M_step) for ratio in range(int(rs*doa), int(re*doa+r_step*doa), int(r_step*doa)) if doa*M/(doa+ratio) >= ratio*M/(doa+ratio)]) else: raise KeyError("Something wrong on the keywords!")
aaef2ddcf589f9a299685344f1ee076e469150bf
8,282
def DecodePublic(curve, bb): """ Decode a public key from bytes. Invalid points are rejected. The neutral element is NOT accepted as a public key. """ pk = curve.Decode(bb) if pk.is_neutral(): raise Exception('Invalid public key (neutral point)') return pk
7bf8d7eb129fe640475fbf404354c204f3242954
8,283
def compact(it): """Filter false (in the truth sense) elements in iterator.""" return filter(bool, it)
0d84d2e7c35447969bfb3b357389e416c71b40bd
8,284
def session_capabilities(session_capabilities): """Log browser (console log) and performance (request / response headers) data. They will appear in `Links` section of pytest-html's html report. """ session_capabilities["loggingPrefs"] = { "browser": "ALL", "performance": "ALL" } return session_capabilities
ab87146f815dffa905a60d143f7aebf4a64d3ad0
8,285
def calculate_overlap_rate(inventor_class_nbr_group_count_dict): """ 计算交叠率 :param inventor_class_nbr_group_patent_count: :return: """ #发明家的总数 inventor_cnt = len(inventor_class_nbr_group_count_dict.keys()) #无法分组的发明家数量 cant_group_inventor = 0 for inventor, class_nbr_group_count_dict in inventor_class_nbr_group_count_dict.items(): #如果在class_nbr_group_count_dict中对应max值的大于等于2个,则说明无法判断属于哪个分组 #sort_list是按dict中的value排序后形成list #形如:[('g01',3),('g02',2)] #所以只需判断sort_list中第1,2个元素的value是否相等即可即sort_list[0][1] == sort_list[1][1] sort_list = sorted(class_nbr_group_count_dict.items(), key=lambda x: x[1], reverse=True) if len(sort_list) > 1 and not sort_list[0][1] == sort_list[1][1]: cant_group_inventor += 1 #计算比值 return (cant_group_inventor + 0.0) / inventor_cnt
0c59c8ffaf8407b4f1ede86c8a3b5b4202f211fc
8,286
import ast def _parse_mock_imports(mod_ast, expanded_imports): """Parses a module AST node for import statements and resolves them against expanded_imports (such as you might get from _expand_mock_imports). If an import is not recognized, it is omitted from the returned dictionary. Returns a dictionary suitable for eval'ing a statement in mod_ast, with symbols from mod_ast's imports resolved to real objects, as per expanded_imports. """ ret = {} for node in mod_ast.body: if isinstance(node, ast.Import): for alias in node.names: if alias.name in expanded_imports: ret[alias.asname or alias.name] = expanded_imports[alias.name] elif isinstance(node, ast.ImportFrom): if node.level == 0: for alias in node.names: fullname ='%s.%s' % (node.module, alias.name) if fullname in expanded_imports: ret[alias.asname or alias.name] = expanded_imports[fullname] return ret
50cb8e4e2469b7bf63deacf0a5085afcded0b5e3
8,287
import os import numpy as np def merge_coord_and_label_files(ROI_coords_dir): """ utils for merging different label and coord file before computing label masks if necessary should be rewritten to more more general with glob("Coord*.txt) and glob("Labels*.txt)... """ list_coords = [] list_labels = [] for event in ['Odor','Recall']: print(event) event_coords_file = os.path.join(ROI_coords_dir,"Coord_Network"+event+".txt") print(event_coords_file) for line in open(event_coords_file): print(line) list_coord = list(map(int,line.strip().split('\t'))) print(list_coord) list_coords.append(list_coord) event_labels_file = os.path.join(ROI_coords_dir,"Labels_Network"+event+".txt") for line in open(event_labels_file): print(line) list_labels.append(line.strip()) print(list_coords) print(list_labels) print(len(list_coords)) print(len(list_labels)) ###### saving merged file all_coords_file = os.path.join(ROI_coords_dir,"Coord_Network_Odor-Recall.txt") all_labels_file = os.path.join(ROI_coords_dir,"Labels_Network_Odor-Recall.txt") np.savetxt(all_coords_file,np.array(list_coords,dtype = 'int'),fmt = '%d') np.savetxt(all_labels_file,np.array(list_labels,dtype = 'string'),fmt = '%s') return all_coords_file,all_labels_file
0e6965aa1c7f3699f1e5f0b7fef957f09e680e85
8,288
def calc_field_size(field_type, length): """ Рассчитывает размер данных поля :param field_type: Тип поля :type field_type: string :param length: Длина поля :type length: int :return: Длина поля в байтах :rtype: int """ if field_type == 'B': return length elif field_type == 'L': return 1 elif field_type == 'N': return length // 2 + 1 elif field_type == 'NC': return length * 2 elif field_type == 'NVC': return length * 2 + 2 elif field_type == 'RV': return 16 elif field_type == 'NT': return 8 elif field_type == 'I': return 8 elif field_type == 'DT': return 7 else: raise ValueError('Unknown field type')
677b28d03d02e45d2f7a771c3c895c16060c229a
8,289
def SortByName(list_response): """Return the list_response sorted by name.""" return sorted(list_response, key=lambda x: x.name)
5cb48e536790c9f246aebe2a38bba77f329c5ae9
8,290
import re def unindent(string): """Remove the initial part of whitespace from string. >>> unindent("1 + 2 + 3\\n") '1 + 2 + 3' >>> unindent(" def fun():\\n return 42\\n") 'def fun():\\n return 42' >>> unindent("\\n def fun():\\n return 42\\n") 'def fun():\\n return 42' >>> unindent(" def fun():\\n return 42\\n\\n") 'def fun():\\n return 42' """ string = re.sub(r'^\n*', '', string.rstrip()) # ignore leading and trailing newlines match = re.match(r'^([\t ]+)', string) if not match: return string whitespace = match.group(1) lines = [] for line in string.splitlines(True): if line.startswith(whitespace): lines.append(line[len(whitespace):]) else: return string return ''.join(lines)
1179d4d4a67380b95d46b3234e4b09fb83f36041
8,292
import torch def quad_kappa_loss(input, targets, y_pow=1, eps=1e-15): """ https://github.com/JeffreyDF/kaggle_diabetic_retinopathy/blob/master/losses.py#L22 :param input: :param targets: :param y_pow: :param eps: :return: """ batch_size = input.size(0) num_ratings = 5 assert input.size(1) == num_ratings tmp = torch.arange(0, num_ratings).view((num_ratings, 1)).expand((-1, num_ratings)).float() weights = (tmp - torch.transpose(tmp, 0, 1)) ** 2 / (num_ratings - 1) ** 2 weights = weights.type(targets.dtype).to(targets.device) # y_ = input ** y_pow # y_norm = y_ / (eps + y_.sum(dim=1).reshape((batch_size, 1))) hist_rater_b = input.sum(dim=0) # hist_rater_b = y_norm.sum(dim=0) hist_rater_a = targets.sum(dim=0) O = torch.mm(input.t(), targets) O = O / O.sum() E = torch.mm(hist_rater_a.reshape((num_ratings, 1)), hist_rater_b.reshape((1, num_ratings))) E = E / E.sum() nom = torch.sum(weights * O) denom = torch.sum(weights * E) return - (1.0 - nom / denom)
f7aab107d9264384f04f1b8ba331223adcb495aa
8,293
def is_tag_exists( lf_client, account_id: str, key: str, ) -> bool: """ Check if an Lake Formation tag exists or not Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lakeformation.html#LakeFormation.Client.get_lf_tag """ try: lf_client.get_lf_tag(CatalogId=account_id, TagKey=key) return True except Exception as e: if str(e).endswith("GetLFTag operation: Tag key does not exist"): return False else: raise e
9f323ee97d4dfc67b183f5bcdc46229fd328eff6
8,294
def browse_repository(script, project, repository): """ Gets the list of repositories for the specified project :param script: A TestScript instance :type script: TestScript :param project: The project for the repository :type project: str :param repository: The repository to browse :type repository: str :return: The browse response as a string :rtype: str """ return script.http("GET", "/projects/%s/repos/%s/browse" % (project, repository))
c3c98c625b3ed0e1de3e795861eb29c9825ef5e8
8,295
import collections def build_node_statistics(nodes, images): """Build a dictionary of cache statistics about a group of nodes.""" # Generic statistics applicable to all groups of nodes. node_statistics = { 'provisioned': len(list(filter(lambda n: n.provisioned, nodes))), 'not provisioned': len(list(filter(lambda n: not n.provisioned, nodes))), 'available (not cached)': len(list(filter(lambda n: n.can_cache(), nodes))), 'cached (includes \'caching\')': len(list(filter(lambda n: n.cached and not n.provisioned, nodes))), 'total': len(nodes), 'images': collections.defaultdict(lambda: 0) } image_names_by_uuid = {image.uuid: image.name for image in images} # Build statistics around which images are cached. for node in nodes: if (node.cached and not node.provisioned and node.cached_image_uuid is not None): # If we don't know the name of the image, just return the UUID. image_name = image_names_by_uuid.get(node.cached_image_uuid, node.cached_image_uuid) node_statistics['images'][image_name] += 1 return node_statistics
6f1b6a7128a088168f3d31054458275d5f13df53
8,296
def render_instruction(name, content): """ Render an arbitrary in-line instruction with the given name and content """ return ':{}: {}'.format(name, content)
2200ab1c865dbad871395476fc2227cc8995b3d1
8,297
def parse_agent_req_file(contents): """ Returns a dictionary mapping {check-package-name --> pinned_version} from the given file contents. We can assume lines are in the form: datadog-active-directory==1.1.1; sys_platform == 'win32' """ catalog = {} for line in contents.splitlines(): toks = line.split('==', 1) if len(toks) != 2 or not toks[0] or not toks[1]: # if we get here, the requirements file is garbled but let's stay # resilient continue name, other = toks version = other.split(';') catalog[name] = version[0] return catalog
7d3516327ffaf147ee85c150921c876ba5ee2980
8,299
def make_etag(hasher): """Build etag function based on `hasher` algorithm.""" def etag(buf): h = hasher() for chunk in buf: h.update(chunk) return '"' + h.hexdigest() + '"' return etag
31963ebacf886298a60e383d2a0c278293a59012
8,301
def indexof(ilist, item): """ returns the index of item in the list """ i = 0 for list_item in ilist: list_item = list_item.strip() if list_item == item: return i i += 1 print("ERROR failed to parse config, can't find item:", item) exit(-4)
e6b24d8b6455433f7b6afd824045fbec0dfabfc6
8,302
from typing import List from typing import Tuple def deflate_spans( spans: List[Tuple[int, int, int]] ) -> List[List[Tuple[int, int]]]: """[summary] Args: spans (List[Tuple[int, int, int]]): [description] Returns: List[List[Tuple[int, int]]]: [description] """ # assuming last element in the tuple is the step id spans = sorted(spans, key=lambda x: (x[2], x[0], x[1])) max_step = max(step_idx for _, _, step_idx in spans) return [ [(s, e) for s, e, step_idx in spans if step_idx == idx] for idx in range(max_step + 1) ]
037c11b0c5d4707b2d19a0b0cc457a93908f5186
8,304
def operate_status_template(open_now: bool) -> tuple: """Flex Message 餐廳營業狀況 Args: open_now (bool): 營業中 Returns: tuple: (營業狀況, 營業文字顏色) """ if open_now: operate_status = { "type": "text", "text": "營業中", "size": "xs", "color": "#ffffff", "align": "center", "gravity": "center", } operate_color = "#9ACD32" else: operate_status = { "type": "text", "text": "休息中", "size": "xs", "color": "#ffffff", "align": "center", "gravity": "center", } operate_color = "#FF6347" return (operate_status, operate_color)
366d291b5e847192401f76f0c8a560c02452cef7
8,305
def paramset_to_rootnames(paramset): """ Generates parameter names for parameters in the set as ROOT would do. Args: paramset (:obj:`pyhf.paramsets.paramset`): The parameter set. Returns: :obj:`List[str]` or :obj:`str`: The generated parameter names (for the non-scalar/scalar case) respectively. Example: pyhf parameter names and then the converted names for ROOT: * ``"lumi"`` -> ``"Lumi"`` * unconstrained scalar parameter ``"foo"`` -> ``"foo"`` * constrained scalar parameter ``"foo"`` -> ``"alpha_foo"`` * non-scalar parameters ``"foo"`` -> ``"gamma_foo_i"`` >>> import pyhf >>> pyhf.set_backend("numpy") >>> model = pyhf.simplemodels.uncorrelated_background( ... signal=[12.0, 11.0], bkg=[50.0, 52.0], bkg_uncertainty=[3.0, 7.0] ... ) >>> model.config.parameters ['mu', 'uncorr_bkguncrt'] >>> pyhf.compat.paramset_to_rootnames(model.config.param_set("mu")) 'mu' >>> pyhf.compat.paramset_to_rootnames(model.config.param_set("uncorr_bkguncrt")) ['gamma_uncorr_bkguncrt_0', 'gamma_uncorr_bkguncrt_1'] """ if paramset.name == 'lumi': return 'Lumi' if paramset.is_scalar: if paramset.constrained: return f'alpha_{paramset.name}' return f'{paramset.name}' return [f'gamma_{paramset.name}_{index}' for index in range(paramset.n_parameters)]
0fc4732a7accff55f8015c5b46cb1c44c002ef18
8,306
import time def get_items_serial_number(prefix, obj): """获取物品唯一货号""" date_str = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) # 生成一个固定6位数的流水号 objmodel = obj.objects.last() serial_number = objmodel.id if objmodel else 0 serial_number = "{0:06d}".format(serial_number + 1) return "{}{}{}".format(prefix, date_str, serial_number)
c8482b0debe680b36845d3ee933d0771c4efe05f
8,308
def header_string(key_length=0, number_of_seconds=2): """ return a header string for the output file """ header_string = '#' header_string += ' ' * (key_length+8) header_string += ' 1 2 3 ' * number_of_seconds + '\n' header_string += '#' header_string += ' ' * (key_length+8) header_string += '1234567890123456789012345678901-' * number_of_seconds + '\n' return(header_string)
8da90fa3171be1f3ce20932777835c5f2239d4a0
8,311
from typing import Optional def int_to_comma_hex(n: int, blength: Optional[int] = None) -> str: """ int_to_comma_hex Translates an integer in its corresponding hex string :type n: ``int`` :param n: Input integer :type blength: ``Optional[int]`` :param blength: Add padding to reach length :return: Translated hex string :rtype: ``str`` """ bhex = f'{n:x}' if len(bhex) % 2 == 1: bhex = '0' + bhex if blength is not None: bhex = '00' * max(blength - len(bhex), 0) + bhex return ':'.join([bhex[i:i + 2] for i in range(0, len(bhex), 2)])
a1833b68b4c179070f454bb675909b3e3495b8cf
8,312
def adcm_api_credentials() -> dict: """ADCM credentials for use in tests""" return {"user": "admin", "password": "admin"}
a2efa47ee588086b0d5dc089728e18b9108964a8
8,313
import re def Language_req(description): """Create a function that captures the language requirements from the job description""" description = description.lower() matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeutsch\b", description) for item in matches: return item
cb6ce14d3cba497f668c701d16c13fdfd78f5dc5
8,314
import logging def matrix_hits(binary_matrix): """Gets the number of cells with value 1 in matrix.""" logging.info("Counting how many contacts are predicted.") count = 0 (n1, n2) = binary_matrix.shape for i in range(n1): for j in range(n2): if j > i: count += binary_matrix[i, j] return count
0242b2844fb2f761e6ba542031f6b188e7d5286e
8,315
from typing import Dict import os def registry() -> Dict[str, Dict]: """ Return a dictionary of problems of the form: `{ "problem name": { "params": ..., }, ... }` where `flexs.landscapes.RosettaFolding(**problem["params"])` instantiates the rosetta folding landscape for the given set of parameters. Returns: dict: Problems in the registry. """ rosetta_data_dir = os.path.join(os.path.dirname(__file__), "data/rosetta") return { "3msi": { "params": { "pdb_file": f"{rosetta_data_dir}/3msi.pdb", "sigmoid_center": -3, "sigmoid_norm_value": 12, }, "starts": { "ed_3_wt": "MAQASVVANQLIPINTHLTLVMMRSEVVTYVHIPAEDIPRLVSMDVNRAVPLGTTLMPDMVKGYAA", # noqa: E501 "ed_5_wt": "MAQASVVFNQLIPINTHLTLVMMRFEVVTPVGCPAMDIPRLVSQQVNRAVPLGTTLMPDMVKGYAA", # noqa: E501 "ed_7_wt": "WAQRSVVANQLIPINTGLTLVMMRSELVTGVGAPAEDIPRLVSMQVNRAVPLGTTNMPDMVKGYAA", # noqa: E501 "ed_12_wt": "RAQESVVANQLIPILTHLTQKMSRRFVVTPVGIPAEDIPRLVNAQVDRAVPLGTTLMPDMDKGYAA", # noqa: E501 "ed_27_wt": "MRRYSVIAYQERPINLHSTLTFNRSEVPWPVNRPASDAPRLVSMQNNRSVPLGTKLPEDPVCRYAL", # noqa: E501 }, }, "3mx7": { "params": { "pdb_file": f"{rosetta_data_dir}/3mx7.pdb", "sigmoid_center": -3, "sigmoid_norm_value": 12, }, }, }
acf7dc0edb4d241d345c5b22a1caf387416951f9
8,319
def str2bool(val): """Convert string to boolean value """ try: if val.lower() in ['false', 'off', '0']: return False else: return True except AttributeError: raise TypeError('value {0} was not a string'.format(type(val)))
01d97b141686a79d310ab59a4acb318250b0746b
8,320
def remove_outliers(df): """Summary Line. Extended description of function. Args: arg1: Function will remove 1.5 IQR outliers from data set. Returns: Will return a data set with outliers within the 1.5 IQR range removed. """ q1 = df.quantile(0.25) q3 = df.quantile(0.75) iqr = q3 - q1 df = df[~((df < (q1 - 1.5 * iqr)) | (df > (q3 + 1.5 * iqr))).any(axis=1)] return df
6333665ddfc4f77b12604c4161ba56c0818663eb
8,321
def get_layers(net_param): """Get layers information. Parameters ---------- net_param : caffe_pb2.NetParameter A pretrined network description. Returns ------- layers : list description of the layers. version : string version information of the pretrained model. """ if len(net_param.layers) > 0: return net_param.layers[:], "V1" elif len(net_param.layer) > 0: return net_param.layer[:], "V2" else: raise Exception("Couldn't find layers!")
6af46460f0ba9fa41111e265cd5e63a14b8ad5cb
8,322
def get_all_coords(rdmol): """Function to get all the coordinates for an RDMol Returns three lists""" conf = rdmol.GetConformer() x_coords = [] y_coords = [] z_coords = [] for atm in rdmol.GetAtoms(): x_coords.append(conf.GetAtomPosition(atm.GetIdx()).x) y_coords.append(conf.GetAtomPosition(atm.GetIdx()).y) z_coords.append(conf.GetAtomPosition(atm.GetIdx()).z) return x_coords, y_coords, z_coords
14399748a77d565f2d65f8ae8f47ec2924c64683
8,325
def evaluations(ty, pv): """ evaluations(ty, pv) -> ACC Calculate accuracy using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 for v, y in zip(pv, ty): if y == v: total_correct += 1 l = len(ty) ACC = 100.0 * total_correct / l return ACC
021c80dab1d4ed97876bebc882db3423af107ea5
8,327
def _is_member_of(cls, obj): """ returns True if obj is a member of cls This has to be done without using getattr as it is used to check ownership of un-bound methods and nodes. """ if obj in cls.__dict__.values(): return True # check the base classes if cls.__bases__: for base in cls.__bases__: if _is_member_of(base, obj): return True return False
c5bfb2920efc3992a92da236471f1de85cdb27a1
8,328
import os def _remove_creds(creds_file=None): """ Remove ~/.onecodex file, returning True if successul or False if the file didn't exist """ if creds_file is None: fp = os.path.expanduser("~/.onecodex") else: fp = creds_file if os.path.exists(fp): os.remove(fp) return True return False
ea25ea62b825353bd5f71dc003ceb6e530aab7c6
8,331
from typing import Optional from typing import Dict from typing import List def scripts(page_content: Optional[Dict]) -> List[str]: """ .. _`example reference server`: https://github.com/stellar/django-polaris/tree/master/example Replace this function with another by passing it to ``register_integrations()`` as described in :doc:`Registering Integrations</register_integrations/index>`. Return a list of strings containing script tags that will be added to the bottom of the HTML body served for the current request. The scripts will be rendered like so: :: {% for script in scripts %} {{ script|safe }} {% endfor %} `page_content` will be the return value from ``content_for_template()``. `page_content` will also contain a ``"form"`` key-value pair if a form will be rendered in the UI. This gives anchors a great deal of freedom on the client side. The `example reference server`_ uses this functionality to inject Google Analytics into our deployment of Polaris, and to refresh the Confirm Email page every time the window is brought back into focus. Note that the scripts will be executed in the order in which they are returned. """ return []
8e591eace462a5649533811bf1c54575f5714174
8,332
import argparse def describe_argparser(): """ Return an argument parser for the describe function """ parser = argparse.ArgumentParser() parser.add_argument("variant", help="Variant to describe, example: RV64GC") return parser
a5c78d2c39373e73204fce8724e240ef084ab0b6
8,333
def _GetSheriffForTest(test): """Gets the Sheriff for a test, or None if no sheriff.""" if test.sheriff: return test.sheriff.get() return None
daa272df6a1882e1379531b2d34297da8bec37b3
8,334
def booth(args): """ Booth function Global minimum: f(1.0,3.0) = 0.0 Search domain: -10.0 <= x, y <= 10.0 """ return (args[0] + 2*args[1] - 7)**2 + (2*args[0] + args[1] - 5)**2
8adf94d9e96ee19758a6e495775d8bdb10330794
8,335
def makeset(weatherpart): """ with open("WeatherWear/clothes.csv") as f: reader = csv.reader(f) next(reader) data = [] for row in reader: data.append( [float(cell) for cell in row[:13]] ) clothes = data """ clothes = [[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 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0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]] for i in range(len(clothes)): clothes[i] = clothes[i] + weatherpart return clothes
be8ca4b1e64585fed368bde0baa447a13d2da7e3
8,336
import math def rainbow_search(x, y, step): """Returns RGB color tuple """ xs = math.sin((step) / 100.0) * 20.0 ys = math.cos((step) / 100.0) * 20.0 scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2 r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale) g = math.sin((x + xs) * scale) + math.cos((y + ys) * scale) b = math.sin((x + ys) * scale) + math.cos((y + ys) * scale) return (r * 255, g * 255, b * 255)
dc1d05f24fe9fb44857210c9fd962ffa4465e1f9
8,339
def recursive_any_to_dict(anyElement): """ Recursive any nested type into a dict (so that it can be JSON'able). :param anyElement: Just about any 'attrs-ized' instance variable type in Python. :return: A dict structure """ if isinstance(anyElement, dict): simple_dict = {} for key, value in anyElement.items(): if isinstance(value, dict): simple_dict[key] = recursive_any_to_dict(value) else: simple_dict[key] = value return simple_dict elif isinstance(anyElement, list): # deal with attrs' list handling simple_list = [] for index in range(len(anyElement)): value = recursive_any_to_dict(anyElement[index]) simple_list.append(value) return simple_list elif isinstance(anyElement, str): return anyElement elif isinstance(anyElement, bool): return str(anyElement) elif isinstance(anyElement, int): return str(anyElement) # all other types at this point here are presumably attrs-ized class-type simple_dict = {} for element in anyElement.__attrs_attrs__: simple_dict[element.name] = recursive_any_to_dict(getattr(anyElement, element.name)) return simple_dict
7e94c93c9470c218781ee0a0059f8b95b0f663e5
8,340
from typing import OrderedDict def genListHeaders(P4Graph): """ Generate the dictionnary of headers. P4Graph : JSon imported file Name, size """ headers = OrderedDict() return headers
6077d41968dc8958ebf1f0d55d1c05607d77915c
8,341
def _int_to_riff(i: int, length: int) -> bytes: """Convert an int to its byte representation in a RIFF file. Represents integers as unsigned integers in *length* bytes encoded in little-endian. Args: i (int): The integer to represent. length (int): The number of bytes used to represent the integer. Returns: bytes: The bytes representation of the specified integer. """ return i.to_bytes(length, "little", signed=False)
9c382486be14af3e5ec22b5aed7c2d9dc3f21d57
8,343
import pathlib def sample_odb_fixture(): """Get the fully qualified path to the sample odb file.""" return str(pathlib.Path(__file__).parent.parent / "resources" / "sample.odb")
12bb3567dc5c5e86bfd6c1042c1c4c3fe310b95a
8,344
def reproject(link, node, epsg): """ reporoject link and node geodataframes for nodes, update X and Y columns """ link = link.to_crs(epsg=epsg) node = node.to_crs(epsg=epsg) node["X"] = node["geometry"].apply(lambda p: p.x) node["Y"] = node["geometry"].apply(lambda p: p.y) return link, node
5ead99d074ea1d643f598d790b083dda511caa1a
8,345
def to_class_name(value): """Convert the current view's object to a usable class name. Useful for outputting a css-class for targetting specific styles or javascript functionality on a per-view basis, for example: <div class="siteContainer {% if request.path == '/' %}home{% else %}{{ object|to_class_name|lower }}{% endif %}"> # noqa """ return value.__class__.__name__
384f566d3808c19d7ba1357b7cddc69a92ca0b5a
8,346
def _create_fold(X, ids): """Create folds from the data received. Returns ------- Data fold. """ if isinstance(X, list): return [x[ids] for x in X] elif isinstance(X, dict): return {k: v[ids] for k, v in X.items()} else: return X[ids]
8c1308913f470632657b909114806875a30fa17f
8,347
def dict_map(**fs): """Map especific elements in a dict. Examples: ```pycon >>> dict_map(a=int, b=str)(dict(a='1', b=123, c=True)) {'a': 1, 'b': '123', 'c': True} >>> ``` """ def _change_dict(d): d = d.copy() for k, f in fs.items(): if k in d: d[k] = f(d[k]) return d return _change_dict
ac67bf69df2aa1aead3da7443a83a09974f8a545
8,349
def StrContains(input_string, substring): """ Return True if the substring is contained in the concrete value of the input_string otherwise false. :param input_string: the string we want to check :param substring: the string we want to check if it's contained inside the input_string :return: True is substring is contained in input_string else false """ return substring.value in input_string.value
b04c22d567be6d1fce664f99719169b4585d75ea
8,351
from typing import Iterable def get_closest(iterable: Iterable, target): """Return the item in iterable that is closest to the target""" if not iterable or target is None: return None return min(iterable, key=lambda item: abs(item - target))
9548954317e90574d7a6d232bc166bde2eea7863
8,352
import collections def utils_vlan_ports_list(duthosts, rand_one_dut_hostname, rand_selected_dut, tbinfo, ports_list): """ Get configured VLAN ports """ duthost = duthosts[rand_one_dut_hostname] cfg_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts'] mg_facts = rand_selected_dut.get_extended_minigraph_facts(tbinfo) vlan_ports_list = [] config_ports = {k: v for k,v in cfg_facts['PORT'].items() if v.get('admin_status', 'down') == 'up'} config_portchannels = cfg_facts.get('PORTCHANNEL', {}) config_port_indices = {k: v for k, v in mg_facts['minigraph_ptf_indices'].items() if k in config_ports} config_ports_vlan = collections.defaultdict(list) vlan_members = cfg_facts.get('VLAN_MEMBER', {}) # key is dev name, value is list for configured VLAN member. for k, v in cfg_facts['VLAN'].items(): vlanid = v['vlanid'] for addr in cfg_facts['VLAN_INTERFACE']['Vlan'+vlanid]: # address could be IPV6 and IPV4, only need IPV4 here if addr.find(':') == -1: ip = addr break else: continue if k not in vlan_members: continue for port in vlan_members[k]: if 'tagging_mode' not in vlan_members[k][port]: continue mode = vlan_members[k][port]['tagging_mode'] config_ports_vlan[port].append({'vlanid':int(vlanid), 'ip':ip, 'tagging_mode':mode}) if config_portchannels: for po in config_portchannels: vlan_port = { 'dev' : po, 'port_index' : [config_port_indices[member] for member in config_portchannels[po]['members']], 'permit_vlanid' : [] } if po in config_ports_vlan: vlan_port['pvid'] = 0 for vlan in config_ports_vlan[po]: if 'vlanid' not in vlan or 'ip' not in vlan or 'tagging_mode' not in vlan: continue if vlan['tagging_mode'] == 'untagged': vlan_port['pvid'] = vlan['vlanid'] vlan_port['permit_vlanid'].append(vlan['vlanid']) if 'pvid' in vlan_port: vlan_ports_list.append(vlan_port) for i, port in enumerate(ports_list): vlan_port = { 'dev' : port, 'port_index' : [config_port_indices[port]], 'permit_vlanid' : [] } if port in config_ports_vlan: vlan_port['pvid'] = 0 for vlan in config_ports_vlan[port]: if 'vlanid' not in vlan or 'ip' not in vlan or 'tagging_mode' not in vlan: continue if vlan['tagging_mode'] == 'untagged': vlan_port['pvid'] = vlan['vlanid'] vlan_port['permit_vlanid'].append(vlan['vlanid']) if 'pvid' in vlan_port: vlan_ports_list.append(vlan_port) return vlan_ports_list
e9d0c5aa6fbfbfe9fe5ecce4e389c6f286ee875b
8,353
def normalise(matrix): """Normalises the agents' cumulative utilities. Parameters ---------- matrix : list of list of int The cumulative utilities obtained by the agents throughout. Returns ------- list of list of int The normalised cumulative utilities (i.e., utility shares) obtained by the agents throughout. """ totals = [ sum(line) for line in matrix ] return [ list(map(lambda x: x/tot, line)) for line, tot in zip(matrix, totals) ]
594a46c9f1f741509ac56439779597545e63f25d
8,354
import os def findFile(input): """ Search a directory for full filename with optional path. """ _fdir, _fname = os.path.split(input) if _fdir == '': _fdir = os.curdir flist = os.listdir(_fdir) found = False for name in flist: if not name.find(_fname): found = True return found
6b9fe7ad0facef2f38cab67f0228e7ca68c7ca36
8,356
def cmdline_from_pid(pid): """ Fetch command line from a process id. """ try: cmdline= open("/proc/%i/cmdline" %pid).readlines()[0] return " ".join(cmdline.split("\x00")).rstrip() except: return ""
61ca5cf3f109863e516a861f76dafd1d6e9dc749
8,357
def none_if_empty(tup): """Returns None if passed an empty tuple This is helpful since a SimpleVar is actually an IndexedVar with a single index of None rather than the more intuitive empty tuple. """ if tup is (): return None else: return tup
26ee7bb9720eaa532d901b9c1f6c4a0fb6f7a340
8,358
def print_melhor_time(funcao_atual_ou_futuro): """Função que imprirmi o melhor time. Parameters ---------- funcao_atual_ou_futuro : list Lista contendo um time de jogadores Returns ------- str Texto organizando o time por posição """ gol, zag1, zag2, lat1, lat2, mei1, mei2, mei3, ata1, ata2, ata3 = funcao_atual_ou_futuro return f"""O melhor time é formado por: -> Goleiro-O melhor goleiro será o {gol} -> Zagueiro-A melhor dupla de zagueiro será {zag1} e {zag2} -> Laterais-A melhor dupla de lateral será {lat1} e {lat2} -> Meias-O melhor meia será composto por {mei1}, {mei2} e {mei3} -> Atacantes->O melhor ataque será composto por {ata1}, {ata2} e {ata3}"""
99c41728dea118cbcd8b6c61188f33f25a8663d1
8,359
def update_named_ports(mig, named_ports): """ Set the named ports on a Managed Instance Group. Sort the existing named ports and new. If different, update. This also implicitly allows for the removal of named_por :param mig: Managed Instance Group Object from libcloud. :type mig: :class: `GCEInstanceGroupManager` :param named_ports: list of dictionaries in the format of {'name': port} :type named_ports: ``list`` of ``dict`` :return: True if successful :rtype: ``bool`` """ changed = False existing_ports = [] new_ports = [] if hasattr(mig.instance_group, 'named_ports'): existing_ports = sorted(mig.instance_group.named_ports, key=lambda x: x['name']) if named_ports is not None: new_ports = sorted(named_ports, key=lambda x: x['name']) if existing_ports != new_ports: if mig.instance_group.set_named_ports(named_ports): changed = True return changed
3a2bd1f591e32629b6257454a491173fb96824e2
8,361
def _attributes_equal(new_attributes, old_attributes): """ Compare attributes (dict) by value to determine if a state is changed :param new_attributes: dict containing attributes :param old_attributes: dict containing attributes :return bool: result of the comparison between new_attributes and old attributes """ for key in new_attributes: if key not in old_attributes: return False elif new_attributes[key] != old_attributes[key]: return False return True
11c92f000f1811254db48a8def3e681a09e8a9a9
8,367
def open(self): """获取开盘价序列""" return self.openArray[-self.size:]
a254b5a389c9b450a685926083b849584ae2a6f9
8,370
from datetime import datetime def detect_resolution(d1: datetime, d2: datetime) -> int: """ Detects the time difference in milliseconds between two datetimes in ms :param d1: :param d2: :return: time difference in milliseconds """ delta = d1 - d2 return int(delta.total_seconds() * 1e3)
a5300254b9f2d84d8111fcb3ad9f222ce6b5a9a6
8,373
def total_distance(solution, distanceMap): """ Calculate the total distance among a solution of cities. Uses a dictionary to get lookup the each pairwise distance. :param solution: A list of cities in random order. :distanceMap: The dictionary lookup tool. :return: The total distance between all the cities. """ totalDistance = 0 for i, city in enumerate(solution[:-1]): # Stop at the second to last city. cityA = city cityB = solution[i + 1] buildKey = (cityA, cityB) totalDistance += distanceMap[buildKey] # Build the key to return home cityA = solution[-1] cityB = solution[0] goHome = (cityA, cityB) totalDistance += distanceMap[goHome] return totalDistance
b478c09540fb93d210df895a9ed31939bf889121
8,374
import struct def py_float2float(val, be=False): """ Converts Python float to 4 bytes (double) """ sig = '>f' if be else '<f' return struct.pack(sig, val)
e828bdedc1bca3536d6c6b5c90bf0cb4bf958066
8,375