content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _eval_at(poly, x, prime): """Evaluates polynomial (coefficient tuple) at x, used to generate a shamir pool in make_random_shares below. """ accum = 0 for coeff in reversed(poly): accum *= x accum += coeff accum %= prime return accum
62aa6718d0a1bc4f1fc8e1eee43a6941b96dfbe6
673,751
def _covariate_name_to_smooth(covariate_name, local_covariates, mulcovs): """Find in this model context the Smooth for a given covariate name.""" covariate_objs = [cobj for cobj in local_covariates if cobj.name == covariate_name] if not covariate_objs: return None elif len(covariate_objs) > 1: ...
e54e93aa22aa5ffd38f4cbfc538e059ca3da3288
673,752
def text_coas(): """ Text certificates of analysis to their recipients. """ # Get the certificate data. # Text links to the contacts. return NotImplementedError
9223da2ebed8721a7f89e75bd3d842bbacdb294e
673,753
def override(d1: dict, d2: dict) -> dict: """Overrides a nested dictionary 'd1' with a nested dictionary 'd2' :param d1: A dictionary to be overwritten (Dorest default configuration) :param d2: A dictionary to overwrite (API configuration) :return: An overwritten dictionary """ return {**{**d1,...
0143db1ff0f4771a30542c8144fcb00ceef56dcb
673,754
def simple_call_string(function_name, argument_list, return_value=None): """Return function_name(arg[0], arg[1], ...) as a string""" call = function_name + "(" + \ ", ".join([var + "=" + repr(value) for (var, value) in argument_list]) + ")" if return_value is not None: ca...
bd5c026f9bf573cbdb99e25872851f46e1218b09
673,755
def get_ticket_url_from_id(ticket_id): """ Get the associate ticket id :param ticket_id: `str` ticket_id :return: `str` ticket url """ return "https://jira.com/id={0}".format(ticket_id)
33a5b7994dc477a9e32d634728ffc6cda42b6d6d
673,756
def _q_start(query_seq, q_seq): """ returns the starting pytyon string index of query alignment (q_seq) in the query_sequence (query_seq) :param query_seq: string full query sequence :param q_seq: string alignment sequence (may contain gaps as "-") :return: :example: >>_q_start(query_seq = ...
25882b80e2adb2ac95cf238c23d0a0afb1e69f9b
673,757
from typing import List def set_ignored_keys(**kwargs) -> List[str]: """ Lets users pass a list of string that will not be checked by case-check. For example, validate_response(..., ignore_case=["List", "OF", "improperly cased", "kEYS"]). """ if 'ignore_case' in kwargs: return kwargs['igno...
9a753f560d36ce4fc28450907f2eb1d6e3306e9a
673,758
def cesar(clear, key, encode=True): """ retourne l'encryption du caractere <clear> par la clé <key> le caractère <key> doit être un caractère alphabétique ASCII c'est à dire que son ord() est entre ceux de 'a' et 'z' ou entre ceux de 'A' et 'Z' Parameters: clear: le caractère à encoder ...
1cb6c4085d82ee45e419ba8127a46c857d4eaf10
673,759
def ft2m(ft): """feet -> meters""" return 0.3048*ft
8ab872d97eb8adcc2cbf72bae270ea5e9045a5ff
673,760
def format_labels(labels): """ Convert a dictionary of labels into a comma separated string """ if labels: return ",".join(["{}={}".format(k, v) for k, v in labels.items()]) else: return ""
44a1f649fd6f9d9d18212e725cb40ce1dab99a18
673,761
def _refresh_candles(candle: dict, candlelist: list[dict], max_len: int = 10000) -> tuple[list[dict], bool]: """Recieve candlestick data and append to candlestick list if it is new candlestick.""" changed = False if candle['k']['x']: if candlelist: if candle['k']['t'] != candlelist[-1]['...
0f898036e0dbf660ef91482e28bc5e95631b08ed
673,762
def join_string_expr(delimiter): """Return a function that can join string expressions.""" def _join_string_expr(tokens): if len(tokens) == 1: return tokens[0].strip('"') else: result = [tokens[0]] for token in tokens[1:]: result.extend(token)...
c398b761d49e28f2c4751de9884167d6ed2c3376
673,764
import os def map_sample_name_to_column(segregation_table): """ Return a dictionary mapping NP sample names to column names in a segregation table. :param segregation_table: Input segregation table. :type segregation_table: :ref:`segregation table <segregation_table>` :returns: Dictionary of ...
64134127afdb139e90be1362ef3388c116e5bf78
673,765
import re def _tokenize(text): """ Reference to an array of the tokens comprising the input string. Each token is either a tag (possibly with nested, tags contained therein, such as ``<a href="<MTFoo>">``, or a run of text between tags. Each element of the array is a two-element array; the first i...
99a27466bb41e35a77cd261b45251ca5381312ed
673,766
import fileinput import sys def cat(*file_names): """ create a generator of line in file_names files (without endline) """ def _cat(input): if file_names: input = fileinput.FileInput(file_names) else: input = sys.stdin for elt in input: yiel...
ace06829814bf78bdc2f467c41d2e1961b4bdc7d
673,767
def check_positive(y_prime): """ Chack that substrate values are not negative when they shouldnt be """ for i in range(len(y_prime)): if y_prime[i] < 0: y_prime[i] = 0 return y_prime
c8d067ea6e995b3fb16d80ef35551a7837310a32
673,768
def get_string_for_language(language_name): """ Maps language names to the corresponding string for qgrep. """ language_name = language_name.lower().lstrip() if language_name == "c": return "tc-getCC" if language_name == "c++" or language_name == "cxx": return "tc-getCXX" if ...
a90f2bbaf1c73832cc0f6057dc9ac812024523d8
673,769
def minmaxscaler(x): """ MinMax scale of a dataset Arguments : :x: pandas Dataframe contening the data to standardize Output : A pandas DataFrame with scaled values """ x_stats = x.describe().transpose() return ((x-x_stats['max'])/(x_stats['max']-x_stats['min']))
bbf25fed8a534d1ab16a874837c221811f575b6f
673,770
def _trc_filename(isd, version): """ Return the TRC file path for a given ISD. """ return 'ISD%s-V%s.trc' % (isd.isd_id, version)
01205a1cde280d7f7fd046906e2919d973752707
673,771
def get_recs(user_recs, k=None): """ Extracts recommended item indices, leaving out their scores. params: user_recs: list of lists of tuples of recommendations where each tuple has (item index, relevance score) with the list of tuples sorted in order of decreasing relevance ...
490d0473e640c70457aa69a9af7dc7a4269e39d3
673,772
import torch def polar_to_rect(mag, ang): """Converts the polar complex representation to rectangular""" real = mag * torch.cos(ang) imag = mag * torch.sin(ang) return real, imag
840039244b303b3f176fbaa29d2ab52d400eb04b
673,773
def AppRcr(b, k, f, kappa, simplex_flag=False, nearest=False): """ Approximate reciprocal of [b]: Given [b], compute [1/b] """ alpha = b.get_type(2 * k)(int(2.9142 * 2**k)) c, v = b.Norm(k, f, kappa, simplex_flag) #v should be 2**{k - m} where m is the length of the bitwise repr of [...
434b97de3015e832212d7c5768499df48ce13450
673,774
def get_contactinfo_tuple(member, considerNoPublish=False): """Returns tuple with the member's contact information If considerNoPublish is True a member with noPublishContactInfo_fld == 1 will get empty contact information fields. """ contactinfo = member.contactinfo department = '?' try: ...
48eb20d0ec4befeb1791fbc407fc7d55f5fd8c7e
673,775
import re def regex_escape(string): """Escape all regular expressions special characters from STRING.""" return re.escape(string)
16af3984ee43515b9f0cc2089bcfecf590331cdb
673,776
def make_place_dictionary(all_places): """ Make dictionary from list of place names/ places id tuples. Dictionary keys = place names, values = number of times place has been added to all maps """ place_dictionary = {} for place in all_places: if place_dictionary.get(place) == ...
2c86da54c8a554d19995c55c790627ba7b786759
673,777
from datetime import datetime def is_valid_isodate(date: str, check_timezone: bool = False) -> bool: """Check if a string is a valid ISO formatted datestring""" dt = None try: dt = datetime.fromisoformat(date) except ValueError: return False if check_timezone: if dt.tzinf...
212c16236c79ef51d369cef18401cfcfd89e246f
673,779
def _append_notes_to_markdown(*, markdown: str, notes: str) -> str: """ Append a notes string to a specified markdown string. Parameters ---------- markdown : str Target markdown string. notes : str Target notes string. Returns ------- markdown : str Result ...
399e9361be9317961a1d071dc36bfb1de49a7161
673,780
import logging import copy def experiment_winner(Battle, num_battles, name_expected_winner): """ Args: Battle: <Battle> Battle instance to evaluate against num_battles: <int> number of battles to run to calculate probability name_expected_winner: <str> name of the Pokemon to calculate ...
f66cf06f387244d53174a0fd9eed8bd18a7c9f0d
673,781
def inhg_to_hpa(value: float) -> float: """Convert an inHg value to hPa.""" return value * 33.8639
1c1366646d3a74059251d9e263c807689c6fd87a
673,782
import re def determine_file_extension_from_response(response): """ This retrieves the file extension from the response. :param requests.Response response: the response object from the download :return the extension indicating the file compression(e.g. zip, tgz) :rtype str """ content_disp...
dd5fd45ef44eea4911331ca463054d0433fb83d9
673,783
import traceback def format_last_exception(prefix=" | "): """Format the last exception for display it in tests. This allows to raise custom exception, without loosing the context of what caused the problem in the first place: >>> def f(): ... raise Exception("Something terrible happened") ...
03506e79fba39cca25d9af817750e7d6742a9603
673,784
def get_next_connection_index(db, profile_id, folder_path): """Finds next connection index Args: db (object): The db object profile_id (int): The id of the profile folder_path (str): The folder path used for grouping and nesting connections Returns: Next connection index va...
9d1d30e08833c5a09ca09a3a80e4a46dc04abd31
673,785
from datetime import datetime def ucis_Time(): """Current time in UCIS Y/M/D/H/M/S format""" return datetime.now().strftime("%Y%m%d%H%M%S")
03018751e1ffcaba7b4775eed133a65ba39c6746
673,786
import json import requests def containerRemove(apikey,container_id): """ *Move* folder from public to trashbin the folder will not be public available. apikey: Your ApiKey from FileCrypt container_id: the container_id as string """ data={"api_key":apikey,"fn":"containerV2","sub":"remove","container_id":contain...
f068375084df4c9e39b04120b138668425ba0c71
673,787
def fixture_seir_data(sir_data_wo_policy): """Returns data for the SIHR model """ x, p = sir_data_wo_policy pp = p.copy() xx = x.copy() pp["alpha"] = 0.5 pp["nu"] = 1 pp["initial_exposed"] = 0 return xx, pp
9091ce921c001f6cb4b94852b96b7929af654036
673,788
import re def splitcamelcase(string): """Transform CamelCase into camel case""" res = "" for ch in string: if re.match('[A-Z]', ch): res += ' ' + ch.lower() else: res += ch return res
be6e51c65174fc9542de05f04b6243147152a99b
673,789
def redraw(environment, unit, objects): """Redraw an environment image. Keyword arguments: - environment -- the image array of the environment - unit -- the size of the sides of the quadratic environment - objects -- a list containing the objects in the environment """ environment.fill(0) ...
7bbfe4a5b594c62ecfbb1ddefc776a29e1ebe07e
673,790
def encryptData(kms_client, data, key_path_name): """ Args: kms_client: data: key_path_name: str - 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/keyRings/YOUR_KEY_RING/cryptoKeys /YOUR_CRYPTO_KEY' Returns: response: str - """ response = kms_client.e...
e827db71d54db52df2cc417004b334c01f7e4a6b
673,791
def can_make_target_sum(integers, target): """Return True if a pair of integers that add up to `target` are found. The time complexity of this algorithm is O(N), where N is the number of integers in `integers`.""" complements = set() for i in integers: # O(N) complement = target - i # O(1)...
c9d92bd75e06457c01875fa82fcb3d9d9ba65de4
673,792
import itertools def flatten_list(lst): """concatenate a list of lists""" return list(itertools.chain.from_iterable(lst))
9134175bb322a8c11d2f30e6ba1d23fa075fc73d
673,793
def calculate_manhattan_dist(idx, value, n): """calculate the manhattan distance of a single tile""" goalRow = value // n #row index at goal goalCol = value % n #col index at goal currentRow = idx // n #current row index currentCol = idx % n #current col index dist = abs(goalRow - currentRo...
4952262666a1d8d4b6c93a436be092f9b50c0480
673,794
def parse_slots(content): """Parse the list of slots. Cleans up spaces between items. Parameters ---------- content: :class:`str` A string containing comma separated values. Returns ------- :class:`str`: The slots string. """ slots = content.split(",") retu...
45d8410be8a628c21d40bbb7d543da9e451d7650
673,795
def fixed_points(G): """Return a list of fixed points for the discrete dynamical system represented by the digraph G. """ return [n for n in G if G.out_degree(n) == 0]
dbd1a918ecc06e23d909e205dbc83d49f8cb2e85
673,796
def isfloat(in_str): """Check if a string can be cast to float""" try: float(in_str) return True except ValueError: return False
c06d46ea0b7fc8bfba9dcafe644bc878d138ab54
673,798
from os import listdir from os.path import join, abspath, dirname def discover_plugins(): """ This function try to discover installed plugins dinamically :return: a list with plugins names :rtype: list(str) """ path = join(abspath(dirname(__file__)), "libs", "plugins") plugin_list = []...
5e269124871c09c1e6534e4a7e92e60f21dd5579
673,799
def get_primary_axis(hist): """Returns the highest dimension axis, e.g. if 1D histo this will return the y-axis. """ dim = hist.GetDimension() if dim == 1: return hist.GetYaxis() elif dim == 2: return hist.GetZaxis()
32099e76fc47081c15bd8f63ae04a11919e2b53e
673,800
import torch def get_device_pytorch(device: str): """Get Pytorch compute device. :param device: device name. """ # translate our own alias into framework-compatible ones return torch.device(device)
87438ab209166c7899d07d3ef82451dd339080e3
673,801
def xtype_from_derivation(derivation): """Returns the script type to be used for this derivation.""" if derivation.startswith("m/84'"): return 'p2wpkh' elif derivation.startswith("m/49'"): return 'p2wpkh-p2sh' else: return 'p2pkh'
247a24644bb69e45b3b85f530594adfaa37e4afd
673,802
import json def load_entities(path): """ Load the entities and return an dict carrying all relevant info """ try: with open(path) as file: entities = json.loads(file.read()) ents = {} for e in entities['entities']: ents[e['entity']] = {'ope...
ddc82ea030af64a2b222ec18f7122833e495e2af
673,803
import re def ExtractThroughput(output): """Extract throughput from MNIST output. Args: output: MNIST output Returns: throuput float """ regex = r'INFO:tensorflow:global_step/sec: (\S+)' match = re.findall(regex, str(output)) return sum(float(step) for step in match) / len(match)
ba513b965fb8706bc2d113db3ce387f0565ae4cc
673,805
def hex2bytes(hex_str): """ Converts spaced hexadecimal string (output of ``bytes2hex()``) function to an array of bytes. Parameters ---------- hex_str: str String of hexadecimal numbers separated by spaces. Returns ------- bytes Array of bytes (ready to be unpicked). ...
7deb5fcc2e805eb8e82392d86f3adcc98b0e4365
673,806
def getfullURL(date): """Returns Congressional Record URL (of PDF record) for a given date.""" base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" return base_url
36cf3160c0e1c8afe888ad9b001e5c9eac8bce03
673,807
import math def lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0): """Return a 1-dimensional Lorentzian function. lorentzian(x, amplitude, center, sigma) = (amplitude/(1 + ((1.0*x-center)/sigma)**2)) / (pi*sigma) """ return (amplitude / (1 + ((1.0 * x - center) / sigma) ** 2)) / (math.pi * sig...
b25721a6e69639206195799d6b69bdc0e9357b01
673,808
def replace_keys(origin_str, key, alias): """ Return the string replaced Lustre keys with alias """ key = key.lower() alias = alias.lower() replace_dict = {} replace_dict[key] = alias replace_dict[key.upper()] = alias.upper() replace_dict[key.capitalize()] = alias.capitalize() fo...
008c985b179521e8ce4023d148206332754f3e72
673,809
def index_sets(items): """ Create a dictionary of sets from an iterable of `(key, value)` pairs. Each item is stored in a set at `key`. More than one item with same key means items get appended to same list. This means items in indices are unique, but they must be hashable. """ index = {} ...
22184945b32857366cbfbfceba9d6fff2332c3fa
673,810
import types import errno def from_file(file_path: str, silent: bool = False): """ Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :param file_path: :param silent: """ d = types.ModuleType('config') d.__file__ =...
6811544b345464a6fb32beb5341777d69b986398
673,811
def _getAllSpacesInConstraint(spaceConstraintData): """ Return a combined list of native and dynamic spaces for a constraint. Args: spaceConstraintData (dict): The loaded space constraint data from the space constraint node Returns: A list of dict representing spaces applie...
f05b437d9233c9d5da36dfd69aaf45e132aafa17
673,812
def extend_palette(palette, colors=256, rgb=3): """Extend palette colors to 256 rgb sets.""" missing_colors = colors - len(palette)//rgb if missing_colors > 0: first_color = palette[:rgb] palette += first_color * missing_colors return palette[:colors*rgb]
091eb60d36f3ed8ad24c2c2905b52058b16f63c0
673,814
def log_sum_exp(x): """calculate log(sum(exp(x))) = max(x) + log(sum(exp(x - max(x)))) """ max_score = x.max(-1)[0] return max_score + (x - max_score.unsqueeze(-1)).exp().sum(-1).log()
754b87d13043e63b928c63de453782b22d44c135
673,816
def align_by_pelvis_batch(joints): """ Assumes joints is 14 x 3 in LSP order. Then hips are: [3, 2] Takes mid point of these points, then subtracts it. """ left_id = 2 right_id = 3 pelvis = (joints[:, left_id, :] + joints[:, right_id, :]) / 2.0 return joints - pelvis[:, None, :]
7b7c77d9c02c52a5ca6f93661595ca0972f7bd2d
673,817
import os def makeEmissionNCFile(dataDirBase="/pierce-scratch/mariavm",\ NCVariable="CO",\ RCPScenario="RCP85",\ decade="20000101-20101231"): """function for getting path of desired variable nc file path Parameters: dataD...
5395126ceba8ab9fcdd8f08e25ea0fad42af22ff
673,818
def tim(method): """ Decorator to time a method call of an ETL if its output object supports it Args: method (function) the method to time """ def tm(*args, **kwargs): slf = args[0] if hasattr(slf.o, "timeit"): return slf.o.timeit(method, slf.o, *args, **kwargs) ...
931280fc647c78cb4fb4701b57d962f8255a252c
673,819
def run_command(command, args, cwd): """Runs a command with the given context. Args: command: ManageCommand to run. args: Arguments, with the app and command name stripped. cwd: Current working directory. Returns: 0 if the command succeeded and non-zero otherwise. Raises: ValueError: The ...
03c77b2e357acee0c1aad3fd6b5c0b092aa919b2
673,820
def divisible(a, b): """Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.""" return not a % b
1322afa568feaf440f5d73f8611e741a8b5d479f
673,821
def mock_strategy(mocker): """Mock strategy""" strategy = mocker.Mock() strategy.request.COOKIES = {} return strategy
6bd9053730911bf6f88858ad1cd437c1b1ec0c56
673,823
def BitSet(x, n): """Return whether nth bit of x was set""" return bool(x[0] & (1 << n))
d331fe0d2f6367409bf1933954a9de3fb051446f
673,824
import os import glob def expand_args(args, on_linesep, on_glob, on_homepath): """Expands arguments list. Args: on_linesep: Set True to split on occurrences of os.linesep. This is reasonably safe -- line separators appear to be escaped when given to Python on the command line. on_glob: Se...
ea00ae00b2e2964aa28a2610a77308feea6c50df
673,825
def read_queries(): """Reads queries.txt and returns a list of X, Y, Z triplets. Returns: list: the list of queries """ with open('queries.txt', 'r') as q_file: queries = [] for line in q_file: X, Y, Z = [], [], [] x, y, z = line.split() X...
e8df6fbbeab2ec58483f2c58eb1fb653ed8e9c35
673,826
import base64 def decodeCipherString(cipherString): """decode a cipher tring into it's parts""" mac = None encryptionType = int(cipherString[0:1]) # all that are currently defined: https://github.com/bitwarden/browser/blob/f1262147a33f302b5e569f13f56739f05bbec362/src/services/constantsService.js#L13-L21 assert e...
89e27a60e0f14d1eb355ccd84af78f0deb694a92
673,827
import uuid def generate_request_id(): """ create randmon request_id """ return uuid.uuid4().hex
5d1335a4b0136f93c83e09a15d50718da3f95795
673,828
def get_corresponding_letter(index, sentence): """ Get the letter corresponding to the index in the given sentence :param index: the wanted index. :param sentence: the reference sentence. :return: the corresponding letter if found, 'None' otherwise. """ if index < len(sentence.letters): ...
4bc6df4228d2e8fc9fdd7ce2791c33d5f2a96257
673,829
import os def prepare_data(data_dir): """ prepare training/testing data return a list of all the image files, along with a list of the classes the image belongs to """ images = [] classes = [] # each data dir contains subdirs of images for each class for class_dir in os.listdir(da...
7ae98d6a6b4d0394046560fe73fac4e9d5008cb4
673,830
def memoize(fn): """Decorator to cache a function. .. warning:: Make sure it's a functional method (i.e., no side effects)! """ cache = {} def newfn(*args, **kw): key = (tuple(args), tuple(sorted(kw.items()))) if key in cache: return cache[key] else: ...
de9ee1de922a0e752ab4c699276a68ff2d1f7e64
673,831
import numpy def smooth_hue_palette(scale): """Takes an array of ints and returns a corresponding colored rgb array.""" # http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL # Based on http://stackoverflow.com/a/17382854 , with simplifications and # optimizations. Assumes S=1, L=0.5, meaning C=1 and m=0. # 0 ...
cfa97d38b1c2a3c95ec519430c33ccf374096277
673,832
def expandmodules(moduleparams, moduledefs): """ moduleparams: list of str names for the install.sh options moduledefs: dict with definitions as returned by getmoduledefs returns list of all expanded modules behind the alias """ modules = [] for mdef in moduleparams: if mdef in modul...
b1bda5b80af0a14a7d1541ed75bfd7329d81871a
673,833
from typing import Any from typing import Union from typing import Type from typing import Callable def try_else(source: Any, target_type: Union[Type, Callable], default_type: Union[None, Type, Callable] = None) -> Any: """ try to do something, and catch and return either some default operation, or the origin...
417e8846e4f457d6d3bcdb9ae296a4dc1da103f5
673,834
import torch def gpu_count(gpus: int) -> int: """ Find the number of GPUs to use. By default, the application attempts to use all GPUs available in the system but users can specify a different number of GPUs if desired. If the system doesn't have any GPUs available, it will default to the CPUs. I...
f835af6f989acc11baa76d63e25e1cf96b3d136f
673,835
import os def _make_unique_log_dir(desired_logdir, counter_limit=500): """ This function makes a unique log directory based on the desired_logdir path. Append _n(where n<= 500) to the basename as required to make sure we don't overwrite an existing directory. :param desired_logdir: ``name of th...
73f9b297ec4ffcb16a4bc8a3eb5a2d4f268ca95e
673,836
def directMessage(message, username=None, email=None, anyoneCanOpenIncidents=None): """(Integration only) Executes command provided in direct message to messaging bot Args: message (str): The message sent in personal context username (str): The username of the user that sent the direct message ...
012e9757a97d40369500d546e60c470f3820072b
673,837
def loc2Dict(loc): """ Convert a loc into a dictionary, for the consideration of maintainability. Parameters ---------- loc: list A location, in format of [lat, lon] or [lat, lon, alt] Return ------ dictionary A dictionary of location """ if (len(loc) == 2): locDict = { 'lat': loc[0], 'lon': loc...
2531cc2bec1c6acbb6999d19c7459da717c54a84
673,838
from typing import List def unique(object: List): """Remove duplicates from a list while preserving the order""" # list(set(object)) does the unique job, but it sets to random order u = [] for item in object: if item not in u: u.append(item) return u
666a768f4b5108e23f220662119df06e9eb38337
673,839
def _excute_async(func_obj, params=None): """把一个方法变成异步调用。 """ return func_obj(**params)
e7cf91117d9ec5070e0aa9c8a4803c53452331a8
673,840
import os def get_tempest_default_config_dir(): """Get default config directory of tempest There are 3 dirs that get tried in priority order. First is /etc/tempest, if that doesn't exist it looks for a tempest dir in the XDG_CONFIG_HOME dir (defaulting to ~/.config/tempest) and last it tries for a ...
e0bf5acbb78886c3b0d1074f85151776c10163e4
673,841
def _create_board(size=4): """Generating the empty starting game board This board can be of any (nxn) size. 0 = a space with no tile """ return [[0 for j in range(size)] for i in range(size)]
9ccacfbf5b8bd034aeb5d5498861223378de3c05
673,842
def apc(x): """Perform average product correct, used for contact prediction. Args: x: np array. Returns: apc np array """ a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to red...
00c995d5a5aeb43ab6a0e33e1a4f64ee92a31ee9
673,843
from typing import Tuple from typing import Dict def key(product_: Tuple[str, Dict]) -> Tuple[float, float]: """Lemma 1 sorting key for the fixed attention problem. An optimal ranking for the fixed attention problem is sorted by this key function. Parameters ---------- product_: tuple[st...
21bdae856ba3bd6cb7796a99fd679cdeb66d7183
673,844
import time def get_change_set_name(): """Return a valid Change Set Name. The name has to satisfy the following regex: [a-zA-Z][-a-zA-Z0-9]* And must be unique across all change sets. """ return 'change-set-{}'.format(int(time.time()))
a583fb2df4376a2c82a184ac4429f1fee983c788
673,845
def unquote(s): """remove quotation chars on both side. >>> unquote('"abc"') 'abc' >>> unquote("'abc'") 'abc' >>> unquote('abc') 'abc' """ if 2 <= len(s) and s[0] + s[-1] in ['""', "''"]: return s[1:-1] else: return s
550065b9d74cd75db499f9156714634d1a37d9a4
673,846
import os import sys import importlib def create_customized_class_instance(class_params): """Create instance of customized algorithms Parameters ---------- class_params: dict class_params should contains following keys: codeDir: code directory classFileName: python fil...
f93ac8a714e402acfe8931b3bdcae6a8990df0ec
673,848
def bb_data_to_coordinates(data): """ Get bb data as -> [x1,y1,h,w], compute coordinates as -> [x1, y1, x2, y2] """ x1 = data[0] y1 = data[1] x2 = data[0] + data[3] - 1 y2 = data[1] + data[2] - 1 return [x1,y1, x2, y2]
d02d6410be73b6cc322f697069c32c64bdce4ef5
673,849
def yyyy2yy(year): """ yy = yyyy2yy(YYYY) return the yy form of YYYY yy - last two digits of YYYY - returned as an int very messy hack """ yy = int( str(int(year))[-2] + str(int(year))[-1] ) return(yy)
5d41f2c0a9e7aa7454f334174bc61d2a254a223e
673,850
from datetime import datetime def as_datetime(value): """Converte uma sequência string para um objeto :class:`datetime.datetime`. Os espaços em branco das bordas da sequência serão removidos antes da conversão. :param str value: String contendo uma data/hora ANSI (``yyyymmddHHMMSS``) :rtype: date...
0aecf91e538e2876452b85f6bad0292bdc27e822
673,851
import subprocess import logging def _call_sub(args, outstd, outerr, cwd=None): """Call a subprocess. """ print("Executing %s" % " ".join(args)) # not pipe stdout - processes will hang # Known limitation of Popen proc = subprocess.Popen(args, cwd=cwd, stdout=outstd, stderr=outerr) proc.wa...
6da6fbb899e638e4d367c8680772737fa75b7937
673,853
def expand_nodes(batch_data, nodes, policies, values): """ Expand a batch of node based on policy logits acquired from the neural network. """ return_values = [] for i, node in enumerate(nodes): data = batch_data[i] game = data[0] state = data[1] player_1 = data[2...
b8cb75090d96dc7cba28bde9cf5b6569d17973d2
673,854
def case_insensitive_getter(from_array, value): """ When creating a Glue Table (either manually or via crawler) columns are automatically lower cased. If the column identifier is saved in the data mapper consistently to the glue table, the getter may not work when accessing the key directly inside t...
0a117b317940186e84c755b2f7992231930ca8ff
673,855
def read_dict(filename, div='='): """Read file into dict. A file containing: foo = bar baz = bog results in a dict { 'foo': 'bar', 'baz': 'bog' } Arguments: filename (str): path to file div (str): deviders between dict keys and values Ret...
26bc9ec287d8e338cd7a5fef3a9f0de49ebf6138
673,856
def chunk_tasks(n_tasks, n_batches, arr=None, args=None, start_idx=0): """Split the tasks into some number of batches to sent out to MPI workers. Parameters ---------- n_tasks : int The total number of tasks to divide. n_batches : int The number of batches to split the tasks into. Of...
1c4f33b68ef2e9e63de2600c89a110c7b3187bd5
673,857
import os def read_fd_decode_safely(fd, size=4096): """ This reads a utf-8 file descriptor and returns a chunck, growing up to three bytes if needed to decode the character at the end. Returns the data and the decoded text. """ data = os.read(fd.fileno(), size) for i in range(4): ...
c96eef12a60d30ac5fcfdb20ac20be740d77a0b9
673,859
import subprocess def call(cmd): """Calls a CLI command and returns the stdout as string.""" return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate()[0].decode('utf-8')
aeae991fc90a44a824557ae60073541fa3956c78
673,860