content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def confidence(output): """Compute a confidence score for NN output""" dim = output.shape[1] if dim != 2: raise NotImplementedError() return [abs(x[1] - 0.5) + abs(x[0] - 0.5) for x in output]
69879afa1c519c5ebc653640fdcdc4d9a1a9fa46
28,047
def cpu_roll_one(): """Reset round score to zero.""" print("Computer rolled a 1") print("round total set to 0. Other players turn!") return 0
30ffdc0ac93ae104e87856ad5a6f0fda76cf51a3
28,048
import time def calculate_time(func): """计算运行时间的装饰器""" def decorator(): start_time = time.time() # 开始计时 func() end_time = time.time() # 计时结束 print("Total Spend time:", str((end_time - start_time) / 60)[0:6] + "分钟") return decorator()
17d3adfd8c54dbe50232bb2568558e8a5648f23e
28,050
def get_V_fan_d_t(t_fan_d_t, V_fan_P0): """1時間当たりの空気搬送ファンの風量 (m3/h) (13) Args: t_fan_d_t(ndarray): 1時間当たりの空気搬送ファンの稼働時間 (h/h) V_fan_P0(float): 空気搬送ファンの送風機特性曲線において機外静圧をゼロとした時の空気搬送ファンの風量 (m3/h) Returns: ndarray: 1時間当たりの空気搬送ファンの風量 (m3/h) """ V_fan_d_t = V_fan_P0 * t_fan_d_t return V_fan_d_t
01d62dcdf4ca04ecd2fa6b70e3a3b7c9aec624dc
28,051
def sqrt(pop): """ Returns square root of length of list :param pop: List :return: Square root of size of list """ return len(pop) ** 0.5
877ae17cbe2cdd3a5f5b2cb03fc8d0b7af48c916
28,052
def complete(ans): """ :param ans: string :return: boolean """ for i in ans: if i == '-': return False return True
1cc423d2e532b25987f44c2dcd164192d548df07
28,053
def dict_subtract(d1, d2): """Subtract dictionary d1 from dictionary d2, to yield a new dictionary d.""" d = {} for key, val in d1.iteritems(): if key not in d2: d[key] = val return d
baf8db2b5c0ff4be7d61effad388f6d9e8edd5c3
28,054
import requests def __get_embedded_openload_url(url): """ url example: https://openloads.co/c2/m2ZUtv0ylvY/filename.mp4 """ url = url.replace(' ', '') embed_url = "https://openload.co/embed/{0}" try: media_id = url.split('/')[4] r = requests.get(embed_url.format(media_id)) if (r.status_code == 200): return embed_url.format(media_id) except: return False
2baaa1d8b44722af81562cdb447951530c9fadc0
28,055
import numpy def index_to_mask(x,n=100): """ Converts the list of indices x into a (nx1) boolean mask, true at those particular indices """ nrange=numpy.arange(n) boole = numpy.zeros(nrange.shape, dtype=bool) for xi in x: boole += nrange==xi return boole
da460820c38ceede2d1495c6186ffd1e8a6a7e6b
28,056
import re def is_hex_color(color: str) -> bool: """ Checks if a given color string is a valid hex color :param color: :return: """ match = re.search(r"^#(?:[0-9a-fA-F]{3}){1,2}$", color) if not match: return False return True
a86632883ccc05bc393b1b310c0fdf2eff559e55
28,057
import logging def get_logger(name): """ Retrieves a logger. :param name: The name of the logger :returns: The requested logger :rtype: logging.getLogger instance """ log = logging.getLogger(name) log.setLevel(logging.ERROR) return log
45d36a78d1a076123a93b3460774056685befc1e
28,058
def str2ascii_arr(name): """ 0-255 """ arr = [ord(c) for c in name] return arr, len(arr)
fd3917a052bc60166aad6ca2a1a4b19154eda108
28,059
def find_ranges_index(ranges, item): """Find the index where an entry *may* be.""" lo = 0 hi = len(ranges) while lo < hi: mid = (lo + hi) // 2 test = ranges[mid] try: test = test[1] except TypeError: pass if item > test: lo = mid + 1 else: hi = mid return lo
55815410b96a3591f8389880a3606d9849e4ce9d
28,060
def get_cls_db(db_name): """ Get benchmark dataset for classification """ if db_name.lower() == 'cls_davis': return './dataset/classification/DAVIS' elif db_name.lower() == 'cls_biosnap': return './dataset/classification/BIOSNAP/full_data' elif db_name.lower() == 'cls_bindingdb': return './dataset/classification/BindingDB'
89cf36b94299e4a4e1b2a4880ae1e891e37e77ac
28,061
import random def random_mac(): """Return a random Ethernet MAC address @link https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-2 """ head = "ca:fe:" hex_digits = '0123456789abcdef' tail = ':'.join([random.choice(hex_digits) + random.choice(hex_digits) for _ in range(4)]) return head + tail
0cace2b7928a9df1b0faea33e9df27b478c9eea7
28,063
import subprocess def env_run(env_path, command, *args, **kwargs): """ Run a command on the context of the virtual environment at the specified path. """ return subprocess.run([env_path/"bin"/command] + list(args), **kwargs).returncode == 0
ff34f0ee37ad2c4f9c171d3a27ccaa74b1ed4b7b
28,064
import pandas def timestamp2period(ts): """Get 6-hour period around timestamp Taking a timestamp, take the 6-hour period starting at the most recent analysis, containing the requested timestamp. That will be the period [ts.hour//6, ts.hour//6+6]. Args: ts: pandas.Timestamp """ return pandas.Period(ts.floor("6H"), "6H")
622cb45693c9a9261afbea0cddf432db0a14cb59
28,065
import sys def getPythonContainers(meth): """Walk up the Python tree from method 'meth', finding its class, its module and all containing packages.""" containers = [] containers.append(meth.im_class) moduleName = meth.im_class.__module__ while moduleName is not None: module = sys.modules.get(moduleName, None) if module is None: module = __import__(moduleName) containers.append(module) moduleName = getattr(module, '__module__', None) return containers
ec5e5563ecf2905b7c037d966bde8f4f7239bcdf
28,066
def remap_CIELab(image): """ INPUT: image: the image to be remapped. The input colorspace should be CIELab image.shape=(image_x, image_y, 3) OUTPUT: an image where the L a and b layers are scaled to be between 0 and 1 for most frequently used colors. they could however be beyond the scale! (this colorspace is called CIEL*a*b* from now on) """ # Normalize image so that all layers are between 0 - 1 (this is to fit the hole rgb part of the LAB space in a unit-cube) # Max(L) = 99.6549222328 # Max(a) = 97.9408293554 # Max(b) = 94.1970679706 # Min(L) = 0.0 # Min(a) = -85.9266517489 # Min(b) = -107.536445411 # White: # L = 1.00000000e+02 # a = -2.45493786e-03 ~ 0 # b = 4.65342115e-03 ~ 0 # Black: # L = 0 # a = 0 # b = 0 # Keep aspectratio constant between a and b layers, so devide both a and b by 108, and recenter around 0.5: image[:,:,0] /= 100. image[:,:,1] = (image[:,:,1] + 108.) / (2.*108) # take the same subset as for the b values, so the colors wont be skewed image[:,:,2] = (image[:,:,2] + 108.) / (2.*108) # Normalize all b values return image
4ee5bed4763dce56f757e686b4416ce43f01afa4
28,067
import pathlib def get_file_size(file_path): """ Returns file size """ file = pathlib.Path(file_path) return file.stat().st_size
aa90923cd117b2b96a76c8d29d6218e3a577d5df
28,069
import os def os_specific_env(env_var_name): """ Gets the operating system specific environment variable format string. :param env_var_name: Environment variable name. :type env_var_name: str """ current_os = os.environ["TEMPLATE_OS"] if current_os.lower() == "linux": return "${}".format(env_var_name) else: return "%{}%".format(env_var_name)
fc32fcc2d2af81d9cd1f53330368ba7f58a5ee3b
28,070
import pandas def df_getitem_tuple_at_codegen(self, row, col): """ Example of generated implementation: def _df_getitem_tuple_at_impl(self, idx): row, _ = idx data = self._dataframe._data[1][0] res_data = pandas.Series(data, index=self._dataframe.index) return res_data.at[row] """ func_lines = ['def _df_getitem_tuple_at_impl(self, idx):', ' row, _ = idx'] check = False for i in range(len(self.columns)): if self.columns[i] == col: col_loc = self.column_loc[col] type_id, col_id = col_loc.type_id, col_loc.col_id check = True func_lines += [ f' data = self._dataframe._data[{type_id}][{col_id}]', f' res_data = pandas.Series(data, index=self._dataframe.index)', ' return res_data.at[row]', ] if check == False: # noqa raise KeyError('Column is not in the DataFrame') func_text = '\n'.join(func_lines) global_vars = {'pandas': pandas} return func_text, global_vars
c785a9ce7a8879df43945dfb4224d7f897261cb4
28,072
import math def deRuiter_radius(src1, src2): """Calculates the De Ruiter radius for two sources""" # The errors are the square root of the quadratic sum of # the systematic and fitted errors. src1_ew_uncertainty = math.sqrt(src1.ew_sys_err**2 + src1.error_radius**2) / 3600. src1_ns_uncertainty = math.sqrt(src1.ns_sys_err**2 + src1.error_radius**2) / 3600. src2_ew_uncertainty = math.sqrt(src2.ew_sys_err**2 + src2.error_radius**2) / 3600. src2_ns_uncertainty = math.sqrt(src2.ns_sys_err**2 + src2.error_radius**2) / 3600. ra_nom = ((src1.ra - src2.ra) * math.cos(math.radians(0.5 * (src1.dec + src2.dec))))**2 ra_denom = src1_ew_uncertainty**2 + src2_ew_uncertainty**2 ra_fac = ra_nom / ra_denom dec_nom = (src1.dec - src2.dec)**2 dec_denom = src1_ns_uncertainty**2 + src2_ns_uncertainty**2 dec_fac = dec_nom / dec_denom dr = math.sqrt(ra_fac + dec_fac) return dr
55c7f174b61c249427f09cec3c885c049f1d38dc
28,075
import logging def get_job_source_code_hashes(self, job_info, provider, job_key, index, job_id=0, received_block_number=None): """Source_code_hashes of the completed job is obtained from its event.""" if received_block_number is None: received_block_number = self.get_deployed_block_number() to_block = "latest" else: to_block = int(received_block_number) try: event_filter = self._eBlocBroker.events.LogJob.createFilter( fromBlock=int(received_block_number), toBlock=to_block, argument_filters={"provider": str(provider)}, ) logged_jobs = event_filter.get_all_entries() for logged_job in logged_jobs: if logged_job.args["jobKey"] == job_key and logged_job.args["index"] == int(index): job_info.update({"source_code_hash": logged_job.args["sourceCodeHash"]}) return job_info except Exception as e: logging.error(f"E: Failed to get_Job_source_code_hash: {e}") raise
d38f02e328500853180f1d50d7629cd5e1be8328
28,076
from typing import Dict def extract_method_arguments(line: str) -> Dict[str, str]: """Read method arguments from text""" # Use the method call to break the string arguments_str = line.split("(")[1].split(")")[0] if not arguments_str: return {} args = {} for entry in arguments_str.split(","): type_, argname = entry.strip().split() args[argname.strip()] = type_.strip() return args
9f3ca90775933b2b32549d7bf12f5c407181bd2d
28,079
def twitterMatrix(db, query): """Run a Cypher query that returns pairs of Twitter screen_names lists of others to which they are linked.""" def matrix_query_as_list(tx): return list(tx.run(query)) with db.session() as session: result = session.read_transaction(matrix_query_as_list) screen_names = [record[0] for record in result if record[0]] name_set = set(screen_names) def get_row(row): row_names = set(result[row][1]).intersection(name_set) return [float(1 & (i in row_names)) for i in screen_names] return screen_names, [get_row(i) for i in range(len(screen_names))]
ceab8245b976a09362f97b7bcb0eb2ac1463e0d8
28,080
def flatten(list_of_lists): """List[List[X]] -> List[X]""" return sum(list_of_lists, [])
8f75134151897bcb58eb5524a40ad2dd515ee49a
28,081
def regions_to_compound_region(regions): """Create compound region from list of regions, by creating the union. Parameters ---------- regions : `~regions.Regions` List of regions. Returns ------- compound : `~regions.CompoundSkyRegion` or `~regions.CompoundPixelRegion` Compound sky region """ region_union = regions[0] for region in regions[1:]: region_union = region_union.union(region) return region_union
51c0844c30b0ec32f547e6922bf22508e8f066cf
28,082
def fix_data(text): """Add BOS and EOS markers to sentence.""" if "<s>" in text and "</s>" in text: # This hopes that the text has been correct pre-processed return text sentences = text.split("\n") # Removing any blank sentences data sentences = ["<s> " + s + " </s>" for s in sentences if len(s.strip()) > 0] return " ".join(sentences)
b502784e9e8fa8875030730595dcaaae66e2f31b
28,083
import base64 def b64_encode(value: bytes) -> bytes: """ URL safe base 64 encoding of a value :param value: bytes :return: bytes """ return base64.urlsafe_b64encode(value).strip(b"=")
40a7dfbec7ec390a71cdacc5ab54ce8e2a092754
28,084
import subprocess def safe_subprocess(command_array): """Executes shell command. Do not raise Args: command_array (list): ideally an array of string elements, but may be a string. Will be converted to an array of strings Returns: bool, str: True/False (command succeeded), command output """ try: # Ensure all args are strings if isinstance(command_array, list): command_array_str = [str(x) for x in command_array] else: command_array_str = [str(command_array)] return True, subprocess.check_output(command_array_str, stderr=subprocess.STDOUT) except OSError as ex: return False, ex.__str__() except subprocess.CalledProcessError as ex: return False, ex.output
fa7d6b0c1045f865bc3c888f8f751507120f86a9
28,087
def _get_tap(baseVal, powerVal): """Retrieve pre-defined list of tap sequences for a given base & power, or raise ValueError. """ if not baseVal in [2,3,5,9]: raise ValueError('baseVal must be in [2,3,5,9], not %s' % str(baseVal)) tap = [] if baseVal == 2: if powerVal == 2: tap = [[1,2]] elif powerVal == 3: tap = [[1,3], [2,3]] elif powerVal == 4: tap = [[1,4], [3,4]] elif powerVal == 5: tap = [[2,5], [3,5], [1,2,3,5], [2,3,4,5], [1,2,4,5], [1,3,4,5]] elif powerVal == 6: tap = [[1,6], [5,6], [1,2,5,6], [1,4,5,6], [1,3,4,6], [2,3,5,6]] elif powerVal == 7: tap = [[1,7], [6,7], [3,7], [4,7], [1,2,3,7], [4,5,6,7], [1,2,5,7], [2,5,6,7], [2,3,4,7], [3,4,5,7], [1,3,5,7], [2,4,6,7], [1,3,6,7], [1,4,6,7], [2,3,4,5,6,7], [1,2,3,4,5,7], [1,2,4,5,6,7], [1,2,3,5,6,7] ] elif powerVal == 8: tap = [[1,2,7,8], [1,6,7,8], [1,3,5,8], [3,5,7,8], [2,3,4,8], [4,5,6,8], [2,3,5,8], [3,5,6,8], [2,3,6,8], [2,5,6,8], [2,3,7,8], [1,5,6,8], [1,2,3,4,6,8], [2,4,5,6,7,8], [1,2,3,6,7,8], [1,2,5,6,7,8] ] elif powerVal == 9: tap = [[4,9], [5,9], [3,4,6,9], [3,5,6,9], [4,5,8,9], [1,4,5,9], [1,4,8,9], [1,5,8,9], [2,3,5,9], [4,6,7,9], [5,6,8,9], [1,3,4,9], [2,7,8,9], [1,2,7,9], [2,4,7,9], [2,5,7,9], [2,4,8,9], [1,5,7,9], [1,2,4,5,6,9], [3,4,5,7,8,9], [1,3,4,6,7,9], [2,3,5,6,8,9], [3,5,6,7,8,9], [1,2,3,4,6,9], [1,5,6,7,8,9], [1,2,3,4,8,9], [1,2,3,7,8,9], [1,2,6,7,8,9], [1,3,5,6,8,9], [1,3,4,6,8,9], [1,2,3,5,6,9], [3,4,6,7,8,9], [2,3,6,7,8,9], [1,2,3,6,7,9], [1,4,5,6,8,9], [1,3,4,5,8,9], [1,3,6,7,8,9], [1,2,3,6,8,9], [2,3,4,5,6,9], [3,4,5,6,7,9], [2,4,6,7,8,9], [1,2,3,5,7,9], [2,3,4,5,7,9], [2,4,5,6,7,9], [1,2,4,5,7,9], [2,4,5,6,7,9], [1,3,4,5,6,7,8,9], [1,2,3,4,5,6,8,9] ] elif powerVal == 10: tap = [[3,10], [7,10], [2,3,8,10], [2,7,8,10], [1,3,4,10], [6,7,9,10], [1,5,8,10], [2,5,9,10], [4,5,8,10], [2,5,6,10], [1,4,9,10], [1,6,9,10], [3,4,8,10], [2,6,7,10], [2,3,5,10], [5,7,8,10], [1,2,5,10], [5,8,9,10], [2,4,9,10], [1,6,8,10], [3,7,9,10], [1,3,7,10], [1,2,3,5,6,10], [4,5,7,8,9,10], [2,3,6,8,9,10], [1,2,4,7,8,10], [1,5,6,8,9,10], [1,2,4,5,9,10], [2,5,6,7,8,10], [2,3,4,5,8,10], [2,4,6,8,9,10], [1,2,4,6,8,10], [1,2,3,7,8,10], [2,3,7,8,9,10], [3,4,5,8,9,10], [1,2,5,6,7,10], [1,4,6,7,9,10], [1,3,4,6,9,10], [1,2,6,8,9,10], [1,2,4,8,9,10], [1,4,7,8,9,10], [1,2,3,6,9,10], [1,2,6,7,8,10], [2,3,4,8,9,10], [1,2,4,6,7,10], [3,4,6,8,9,10], [2,4,5,7,9,10], [1,3,5,6,8,10], [3,4,5,6,9,10], [1,4,5,6,7,10], [1,3,4,5,6,7,8,10], [2,3,4,5,6,7,9,10], [3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,10], [1,2,3,4,5,6,9,10], [1,4,5,6,7,8,9,10], [2,3,4,5,6,8,9,10], [1,2,4,5,6,7,8,10], [1,2,3,4,6,7,9,10], [1,3,4,6,7,8,9,10]] elif powerVal == 11: tap = [[9,11]] elif powerVal == 12: tap = [[6,8,11,12]] elif powerVal == 13: tap = [[9,10,12,13]] elif powerVal == 14: tap = [[4,8,13,14]] elif powerVal == 15: tap = [[14,15]] elif powerVal == 16: tap = [[4,13,15,16]] elif powerVal == 17: tap = [[14,17]] elif powerVal == 18: tap = [[11,18]] elif powerVal == 19: tap = [[14,17,18,19]] elif powerVal == 20: tap = [[17,20]] elif powerVal == 21: tap = [[19,21]] elif powerVal == 22: tap = [[21,22]] elif powerVal == 23: tap = [[18,23]] elif powerVal == 24: tap = [[17,22,23,24]] elif powerVal == 25: tap = [[22,25]] elif powerVal == 26: tap = [[20,24,25,26]] elif powerVal == 27: tap = [[22,25,26,27]] elif powerVal == 28: tap = [[25,28]] elif powerVal == 29: tap = [[27,29]] elif powerVal == 30: tap = [[7,28,29,30]] elif baseVal == 3: if powerVal == 2: tap = [[2,1], [1,1]] elif powerVal == 3: tap = [[0,1,2], [1,0,2], [1,2,2], [2,1,2]] elif powerVal == 4: tap = [[0,0,2,1], [0,0,1,1], [2,0,0,1], [2,2,1,1], [2,1,1,1], [1,0,0,1], [1,2,2,1], [1,1,2,1] ] elif powerVal == 5: tap = [[0,0,0,1,2], [0,0,0,1,2], [0,0,1,2,2], [0,2,1,0,2], [0,2,1,1,2], [0,1,2,0,2], [0,1,1,2,2], [2,0,0,1,2], [2,0,2,0,2], [2,0,2,2,2], [2,2,0,2,2], [2,2,2,1,2], [2,2,1,2,2], [2,1,2,2,2], [2,1,1,0,2], [1,0,0,0,2], [1,0,0,2,2], [1,0,1,1,2], [1,2,2,2,2], [1,1,0,1,2], [1,1,2,0,2]] elif powerVal == 6: tap = [[0,0,0,0,2,1], [0,0,0,0,1,1], [0,0,2,0,2,1], [0,0,1,0,1,1], [0,2,0,1,2,1], [0,2,0,1,1,1], [0,2,2,0,1,1], [0,2,2,2,1,1], [2,1,1,1,0,1], [1,0,0,0,0,1], [1,0,2,1,0,1], [1,0,1,0,0,1], [1,0,1,2,1,1], [1,0,1,1,1,1], [1,2,0,2,2,1], [1,2,0,1,0,1], [1,2,2,1,2,1], [1,2,1,0,1,1], [1,2,1,2,1,1], [1,2,1,1,2,1], [1,1,2,1,0,1], [1,1,1,0,1,1], [1,1,1,2,0,1], [1,1,1,1,1,1] ] elif powerVal == 7: tap = [[0,0,0,0,2,1,2], [0,0,0,0,1,0,2], [0,0,0,2,0,2,2], [0,0,0,2,2,2,2], [0,0,0,2,1,0,2], [0,0,0,1,1,2,2], [0,0,0,1,1,1,2], [0,0,2,2,2,0,2], [0,0,2,2,1,2,2], [0,0,2,1,0,0,2], [0,0,2,1,2,2,2], [0,0,1,0,2,1,2], [0,0,1,0,1,1,2], [0,0,1,1,0,1,2], [0,0,1,1,2,0,2], [0,2,0,0,0,2,2], [0,2,0,0,1,0,2], [0,2,0,0,1,1,2], [0,2,0,2,2,0,2], [0,2,0,2,1,2,2], [0,2,0,1,1,0,2], [0,2,2,0,2,0,2], [0,2,2,0,1,2,2], [0,2,2,2,2,1,2], [0,2,2,2,1,0,2], [0,2,2,1,0,1,2], [0,2,2,1,2,2,2] ] elif baseVal == 5: if powerVal == 2: tap = [[4,3], [3,2], [2,2], [1,3]] elif powerVal == 3: tap = [[0,2,3], [4,1,2], [3,0,2], [3,4,2], [3,3,3], [3,3,2], [3,1,3], [2,0,3], [2,4,3], [2,3,3], [2,3,2], [2,1,2], [1,0,2], [1,4,3], [1,1,3]] elif powerVal == 4: tap = [[0,4,3,3], [0,4,3,2], [0,4,2,3], [0,4,2,2], [0,1,4,3], [0,1,4,2], [0,1,1,3], [0,1,1,2], [4,0,4,2], [4,0,3,2], [4,0,2,3], [4,0,1,3], [4,4,4,2], [4,3,0,3], [4,3,4,3], [4,2,0,2], [4,2,1,3], [4,1,1,2], [3,0,4,2], [3,0,3,3], [3,0,2,2], [3,0,1,3], [3,4,3,2], [3,3,0,2], [3,3,3,3], [3,2,0,3], [3,2,2,3], [3,1,2,2], [2,0,4,3], [2,0,3,2], [2,0,2,3], [2,0,1,2], [2,4,2,2], [2,3,0,2], [2,3,2,3], [2,2,0,3], [2,2,3,3], [2,1,3,2], [1,0,4,3], [1,0,3,3], [1,0,2,2], [1,0,1,2], [1,4,1,2], [1,3,0,3], [1,3,1,3], [1,2,0,2], [1,2,4,3], [1,1,4,2]] elif baseVal == 9: if powerVal == 2: tap = [[1,1]] if not tap: raise ValueError('M-sequence %.0f^%.0f is not defined by this function' % (baseVal, powerVal)) return tap
dc40edf1a09d5ad7fa76945a31b13570eacddb64
28,088
def comment_scalar(a_dict, key): """Comment out a scalar in a ConfigObj object. Convert an entry into a comment, sticking it at the beginning of the section. Returns: 0 if nothing was done. 1 if the ConfigObj object was changed. """ # If the key is not in the list of scalars there is no need to do anything. if key not in a_dict.scalars: return 0 # Save the old comments comment = a_dict.comments[key] inline_comment = a_dict.inline_comments[key] if inline_comment is None: inline_comment = '' # Build a new inline comment holding the key and value, as well as the old inline comment new_inline_comment = "%s = %s %s" % (key, a_dict[key], inline_comment) # Delete the old key del a_dict[key] # If that was the only key, there's no place to put the comments. Do nothing. if len(a_dict.scalars): # Otherwise, put the comments before the first entry first_key = a_dict.scalars[0] a_dict.comments[first_key] += comment a_dict.comments[first_key].append(new_inline_comment) return 1
f2121caa4e58ec88527ae128a0ac9669efa066d7
28,089
from datetime import datetime def xml2date(s): """Convert XML time string to python datetime object""" return datetime.strptime(s[:22]+s[23:], '%Y-%m-%dT%H:%M:%S%z')
762480533d8e64544b4b4c4c67093098dcfebb56
28,091
import numpy def _find_next_batch( example_to_file_indices, num_examples_per_batch, next_example_index): """Determines which examples are in the next batch. E = total number of examples :param example_to_file_indices: length-E numpy array of indices. If example_to_file_indices[i] = j, the [i]th example comes from the [j]th file. :param num_examples_per_batch: Number of examples per batch. :param next_example_index: Index of next example to be used. :return: batch_indices: 1-D numpy array with indices of examples in the next batch. """ num_examples = len(example_to_file_indices) if next_example_index >= num_examples: return None first_index = next_example_index last_index = min([ first_index + num_examples_per_batch - 1, num_examples - 1 ]) batch_indices = numpy.linspace( first_index, last_index, num=last_index - first_index + 1, dtype=int ) file_index = example_to_file_indices[next_example_index] subindices = numpy.where( example_to_file_indices[batch_indices] == file_index )[0] batch_indices = batch_indices[subindices] if len(batch_indices) == 0: batch_indices = None return batch_indices
8a38521630cb701cb695a06aa8db697fd8307525
28,095
def rivers_with_stations(stations): """Returns a set with the names of any rivers with a monitoring station""" counter = 0 valid_rivers = set() while counter < len(stations): valid_rivers.add(stations[counter].river) counter += 1 if counter > 200000: break else: pass return valid_rivers
2003b12a875cd34b6faa85f564da56dff679dc99
28,096
def min(x, y): """Minimum""" return min(x, y)
8c6b242ae050cd1e80102677a043735fdf05be34
28,097
import os def _absolute_template_path(fn): """ Return absolute path for filename from local ``xslt/`` directory. Args: fn (str): Filename. ``MARC21slim2MODS3-4-NDK.xsl`` for example. Returns: str: Absolute path to `fn` in ``xslt`` dicretory.. """ return os.path.join(os.path.dirname(__file__), "xslt", fn)
ef9c46fe965cbf5e37ca66c186e4fcc44c004df8
28,098
def solution(ar): """ Return exactly once :param ar: :return: """ xor_sum = 0 # xor cancels the same elements ie. 2 xor 2 = 0 for item in ar: xor_sum = xor_sum ^ item return xor_sum
f0370136ba87fed1b8d40ece176e23257c7757b8
28,099
import re def format_header ( parsed_args ): """ parse the RVDB formatted FASTA headers and re-writes in desired format """ accessions = [] with open (parsed_args.inputFASTA) as infile: reader = infile.readlines() try: with open (parsed_args.output, 'w') as outfile: for line in reader: if re.search('^>',line): newline = line.split('|')[2:] newline = '>gb|'+'|'.join(newline) accessions.append(newline[0]) outfile.writelines(newline) else: outfile.writelines(line) except: outfile = 'HIVE_'+parsed_args.inputFASTA with open (outfile, 'w') as outfile: for line in reader: if re.search('^>',line): newline = line.split('|')[2:] accessions.append(newline[0]) newline = '>gb|'+'|'.join(newline) outfile.writelines(newline) else: outfile.writelines(line) return accessions
cdc10767f36166f73e30e2c0b342db5ef8d524ec
28,100
import os def take_checkpoint(root): """ Calls the perforce server and takes a snapshot """ cmd = 'p4d -r %s -z -jc' % root ret = os.system(cmd) if ret == 0: return True return False
a7c022c9b240d60b800c1ec75b5741a6a11c12f1
28,102
def atom2dict(atom, dictionary=None): """Get a dictionary of one of a structure's :class:`diffpy.structure.Structure.atoms` content. Only values necessary to initialize an atom object are returned. Parameters ---------- atom : diffpy.structure.Structure.atom Atom in a structure. dictionary : dict, optional Dictionary to update with structure atom information. If None (default), a new dictionary is created. Returns ------- dictionary : dict Dictionary with structure atoms information. """ if dictionary is None: dictionary = {} dictionary.update( { attribute: atom.__getattribute__(attribute) for attribute in ["element", "label", "occupancy", "xyz", "U"] } ) return dictionary
6873c64bd39d211a43f302375d6a6c76e3bd0b7e
28,103
def get_connectivity(input_nodes): """Create a description of the connections of each node in the graph. Recurrent connections (i.e. connections of a node with itself) are excluded. Args: input_nodes (:obj:`list` of :obj:`Node`): the input operations of the model. Returns: graph (:obj:`dict` of :obj:`dict` of :obj:`set`): a description of the graph's connectivity in terms of inbound-outbound nodes of each node. """ graph = dict() nodes = input_nodes.copy() while len(nodes) != 0: # select a node current_node = nodes.pop(0) # if no information has been collected yet, set up dict entry if current_node not in graph: graph[current_node] = {'inbound': set(), 'outbound': set()} # scroll through current node's outbound nodes for node in current_node.outbound_nodes: # skip recurrent connections (for RNN cells) if node == current_node: continue # if no information has been collected yet, set up dict entry if node not in graph: nodes.append(node) graph[node] = {'inbound': set(), 'outbound': set()} # add reciprocal connectivity information graph[current_node]['outbound'].add(node) graph[node]['inbound'].add(current_node) return graph
ea14ff70f4c821744079219a2ec3ee50acc0483b
28,104
def get_message_with_context(msg: str, context: str) -> str: """ Concatenates an error message with a context. If context is empty string, will only return the error message. :param msg: the message :param context: the context of the message :return: the message with context """ if len(context) == 0: return msg else: msg = "\t" + "\n\t".join(msg.splitlines()) return "%s\n%s" % (context, msg)
8d625b297ba4510fdef3476138bafd1e210fcaa6
28,105
def get_default_keras_loss_names(): """ Get the default available losses from Keras and return them as list of strings. :return: """ return ['categorical_crossentropy']
a26d5f8042d4728db36fa97fe838cd5437415bf8
28,106
def mean(array, axis=0): """Calculates standard error.""" return array.mean(axis=axis) if len(array) > 0 else 0.0
5ea0fe92b1a882a47d8418574978bf6adc592748
28,107
def unique(list1, list2): """Get the unique items that are in the first list but not in the second list. NOTE: unique(l1,l2) is not always equal to unique(l2,l1) Args: list1 (list): A list of elements. list2 (list): A list of elements. Returns: list: A list with the unique elements. Examples: >>> unique([1,2,3], [2,3,4]) [1] >>> unique([2,3,4], [1,2,3]) [4] """ return list(set(list1) - set(list2))
9e870319287ef7296cb5f54dc1089dc676ecc553
28,109
def all_belong(candidates,checklist): """Check whether a list of items ALL appear in a given list of options. Returns a single 1 or 0 value.""" return 1-(0 in [x in checklist for x in candidates])
05aca77653dad3cd8221a66f45493aa53cb93654
28,110
from six import PY2 import sys def write_bytes_to_stdout(b): """Write bytes (python 3) or string (python 2) to stdout.""" if PY2: return sys.stdout.write(b) else: return sys.stdout.buffer.write(b)
533d4c7f55adf890269334dd52bfc8e787d6aae4
28,111
def get_classes(module, superclass=None): """ Return a list of new-style classes defined in *module*, excluding _private and __magic__ names, and optionally filtering only those inheriting from *superclass*. Note that both arguments are actual modules, not names. This method only returns classes that were defined in *module*. Those imported from elsewhere are ignored. """ objects = [ getattr(module, name) for name in dir(module) if not name.startswith("_")] # filter out everything that isn't a new-style # class, or wasn't defined in *module* (ie, it # is imported from somewhere else) classes = [ obj for obj in objects if isinstance(obj, type) and (obj.__module__ == module.__name__) ] # if a superclass was given, filter the classes # again to remove those that aren't its subclass if superclass is not None: classes = [ cls for cls in classes if issubclass(cls, superclass)] return classes
9b31c7179a29b148e8e7503fa8bc06282e1248b4
28,112
from hashlib import md5 as _md5 def get_filesize_and_checksum(filename): """Opens the file with the passed filename and calculates its size and md5 hash Args: filename (str): filename to calculate size and checksum for Returns: tuple (int,str): size of data and its md5 hash """ md5 = _md5() size = 0 with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): md5.update(chunk) size += len(chunk) return (size, str(md5.hexdigest()))
b8e1c0dc6bcb9785d2c6f47dbebe6ccedf18b1af
28,113
def to_datetimepicker_format(python_format_string): """ Given a python datetime format string, attempts to convert it to the nearest PHP datetime format string possible. """ python2PHP = { "%a": "D", "%A": "l", "%b": "M", "%B": "F", "%c": "", "%d": "d", "%H": "H", "%I": "h", "%j": "z", "%m": "m", "%M": "i", "%p": "A", "%S": "s", "%U": "", "%w": "w", "%W": "W", "%x": "", "%X": "", "%y": "y", "%Y": "Y", "%Z": "e", } php_format_string = python_format_string for py, php in python2PHP.items(): php_format_string = php_format_string.replace(py, php) return php_format_string
525563b4857e8cedb90c4180ee959b2c408ac92c
28,115
import os def _image_file_path(instance, filename): """Returns the subfolder in which to upload images for articles. This results in media/article/img/<filename>""" return os.path.join( 'article', str(instance.article.pk), 'images', filename )
f917666d7704f005e776ca75ecb296c5b1508be4
28,116
def getNameToIdDict(tree): """Get a mapping from name to id for an nxtree. Will be invalid if changes are made to the tree. """ ret = {} for id in tree.postOrderTraversal(): if tree.hasName(id): ret[tree.getName(id)] = id return ret
a94f6f9a90c1874c3f07f20e2e096929c923b60e
28,117
def get_boundary(): """ Before I used: boundary = mimetools.choose_boundary() But that returned some "private" information: '127.0.0.1.1000.6267.1173556103.828.1' Now I simply return a fixed string which I generated once and now re-use all the time. There is a reason for having a fixed boundary! When comparing two fuzzable requests it's easier to do it if the boundaries are static. This allows get_request_hash() to work as expected. The problem with fixed boundaries is that they might be used to fingerprint w3af, or that they might appear in the data we send to the wire and break the request. :return: """ return 'b08c02-53d780-e2bc43-1d5278-a3c0d9-a5c0d9'
82c70fe3b03de09f654aebe80691d235fadba4d0
28,118
def rebase(input_base, digits, output_base): """ Change digits of a number from input base to output base """ if input_base < 2: raise ValueError("input base must be >= 2") if any(map(lambda x: x < 0 or x >= input_base, digits)): raise ValueError("all digits must satisfy 0 <= d < input base") if output_base < 2: raise ValueError("output base must be >= 2") base10 = 0 for index, digit in enumerate(digits[::-1]): base10 += digit * input_base ** index result = [] while base10 != 0: result.append(base10 % output_base) base10 //= output_base return result[::-1] if result else [0]
8a242dae905559e8048cfb92e053bae5a8dde596
28,119
import json def parse_json(s, **kwargs): """ Wrapper to read JSON, stubbed for now """ return json.loads(s, **kwargs)
1e22fcfbb8d2b6a61d74f5cf2f2ea4fb537bf21b
28,120
import random def generator_random_email(): """生成随机的10位数邮箱 :return: Examples: | ${email} | Generator Random Email | => | ${email} = 45tghmju79@email.com """ char_num = [a for a in range(0, 10)] char_lower_case = list('abcdefghijklmnopqrstuvwxyz') char_capital = list('abcdefghijklmnopqrstuvwxyz'.upper()) char_list = char_num + char_lower_case + char_capital email_first = '' for i in range(0, 10): random_index = random.randint(0, len(char_list) - 1) email_first += str(char_list[random_index]) email_second_list = ['@qq.com', '@mo9.com', '@gmail.com', '@163.com'] email_second = email_second_list[random.randint(0, len(email_second_list) - 1)] email = email_first + email_second return email
8d0ec38d614f67c06ce200afc88e6286d5ba82cd
28,121
def rotate_convert(value) -> int: """ :param value:midi values: 1-63 plus 65-127 minus :return: value to add """ if value & 64: return -(value - 64) else: return value
435048382ded63201da93654d4ab679534cd75f6
28,122
def convert_string(data_to_convert): """ Parse ASCII string from byte array :param data_to_convert: Input byte array :return: Parsed string """ return data_to_convert[2:].decode('hex')
3bd234db7793d9d694e6c40f74f1acfcc09ca60f
28,125
import os import sqlite3 def get_properties(elt): """ Retrieve properties of an element such as its density, lattice constant, etc. as a dictionary If no information is found in the database then at least Element, Z and mass will be returned Examples -------- > get_properties("C") {'Element': 'C', 'Z': 6, 'mass': 12.010735896764459} > get_properties("Si") {'Element': 'Si', 'Q': 0.78, 'Z': 14, 'density': 5e+22, 'ion_nrj': 8.15, 'lattice_const': 5.431, 'lattice_type': 'diamond_fcc', 'mass': 28.085498706418875, 'sublim_nrj': 4.63, 'work_func': 4.85} """ DB_PATH = os.path.join(os.path.abspath(os.path.join(__file__,"../..")),"data", "elements.db") conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute("SELECT * from properties where Element='{}'".format(elt)) res = c.fetchone() r = {} if res: for idx, col in enumerate(c.description): r[col[0]] = res[idx] else: res = c.execute("SELECT mass,abund,symbol,Z from elements where symbol='{}'".format(elt)) if res: row = res.fetchall() r['Element'] = row[0][2] r['Z'] = row[0][3] r['mass'] = sum([x[0]*x[1] for x in row]) return r
8e820aa22f501437bd4a6fd8115ca4245ef70d76
28,128
def exception_str(exc): """Call this to get the exception string associated with the given exception or tuple of the form (exc, traceback) or (exc_class, exc, traceback). """ if isinstance(exc, tuple) and len(exc) == 3: return str(exc[1]) return str(exc)
eb3729cc49a5e346fbd9c064f2fe0fc4ef4bd2c2
28,129
def sanityCheck(url): """ Checks for a valid url pattern, and returns True if valid, False otherwise url: string valid: boolean """ splitted_url = url.split('/') valid = False try: if splitted_url[0] == "https:" and splitted_url[1] == "" and splitted_url[2] == "github.com" and splitted_url[4].split('.')[1] == "git": valid = True except: pass return valid
21fc0fe52803ad010a0c5ca06aa3dfe750df4518
28,130
def xidz(numerator, denominator, value_if_denom_is_zero): """ Implements Vensim's XIDZ function. This function executes a division, robust to denominator being zero. In the case of zero denominator, the final argument is returned. Parameters ---------- numerator: float denominator: float Components of the division operation value_if_denom_is_zero: float The value to return if the denominator is zero Returns ------- numerator / denominator if denominator > 1e-6 otherwise, returns value_if_denom_is_zero """ small = 1e-6 # What is considered zero according to Vensim Help if abs(denominator) < small: return value_if_denom_is_zero else: return numerator * 1.0 / denominator
45782f957c56a0f91528d6d945c5d7887fd68e95
28,131
def mock_exists(file_map, fn): """ mock os.path.exists() """ return (fn in file_map)
f68741c4bd4da3e5f4d32dce1ef9c249495c8f5a
28,132
def linear_function(x,m,b): """ Get the y value of a linear function given the x value. Args: m (float): the slope b (float): the intercept Returns: The expected y value from a linear function at some specified x value. """ return m*x + b
929882eb3f3e4b0767458c63ed17ca67fc6ab17f
28,133
def pp_timestamp(t): """ Get a friendly timestamp represented as a string. """ if t is None: return '' h, m, s = int(t / 3600), int(t / 60 % 60), t % 60 return "%02d:%02d:%05.2f" % (h, m, s)
d1766cabcff9f09c145d98536900e9a82e734f63
28,139
import numpy def pt2numpy(pt): """Translate WKT Raster pixel type to NumPy data type""" numpytypes = { '8BUI' : numpy.uint8, '16BSI' : numpy.int16, '16BUI' : numpy.uint16, '32BSI' : numpy.int32, '32BUI' : numpy.uint32, '32BF' : numpy.float32, '64BF' : numpy.float64 } return numpytypes.get(pt, numpy.uint8)
ec5dad598da7ac2604dda7bf7e9cf2842006e493
28,140
def remove_hook_words(text, hook_words): """ removes hook words from text with one next word for text = "a b c d e f" and hook_words = ['b', 'e'] returns "a d" (without b, e and next words) """ words = text.split() answer = [] k = 0 while k < len(words): if words[k] in hook_words: k += 2 else: answer.append(words[k]) k += 1 return ' '.join(answer)
aaa1706fe7d9322d900ef346f3189824d06f8df2
28,142
def Farm_Loc(player): """farm location function""" player.coins += 3 return (player)
849e452774ea2446d4c6972044c1d6c2777b6554
28,144
def simdata2obsconditions(sim): """Pack simdata observation conditions into a dictionary. Parameters ---------- simdata : Table Simulation data table. Returns ------- obs : dict Observation conditions dictionary. """ obs = dict(AIRMASS=sim.airmass, EXPTIME=sim.exptime, MOONALT=sim.moonalt, MOONFRAC=sim.moonfrac, MOONSEP=sim.moonsep, SEEING=sim.seeing) return obs
3a3d5ab351842d53e5c753b83f09ac68de1a9b55
28,145
import socket def get_real_ip(): """ Attempts to get the IP address that's used for interesting things. """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("8.8.8.8", 53)) except: return False ip_address = s.getsockname()[0] first_octet = ip_address.split('.') if first_octet != '127' and first_octet != '169': return ip_address else: return False
56de5f9fa00a083fc1682f70d500486c99147aad
28,146
def is_u2f_enabled(user): """ Determine if a user has U2F enabled """ return user.u2f_keys.all().exists()
39b3b93e03eee230fc978ad5ec64ba4965b2d809
28,149
def extend_feature_columns(feature_columns): """ Use to define additional feature columns, such as bucketized_column and crossed_column Default behaviour is to return the original feature_column list as is Args: feature_columns: [tf.feature_column] - list of base feature_columns to be extended Returns: [tf.feature_column]: extended feature_column list """ # examples - given: # 'x' and 'y' are two numeric features: # 'alpha' and 'beta' are two categorical features # feature_columns['alpha_X_beta'] = tf.feature_column.crossed_column( # [feature_columns['alpha'], feature_columns['beta']], int(1e4)) # # num_buckets = parameters.HYPER_PARAMS.num_buckets # buckets = np.linspace(-2, 2, num_buckets).tolist() # # feature_columns['x_bucketized'] = tf.feature_column.bucketized_column( # feature_columns['x'], buckets) # # feature_columns['y_bucketized'] = tf.feature_column.bucketized_column( # feature_columns['y'], buckets) # # feature_columns['x_bucketized_X_y_bucketized'] = tf.feature_column.crossed_column( # [feature_columns['x_bucketized'], feature_columns['y_bucketized']], int(1e4)) return feature_columns
11d0c77331745719d445f7926f041e2fe1c70903
28,150
import torch def max_matching(scores): """ Matching according to maximum similarity. Input matrix shape: [D, T] (dim=0) Return ids shape: [T] """ ids = scores.new_full((scores.size(1), ), -1).long() # assume t2d t2d_max, t2d_idxs = scores.max(dim=0) match_t_idxs = torch.nonzero(t2d_max > 0).squeeze(1) if match_t_idxs.shape[0] == 0: return ids t2d_max = t2d_max[match_t_idxs.tolist()] t2d_idxs = t2d_idxs[match_t_idxs.tolist()] _, d2t_idxs = scores[:, match_t_idxs].max(dim=1) flag_d2t = d2t_idxs[t2d_idxs].long() flag_t2d = torch.arange(t2d_idxs.size(0)).to(scores.device) is_match = (flag_d2t == flag_t2d) if not is_match.all(): true_match_t_idxs = torch.nonzero(is_match == 1).squeeze(1) ids[match_t_idxs[true_match_t_idxs]] = t2d_idxs[true_match_t_idxs] scores[t2d_idxs[true_match_t_idxs], :] = 0 unmatch_t_idxs = torch.nonzero(is_match == 0).squeeze(1) _ids = max_matching(scores[:, match_t_idxs[unmatch_t_idxs]]) ids[match_t_idxs[unmatch_t_idxs]] = _ids else: ids[match_t_idxs] = t2d_idxs return ids
63bf51639050371d55bcd3413738c26e82c878f2
28,151
def get_initial_user_settings(argv): """ Parses the given command line arguments to extract the user's desired user_set_speed and safe_distance. If a value is not given then None is returned in place of that value. >>> get_initial_user_settings(["speed=20", "distance=150"]) (20, 150) >>> get_initial_user_settings(["foo", "distance=150"]) (None, 150) :param list[str] argv: The command line arguments to parse. :return: A tuple containing the desired user_set_speed and safe_distance. :rtype: tuple[int, int] """ user_set_speed = None safe_distance = None for a in argv[1:]: splitted = a.split("=") if splitted[0] == "speed": user_set_speed = int(splitted[1]) elif splitted[0] == "distance": safe_distance = int(splitted[1]) return user_set_speed, safe_distance
058c5543688646a37e61a5e8f6e0b1f6abd5eacf
28,152
def clean_data(players): """Sanitize the list of player data.""" cleaned_players = [] for player in players: cleaned_player = {} for key, value in player.items(): cleaned_value = value if key == "height": cleaned_value = int(value[0:2]) elif key == "experience": cleaned_value = value == "YES" elif key == "guardians": cleaned_value = value.split(" and ") cleaned_player[key] = cleaned_value cleaned_players.append(cleaned_player) return cleaned_players
88836eb154ff1a3cb32c567634adf813ac234de6
28,153
def _jupyter_server_extension_paths(): """python module to load as extension""" return [{"module": "ipydrawio_export"}]
a4a3cf100b8cfeb6acec9ff0d1482f2fe1587068
28,154
import argparse import os def parse_args(): """ Parse arguments for program """ parser = argparse.ArgumentParser(description="Program for renaming files") parser.add_argument("find",help="Find pattern") parser.add_argument("-i","--ignore_case", action="store_true", help = "Ignore case") parser.add_argument("rename",help="Rename pattern") parser.add_argument("-d","--directory",default=os.getcwd(), help = "Directory") parser.add_argument("-y","--no_confirm", action="store_true", help="Don't ask for confirmation") return parser.parse_args()
561ce79282688360f8122e7f89abbcf3f0d70f7d
28,155
import shutil def exe_exists(exe): """ Returns the full path if executable exists and is the path. None otherwise """ return shutil.which(exe)
38bed97a3d195e6adc8e0dba936d213828f15e2f
28,156
def is_term_mod(label): """Check if `label` corresponds to a terminal modification. Parameters ---------- label : str Returns ------- out : bool """ return label[0] == '-' or label[-1] == '-'
c7ed745be0ab0dac54c8846bb2865832e5aa4778
28,157
def confusion_stats(set_true, set_test): """ Count the true positives, false positives and false negatives in a test set with respect to a "true" set. True negatives are not counted. """ true_pos = len(set_true.intersection(set_test)) false_pos = len(set_test.difference(set_true)) false_neg = len(set_true.difference(set_test)) return true_pos, false_pos, false_neg
401b216b1317f16a424830e71b48f1d21d603956
28,159
def verif_lettres_joueur(plateau, lettres_joueur, coup): """ Cette fonction renvoie True: - Si le mot à placer appartient au lettres du joueur (lettres_joueurs) ou - Si une ou plusieurs lettres manquent mais sont déjà placées à la place adéquate sur le plateau (plateau). Sinon, la fonction renvoie False. On pré-suppose que le mot ne dépasse pas des bornes du plateau Arguments : - plateau (liste) : une liste de sous-listes qui représentent chacune une ligne du plateau de jeu. Elles contiennent chacune, soit un underscore pour indiquer que la case est vide, soit une lettre si elle a déjà été placée là auparavant. - lettres_joueur (liste) : une liste qui contient chacune des lettres que le joueur possède sur son chevalet. Toutes ces lettres sont en MAJUSCULE. - coup (tuple): un tuple à 3 éléments: - mot (str): une chaine de caractère en majuscule qui indique le mot à placer - pos (tuple) : un tuple d'entiers (l,c) qui indiquent le numéro de ligne (l), et le numéro de la colonne (c) de la première lettre du mot à placer - dir (str) : un charactère (h ou v) qui indique la direction du mot Valeurs de retour: - bool (True ou False) """ re = False ret = [] mot, pos, dir = coup l, c = pos if dir == 'h': for i in range(len(mot)): current_letter = plateau[l][c + i] if (mot[i] in lettres_joueur) or (mot[i] == current_letter): ret.append('True') else: ret.append('False') elif dir == 'v': for j in range(len(mot)): current_letter = plateau[l + j][c] if (mot[j] in lettres_joueur) or (mot[j] == current_letter): ret.append('True') else: ret.append('False') if 'False' not in ret: re = True return(re)
8a05bbe54b281afec4bc31bb6577528aa6cf3816
28,160
def get_item_nodeid(item): """Build item node id.""" # note: pytest's item.nodeid could be modified by third party, so build a local one here if item.location and len(item.location) > 2: return item.location[0].replace("\\", "/") + "::" + item.location[2].replace(".", "::") return item.fspath.relto(item.config.rootdir).replace("\\", "/") + "::" + item.getmodpath().replace(".", "::")
a25594640d96dd387a4fbecc11ef874b8000faf7
28,161
def category_parents(category): """ Get list parents of category :param category: Object category, product. e.g <8c8fff64-8886-4688-9a90-24f0d2d918f9> :return: Dict | List | List categories and sub-categories. e.g. [ { "id": "c0136516-ff72-441a-9835-1ecb37357c41", "name": "Sombreros y Gorros" }, { "id": "ff2cbe7e-a817-41d5-9363-6175bb757505", "name": "Accesorios" }, { "id": "7b68e61c-516a-45b4-8eda-654f3af39e03", "name": "ROPA MUJER" } ] """ if not category.parent_category: return [] parent_list = [] while category.parent_category: parent_list.append({ 'id': str(category.id), 'name': category.name, } ) category = category.parent_category parent_list.append({ 'id': str(category.id), 'name': category.name, } ) return parent_list
84616c76fb4179eb2f91600699e1f07d0de9b15f
28,162
def missingNumber(nums: list) -> int: """ 解法2:数学公式。 """ n = len(nums) expected_sum = n*(n+1) // 2 actual_sum = sum(nums) return expected_sum - actual_sum
ae6c0a7533e81c1c3d0e61a49298cdf551eda261
28,163
from typing import Iterable from typing import Dict from typing import Any from typing import List import collections def _list_dict_to_dict_list(samples: Iterable[Dict[Any, Any]]) -> Dict[Any, List[Any]]: """Convert a list of dictionaries to a dictionary of lists. Args: samples: a list of dictionaries Returns: a dictionary of lists .. versionadded:: 0.2 """ collated = collections.defaultdict(list) for sample in samples: for key, value in sample.items(): collated[key].append(value) return collated
a5bd1dea71306f5e8151f6dfcc94b96f328b6d76
28,165
def count_rule_conditions(rule_string: str) -> int: """ Counts the number of conditions in a rule string. Parameters ---------- rule_string : str The standard Iguanas string representation of the rule. Returns ------- int Number of conditions in the rule. """ n_conditions = rule_string.count("X['") return n_conditions
4dc8bc3fdc7ee4d4302101a39b7849bcd7dff6e8
28,166
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of parameters that will be estimated. Will raise a ValueError otherwise. Parameters ---------- name_list : list of strings. Each element should be the name of a parameter that is to be estimated. num_alts : int. Should be the total number of alternatives in the universal choice set for this dataset. constrainted_param : {0, 1, True, False} Indicates whether (1 or True) or not (0 or False) one of the type of parameters being estimated will be constrained. For instance, constraining one of the intercepts. list_title : str. Should specify the type of parameters whose names are being checked. Examples include 'intercept_params' or 'shape_params'. Returns ------- None. """ if len(name_list) != (num_alts - constrained_param): msg_1 = "{} is of the wrong length:".format(list_title) msg_2 = "len({}) == {}".format(list_title, len(name_list)) correct_length = num_alts - constrained_param msg_3 = "The correct length is: {}".format(correct_length) total_msg = "\n".join([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
d83ed7d6989c7e3ccdbbb256eaa72759a7f242d3
28,167
def compose_terms(terms): """ Compose a sequence of terms. Composition is done with *time* ordered left-to-right. Thus composition order is NOT the same as usual matrix order. E.g. if there are three terms: `terms[0]` = T0: rho -> A*rho*A `terms[1]` = T1: rho -> B*rho*B `terms[2]` = T2: rho -> C*rho*C Then the resulting term T = T0*T1*T2 : rho -> CBA*rho*ABC, so that term[0] is applied *first* not last to a state. Parameters ---------- terms : list A list of terms to compose. magnitude : float, optional The magnitude of the composed term (fine to leave as None if you don't care about keeping track of magnitudes). Returns ------- RankOneTerm """ assert(len(terms) > 0) # otherwise return something like RankOneTerm(1.0, None, None)? return terms[0].compose(terms)
dc6cdbe5f05e1a93335f0436136dfe4f0ec7a5d3
28,168
def get_token_object(auth): """ Retrieve the object or instance from a token creation. Used for knox support. :param auth: The instance or tuple returned by the token's .create() :type auth tuple | rest_framework.authtoken.models.Token :return: The instance or object of the token :rtype: rest_framework.authtoken.models.Token | knox.models.AuthToken """ return auth[0] if isinstance(auth, tuple) else auth
3651951e413f3fd44f159ed6070542d54f2923b2
28,169
def format_interconnector_loss_demand_coefficient(LOSSFACTORMODEL): """Re-formats the AEMO MSS table LOSSFACTORMODEL to be compatible with the Spot market class. Examples -------- >>> LOSSFACTORMODEL = pd.DataFrame({ ... 'INTERCONNECTORID': ['X', 'X', 'X', 'Y', 'Y'], ... 'REGIONID': ['A', 'B', 'C', 'C', 'D'], ... 'DEMANDCOEFFICIENT': [0.001, 0.003, 0.005, 0.0001, 0.002]}) >>> demand_coefficients = format_interconnector_loss_demand_coefficient(LOSSFACTORMODEL) >>> print(demand_coefficients) interconnector region demand_coefficient 0 X A 0.0010 1 X B 0.0030 2 X C 0.0050 3 Y C 0.0001 4 Y D 0.0020 Parameters ---------- LOSSFACTORMODEL : pd.DataFrame ================= ====================================================================================== Columns: Description: INTERCONNECTORID unique identifier of a interconnector (as `str`) REGIONID unique identifier of a market region (as `str`) DEMANDCOEFFICIENT the coefficient of regional demand variable in the loss factor equation (as `np.float64`) ================= ====================================================================================== Returns ---------- demand_coefficients : pd.DataFrame ================== ========================================================================================= Columns: Description: interconnector unique identifier of a interconnector (as `str`) region the market region whose demand the coefficient applies too, required (as `str`) demand_coefficient the coefficient of regional demand variable in the loss factor equation (as `np.float64`) ================== ========================================================================================= """ demand_coefficients = LOSSFACTORMODEL.loc[:, ['INTERCONNECTORID', 'REGIONID', 'DEMANDCOEFFICIENT']] demand_coefficients.columns = ['interconnector', 'region', 'demand_coefficient'] return demand_coefficients
a7a87543eedb33248f6532ec234d47b7fe5455b3
28,170
import sys def identify_column(query_column, header): """ Identifies the query column of interest if entered as an integer or a string and gives the index values of that column. Parameters ---------- query_column: integer or string The column to search for the query_value in. header: list of strings The header of the file of interest which contains the column titles to be searched for a match with inputted strings for query columns. Returns: -------- index: integer Index value of the query column. """ index = 0 # checks if integer for column was inputted # assumes counting starting at 0 for column_header in header: try: type(int(query_column)) == int column = int(query_column) # checks for array length exception if column > (len(header) - 1): print("Searching for result column " + str(query_column) + " but there are only " + str(len(header)-1) + " fields") sys.exit(1) else: index = column except ValueError: if query_column == column_header: break else: index += 1 # checks for str(query_column) match exception if index > (len(header)-1): print("Searching for result column " + query_column + " but this file does not contain it") sys.exit(1) return(index)
1dfbc16974dcfe971722636b99ffc22300d3ea28
28,171
from datetime import datetime def to_time_string(value): """ gets the time string representation of input datetime with utc offset. for example: `23:40:15` :param datetime | time value: input object to be converted. :rtype: str """ time = value if isinstance(value, datetime): time = value.timetz() return time.isoformat(timespec='seconds')
b81ffff8b4ab626e0094bcfeb0bf6916de89d344
28,172
def u(string: str) -> bytes: """Shortcut to encode string to bytes.""" return string.encode('utf8')
3310da2d9f24be94c0426128ac19db2481dd2c2d
28,173
from pathlib import Path import typing import subprocess def git_get_toplevel(repo_path: Path ) -> typing.Optional[Path]: """ Get top-level working tree path for @repo_path. Returns None when not in repository. """ sp = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], cwd=repo_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sout, serr = sp.communicate() if sp.returncode != 0: return None return Path(sout.decode().strip())
ff047fed00839a27650e04cbc816b3a5d3ec9d28
28,176
import random def random_selection(similarity_matrix, nb_items=None): """ Selects randomly an item from the given similarity_matrix :param similarity_matrix: (pandas.DataFrame) an NxN dataframe; should be (a) symmetric and (b) values {i,j} to represent the similarity between item of row i and column j :param nb_items: (int) number of items to be selected; if None all items are selected in the returned list :return: (list) a list of random items """ selected_items = [] nb_total_items = similarity_matrix.shape[0] if (nb_items is None) or (nb_items > nb_total_items): nb_items = nb_total_items for i in range(nb_items): temp = random.sample(list(similarity_matrix), 1)[0] selected_items.append(temp) return selected_items
dd54045f690dc63c3a5b8c21685c6d610b45fccb
28,177
def try_guess(guess, current_game, game_word): """Test input letter""" result = False for i, value in enumerate(game_word): if value == guess: result = True current_game[i] = guess return current_game, result
5f73dc0a4592ad3de7c880eb41f26660fee9ce68
28,178
def dictToTuple(heading, d): """Convert dict into an ordered tuple of values, ordered by the heading""" return tuple([d[attr] for attr in heading])
1a76201da4e5348a4c4ba9607992ad41a1c87163
28,179
def nrl(tb37v, tb37h): """Lo/Naval Research Laboratory (NRL) """ A0 = 1.3 # values from Leif A1 = 0.019 c = A0 - A1*(tb37v - tb37h) return c
be3ffb39683126df089d1298a87f7d3ab351514a
28,180