content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def format_search_log(json_string): """ usage example {{ model_object|format_search_log }} """ query_json = json.loads(json_string) attributes_selected = sorted(query_json.get('_source')) context = {} context['attributes_selected'] = attributes_selected return attributes_selected
eb5aa21590474acaee7b2b94a1cfdc52c080d017
706,011
def test_get_earth_imperative_solution(solar_system): """ ## Imperative Solution The first example uses flow control statements to define a [Imperative Solution]( https://en.wikipedia.org/wiki/Imperative_programming). This is a very common approach to solving problems. """ def get_planet_by_name(name, the_solar_system): try: planets = the_solar_system['star']['planets'] for arc in planets.values(): for planet in arc: if name == planet.get('name', None): return planet except KeyError: pass return None actual = get_planet_by_name('Earth', solar_system) expected = {'Number of Moons': '1', 'diameter': 12756, 'has-moons': True, 'name': 'Earth'} assert actual == expected
f966886e3384547803106c404a21e2bb7ecd8fa9
706,012
def radialBeamProfile_flatTop(x,y,a): """Top hat beam profile \param[in] x x-position for profile computation \param[in] y y-position for profile computation \param[in] a radial extension of flat-top component \param[in] R 1/e-width of beam profile \param[out] isp radial irradiation source profile """ if (x**2+y**2) <= a*a: return 1.0 else: return 0.0
699d214c499d8cbcf1c0ed26a5d0d00cf2813f3f
706,013
import platform def get_machine_name(): """ Portable way of calling hostname shell-command. Regarding docker containers: NOTE: If we are running from inside the docker-dev environment, then $(hostname) will return the container-id by default. For now we leave that behaviour. We can override it in the future by passing --hostname to the container. Documentation: https://docs.docker.com/config/containers/container-networking/#ip-address-and-hostname :return: Unique name for a node in the cluster """ machine_name = platform.node() return machine_name
ae5a7090846164a97cafd07af4701dcfcc25070e
706,014
def pass_through_formatter(value): """No op update function.""" return value
202ea761db9e1fa858718c61df3a7fd18f02826c
706,015
def check_branch(payload, branch): """ Check if a push was on configured branch. :param payload: Payload from web hook. :param branch: Name of branch to trigger action on. :return: True if push was on configured branch, False otherwise. """ if "ref" in payload: if payload["ref"] == branch: return True return False
88bd0ebae330ee169e97a40aee208b2f92ee4a32
706,016
import re def nice(name): """Generate a nice name based on the given string. Examples: >>> names = [ ... "simple_command", ... "simpleCommand", ... "SimpleCommand", ... "Simple command", ... ] >>> for name in names: ... nice(name) 'Simple Command' 'Simple Command' 'Simple Command' 'Simple Command' Arguments: name (str): The string from which generate the nice name. Returns: str: The generated nice name. """ # The regular expression will match all upper case characters except the # one that starts the string and insert a space before it. return re.sub(r"(?<!^)([A-Z])", r" \1", name).replace("_", " ").title()
ab96675423812a85744bb76e7f62d08bbbac2eea
706,018
def findwskeyword(keyword, sol): """Find and return a value for a keyword in the list of the wavelength solution""" i = sol.index(keyword) j = sol[i:].index('\n') return sol[i:i + j].split('=')[1].strip()
b3cc028415d74ecfd7ec3868ae591d7b4d3b8860
706,020
def format_time(time): """ Converts datetimes to the format expected in SAML2 XMLs. """ return time.strftime("%Y-%m-%dT%H:%M:%SZ")
03651b72aa0b177ac1ac3f1ccafdba6fe967a11a
706,021
def get_delivery_voucher_discount(voucher, total_price, delivery_price): """Calculate discount value for a voucher of delivery type.""" voucher.validate_min_amount_spent(total_price) return voucher.get_discount_amount_for(delivery_price)
8ede095730c1d29d01949dff47b4a2893d29720c
706,022
def process_results(unprocessed, P, R, G): """Process the results returned by the worker pool, sorting them by policy and run e.g. results[i][j][k] are the results from policy i on run j on graph k. Parameters: - unprocessed: Unprocessed results (as returned by the worker pool) - P: number of policies - R: number of runs - G: number of graphs/SCMs/test cases """ results = [] for i in range(P): policy_results = [] for r in range(R): run_results = unprocessed[(i*G*R + G*r):(i*G*R + G*(r+1))] policy_results.append(run_results) results.append(policy_results) return results
24c2854723b3fc33c3fee58595f84d789e861fbc
706,025
def check_hashtarget(bible_hash, target): """ tests if the biblepay hash is valid for the hashtarget, means that is it lower. True = is lower and all is fine """ rs = False try: rs = int(bible_hash, 16) < int(target, 16) except: pass return rs
a0041d8834b2a0af0a08c2562ffed599925ed5a8
706,026
def gen_spacer(spacer_char="-", nl=2): """ Returns a spacer string with 60 of designated character, "-" is default It will generate two lines of 60 characters """ spacer = "" for i in range(nl): spacer += spacer_char * 60 spacer += "\n" return spacer
7434f191dafdf500c2fc3e67373afc664e543ce0
706,027
def __check_interface_state(duthost, interface, state='up'): """ Check interface status Args: duthost: DUT host object interface: Interface of DUT state: state of DUT's interface Returns: Bool value which confirm port state """ ports_down = duthost.interface_facts(up_ports=[interface])['ansible_facts']['ansible_interface_link_down_ports'] if 'down' in state: return interface in ports_down return interface not in ports_down
bc17d489064e9a81ec77dad5ab3682c9a96fa88d
706,029
import torch def get_number_of_voxels_per_class(labels: torch.Tensor) -> torch.Tensor: """ Computes the number of voxels for each class in a one-hot label map. :param labels: one-hot label map in shape Batches x Classes x Z x Y x X or Classes x Z x Y x X :return: A tensor of shape [Batches x Classes] containing the number of non-zero voxels along Z, Y, X """ if not len(labels.shape) in [5, 4]: raise Exception("labels must have either 4 (Classes x Z x Y x X) " "or 5 dimensions (Batches x Classes x Z x Y x X), found:{}" .format(len(labels.shape))) if len(labels.shape) == 4: labels = labels[None, ...] return torch.count_nonzero(labels, dim=(2, 3, 4))
568a91639a42cf3cd3debe365c5a963512d95dfc
706,030
import pydoc def read_docstring(object_): """ Returns object docstring without the FILE information. """ fmt = "```\n{}\n```\n" docs = pydoc.plain(pydoc.render_doc(object_)).split("FILE")[0].rstrip() return fmt.format(docs)
5c21f6eadf400ac9316e3f44d98464536b9b7536
706,031
def parse_scales_line(line): """ Args: - line: Returns: - scales_dict """ def advance_past_token(str, token): return str[str.find(token) + len(token):] scales_dict = {} line = advance_past_token(line, 'Scales:') pair_str = line.split(',') for pair_str in pair_str: dname, scale = pair_str.split(':') scales_dict[dname.strip()] = float(scale) return scales_dict
b16e1f431b878aa6418beaed3f141fe928a229e1
706,032
import collections def parse_remove_configuration(configuration): """ Turns the configuration line of splitting into a name and a set of params. """ if configuration is None: return "None", None print('conf', configuration) conf_dict = collections.OrderedDict(configuration) name = 'remove' for key in conf_dict.keys(): if key != 'weights' and key != 'boost': name += '_' name += key return name, conf_dict
40bf749c2e142cef534f945179b987fd3c7ba6d8
706,033
def focused_evaluate(board): """ Given a board, return a numeric rating of how good that board is for the current player. A return value >= 1000 means that the current player has won; a return value <= -1000 means that the current player has lost """ score = board.longest_chain(board.get_current_player_id()) * 10 # Prefer having your pieces in the center of the board. for row in range(6): for col in range(7): if board.get_cell(row, col) == board.get_current_player_id(): score -= abs(3-col) elif board.get_cell(row, col) == board.get_other_player_id(): score += abs(3-col) if board.is_game_over(): if int(board.is_win()) == int(board.get_current_player_id()): score = +1000; score -= board.num_tokens_on_board() elif int(board.is_win()) == int(board.get_other_player_id()): score = -1000 return score
b2cbb91cdb048ef41a13532e400173daa05af4b8
706,034
def uploadResourceFileUsingSession(url, session, resourceName, fileName, fullPath, scannerId): """ upload a file for the resource - e.g. a custom lineage csv file works with either csv for zip files (.csv|.zip) returns rc=200 (valid) & other rc's from the post """ print( "uploading file for resource " + url + " resource=" + resourceName ) apiURL = url + "/access/1/catalog/resources/" + resourceName + "/files" print("\turl=" + apiURL) # header = {"accept": "*/*", } params = {"scannerid": scannerId, "filename": fileName, "optionid": "File"} print("\t" + str(params)) # files = {'file': fullPath} mimeType = "text/csv" readMode = "rt" if fileName.endswith(".zip"): mimeType = "application/zip" readMode = "rb" if fileName.endswith(".dsx"): mimeType = "text/plain" file = {"file": (fileName, open(fullPath, readMode), mimeType)} # file = {"file": (fileName, open(fullPath, readMode), )} print(f"\t{file}") # print(f"session header:{session.headers}") uploadResp = session.post( apiURL, data=params, files=file, ) print("\tresponse=" + str(uploadResp.status_code)) if uploadResp.status_code == 200: # valid - return the json return uploadResp.status_code else: # not valid print("\tupload file failed") print("\t" + str(uploadResp)) print("\t" + str(uploadResp.text)) return uploadResp.status_code
8a4a8c21563f1467db284f2e98dd1b48dbb65a3c
706,035
import platform import os def _clear_screen(): """ http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """ if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
2958ef538e95d717d60c577c631ddd91240c48f9
706,036
def numeric_to_string(year): """ Convert numeric year to string """ if year < 0 : yearstring = "{}BC".format(year*-1) elif year >= 0: yearstring = "{}AD".format(year) else: raise return yearstring
3469e2dd5e05c49b4861782da2dd88bac781c61d
706,039
def _get_num_ve_sve_and_max_num_cells(cell_fracs): """ Calculate the num_ve, num_sve and max_num_cells Parameters ---------- cell_fracs : structured array, optional A sorted, one dimensional array, each entry containing the following fields: :idx: int The volume element index. :cell: int The geometry cell number. :vol_frac: float The volume fraction of the cell withing the mesh ve. :rel_error: float The relative error associated with the volume fraction. Returns ------- num_ve : int Number of the total voxels num_sve : int Number of the total subvoxels, eqaul to or greater than num_ve max_num_cells : int Max number of cells (subvoxels) in a voxel """ num_sve = len(cell_fracs) num_ve = len(set(cell_fracs["idx"])) max_num_cells = -1 for i in range(num_sve): max_num_cells = max(max_num_cells, len(cell_fracs[cell_fracs["idx"] == i])) return num_ve, num_sve, max_num_cells
c0d154898bbfeafd66d89a2741dda8c2aa885a9a
706,040
def flip_nums(text): """ flips numbers on string to the end (so 2019_est --> est_2019)""" if not text: return '' i = 0 s = text + '_' while text[i].isnumeric(): s += text[i] i += 1 if text[i] == '_': i += 1 return s[i:]
e0534e25e95b72e1d6516111413e32a6dae207ef
706,041
def extent2(texture): """ Returns the extent of the image data (0.0-1.0, 0.0-1.0) inside its texture owner. Textures have a size power of 2 (512, 1024, ...), but the actual image can be smaller. For example: a 400x250 image will be loaded in a 512x256 texture. Its extent is (0.78, 0.98), the remainder of the texture is transparent. """ return (texture.tex_coords[3], texture.tex_coords[7])
16c6d220ad48201fd133ed11c97452bf0831c0d8
706,042
def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # Store the total length of the hand hand_len = 0 # For every letter in the hand for key in hand.keys(): # Add the number of times that letter appears in the hand # to the variable storing hand length hand_len += hand[key] # Return the number of letters in the current hand return hand_len
297f8af5943bf87bb7999a1212d54430857de12b
706,043
def _server_allow_run_on_save() -> bool: """Allows users to automatically rerun when app is updated. Default: true """ return True
3a895abd8201ce97c8f2f928b841eb86bf6327d1
706,044
def Law_f(text): """ :param text: The "text" of this Law """ return '\\begin{block}{Law}\n' + text + '\n\\end{block}\n'
594b279c5971a9d379666179c4d0633fc02a8bd9
706,045
import torch def valid_from_done(done): """Returns a float mask which is zero for all time-steps after a `done=True` is signaled. This function operates on the leading dimension of `done`, assumed to correspond to time [T,...], other dimensions are preserved.""" done = done.type(torch.float) valid = torch.ones_like(done) valid[1:] = 1 - torch.clamp(torch.cumsum(done[:-1], dim=0), max=1) return valid
0ca2bd0f9e23605091b2f8d1bc15e67e1632b82b
706,046
def rescale_list_to_range(original, limits): """ Linearly rescale values in original list to limits (minimum and maximum). :example: >>> rescale_list_to_range([1, 2, 3], (0, 10)) [0.0, 5.0, 10.0] >>> rescale_list_to_range([1, 2, 3], (-10, 0)) [-10.0, -5.0, 0.0] >>> rescale_list_to_range([1, 2, 3], (0j, 10j)) [0j, 5j, 10j] :param original: Original list or list-like to be rescaled. :type original: list :param limits: Tuple of two floats, min and max, to constrain the new list :type limits: tuple :return: Original list rescaled to fit between min and max :rtype: list """ new_min, new_max = limits[0:2] old_min, old_max = min(original), max(original) return (new_max + new_min) / 2 * original / old_min if old_min == old_max \ else [new_max * (v - old_min) / (old_max - old_min) + new_min * (old_max - v) / (old_max - old_min) for v in original]
bdd38bb24b597648e4ca9045ed133dfe93ad4bd8
706,047
def get_ratings(labeled_df): """Returns list of possible ratings.""" return labeled_df.RATING.unique()
2b88b1703ad5b5b0a074ed7bc4591f0e88d97f92
706,048
from math import cos,pi from numpy import zeros def gauss_legendre(ordergl,tol=10e-14): """ Returns nodal abscissas {x} and weights {A} of Gauss-Legendre m-point quadrature. """ m = ordergl + 1 def legendre(t,m): p0 = 1.0; p1 = t for k in range(1,m): p = ((2.0*k + 1.0)*t*p1 - k*p0)/(1.0 + k ) p0 = p1; p1 = p dp = m*(p0 - t*p1)/(1.0 - t**2) return p1,dp A = zeros(m) x = zeros(m) nRoots = (m + 1)// 2 # Number of non-neg. roots for i in range(nRoots): t = cos(pi*(i + 0.75)/(m + 0.5)) # Approx. root for j in range(30): p,dp = legendre(t,m) # Newton-Raphson dt = -p/dp; t = t + dt # method if abs(dt) < tol: x[i] = t; x[m-i-1] = -t A[i] = 2.0/(1.0 - t**2)/(dp**2) # Eq.(6.25) A[m-i-1] = A[i] break return x,A
5353373ee59cd559817a737271b4ff89cc031709
706,049
import re def irccat_targets(bot, targets): """ Go through our potential targets and place them in an array so we can easily loop through them when sending messages. """ result = [] for s in targets.split(','): if re.search('^@', s): result.append(re.sub('^@', '', s)) elif re.search('^#', s) and s in bot.config.core.channels: result.append(s) elif re.search('^#\*$', s): for c in bot.config.core.channels: result.append(c) return result
b7dce597fc301930aae665c338a9e9ada5f2be7e
706,050
def cli(ctx, path, max_depth=1): """List files available from a remote repository for a local path as a tree Output: None """ return ctx.gi.file.tree(path, max_depth=max_depth)
4be4fdffce7862332aa27a40ee684aae31fd67b5
706,051
def merge(d, **kwargs): """Recursively merges given kwargs int to a dict - only if the values are not None. """ for key, value in kwargs.items(): if isinstance(value, dict): d[key] = merge(d.get(key, {}), **value) elif value is not None: d[key] = value return d
168cc66cce0a04b086a17089ebcadc16fbb4c1d0
706,053
import os def get_db_path(): """Return the path to Dropbox's info.json file with user-settings.""" if os.name == 'posix': # OSX-specific home_path = os.path.expanduser('~') dbox_db_path = os.path.join(home_path, '.dropbox', 'info.json') elif os.name == 'nt': # Windows-specific home_path = os.getenv('LOCALAPPDATA') dbox_db_path = os.path.join(home_path, 'Dropbox', 'info.json') else: raise NotImplementedError("Unknown Platform: {0}".format(os.name)) return dbox_db_path
04ee901faea224dde382a11b433f913557c7cb21
706,054
import math def convert_table_value(fuel_usage_value): """ The graph is a little skewed, so this prepares the data for that. 0 = 0 1 = 25% 2 = 50% 3 = 100% 4 = 200% 5 = 400% 6 = 800% 7 = 1600% (not shown) Intermediate values scale between those values. (5.5 is 600%) """ if fuel_usage_value < 25: return 0.04 * fuel_usage_value else: return math.log((fuel_usage_value / 12.5), 2)
15e4deedb4809eddd830f7d586b63075b71568ef
706,055
import requests from datetime import datetime def fetch_status(): """ 解析サイト<https://redive.estertion.win> からクラバト情報を取ってくる return ---- ``` { "cb_start": datetime, "cb_end": datetime, "cb_days": int } ``` """ # クラバト開催情報取得 r = requests.get( "https://redive.estertion.win/ver_log_redive/?page=1&filter=clan_battle" ).json() # クラバト開始日取得 cb_start = r["data"][0]["clan_battle"][0]["start"] cb_start = datetime.strptime(cb_start, "%Y/%m/%d %H:%M:%S") # クラバト終了日取得 cb_end = r["data"][0]["clan_battle"][0]["end"] cb_end = datetime.strptime(cb_end, "%Y/%m/%d %H:%M:%S") # クラバト開催日数 cb_days = (cb_end - cb_start).days + 1 return {"cb_start": cb_start, "cb_end": cb_end, "cb_days": cb_days}
683c9fe84bf346a1cce703063da8683d3469ccc2
706,056
def A004086(i: int) -> int: """Digit reversal of i.""" result = 0 while i > 0: unit = i % 10 result = result * 10 + unit i = i // 10 return result
b0a65b7e203b7a92f7d6a1846888798c369ac869
706,057
def should_raise_sequencingerror(wait, nrep, jump_to, goto, num_elms): """ Function to tell us whether a SequencingError should be raised """ if wait not in [0, 1]: return True if nrep not in range(0, 16384): return True if jump_to not in range(-1, num_elms+1): return True if goto not in range(0, num_elms+1): return True return False
fc7c4bdb29cd5b90faec59a4f6705b920304aae0
706,058
def add_volume (activity_cluster_df, activity_counts): """Scales log of session counts of each activity and merges into activities dataframe Parameters ---------- activity_cluster_df : dataframe Pandas dataframe of activities, skipgrams features, and cluster label from DBSCAN activity_counts: dictionary Dictionary (from activities.create_corpus func) of activity and session counts Returns ------- pandas dataframe of activities, skipgrams features, x-value, y-value, and activity volume percentiles """ assert isinstance(activity_counts, dict) == True, "activity_counts should be a dictionary." assert len(activity_counts) >= len(activity_cluster_df), "activity_counts must contain the same number or more activity entries than activity_cluster_df." # Map activities to capture unique session ID acount in activities dataframe activity_cluster_df['volume_pctl'] = activity_cluster_df.index.map(activity_counts) # Replace absolute volume with percentile rank integer activity_cluster_df['volume_pctl'] = activity_cluster_df['volume_pctl'].rank(pct=True) * 100 return activity_cluster_df
1ea67909e2c48500ca2f022a3ae5ebcbe28da6c8
706,059
def prefetched_iterator(query, chunk_size=2000): """ This is a prefetch_related-safe version of what iterator() should do. It will sort and batch on the default django primary key Args: query (QuerySet): the django queryset to iterate chunk_size (int): the size of each chunk to fetch """ # walk the records in ascending id order base_query = query.order_by("id") def _next(greater_than_id): """Returns the next batch""" return base_query.filter(id__gt=greater_than_id)[:chunk_size] batch = _next(0) while batch: item = None # evaluate each batch query here for item in batch: yield item # next batch starts after the last item.id batch = _next(item.id) if item is not None else None
e8a8feeea8073161283018f19de742c9425e2f94
706,060
import os def get_dir(foldername, path): """ Get directory relative to current file - if it doesn't exist create it. """ file_dir = os.path.join(path, foldername) if not os.path.isdir(file_dir): os.mkdir(os.path.join(path, foldername)) return file_dir
8574dfc0503c8cc6410dc013a23689ac2b77f5d6
706,061
def dicom_strfname( names: tuple) -> str: """ doe john s -> dicome name (DOE^JOHN^S) """ return "^".join(names)
864ad0d4c70c9bb4acbc65c92bf83a97415b9d35
706,062
def skip(line): """Returns true if line is all whitespace or shebang.""" stripped = line.lstrip() return stripped == '' or stripped.startswith('#!')
4ecfb9c0f2d497d52cc9d9e772e75d042cc0bcce
706,063
def draw_box(image, box, color): """Draw 3-pixel width bounding boxes on the given image array. color: list of 3 int values for RGB. """ y1, x1, y2, x2 = box image[y1:y1 + 1, x1:x2] = color image[y2:y2 + 1, x1:(x2+1)] = color image[y1:y2, x1:x1 + 1] = color image[y1:y2, x2:x2 + 1] = color return image
4d1e713c6cb6a3297b4f7d8ab9682205947770da
706,064
def get_statuses_one_page(weibo_client, max_id=None): """获取一页发布的微博 """ if max_id: statuses = weibo_client.statuses.user_timeline.get(max_id=max_id) else: statuses = weibo_client.statuses.user_timeline.get() return statuses
4a214489aa5696c9683c9cfa96d79ee169135eb5
706,065
def do_nothing(ax): """Do not add any watermark.""" return ax
6fbe32dc45ca1a945e1c45bf0319770c4d683397
706,066
def _scan_real_end_loop(bytecode, setuploop_inst): """Find the end of loop. Return the instruction offset. """ start = setuploop_inst.next end = start + setuploop_inst.arg offset = start depth = 0 while offset < end: inst = bytecode[offset] depth += inst.block_effect if depth < 0: return inst.next offset = inst.next
9cff8ab77563a871b86cdbb14236603ec58e04b6
706,067
def IndividualsInAlphabeticOrder(filename): """Checks if the names are in alphabetic order""" with open(filename, 'r') as f: lines = f.readlines() individual_header = '# Individuals:\n' if individual_header in lines: individual_authors = lines[lines.index(individual_header) + 1:] sorted_authors = sorted(individual_authors, key=str.casefold) if sorted_authors == individual_authors: print("Individual authors are sorted alphabetically.") return True else: print("Individual authors are not sorted alphabetically." " The expected order is:") print(''.join(sorted_authors)) return False else: print("Cannot find line '# Individuals:' in file.") return False
4753bbf41498373695f921555c8f01183dbb58dc
706,068
from pathlib import Path def add_filename_suffix(file_path: str, suffix: str) -> str: """ Append a suffix at the filename (before the extension). Args: path: pathlib.Path The actual path object we would like to add a suffix suffix: The suffix to add Returns: path with suffix appended at the end of the filename and before extension """ path = Path(file_path) return str(path.parent.joinpath(path.stem + suffix).with_suffix(path.suffix))
546bb95f694ee5d5cb26873428fcac8453df6a54
706,069
def list_dropdownTS(dic_df): """ input a dictionary containing what variables to use, and how to clean the variables It outputs a list with the possible pair solutions. This function will populate a dropdown menu in the eventHandler function """ l_choice = [] for key_cat, value_cat in dic_df['var_continuous'].items(): l_choice.append(value_cat['name']) l_choice = ['-'] + l_choice return l_choice
fcd0474fa6941438cb39c63aa7605f1b776fd538
706,070
def recostruct(encoded, weights, bias): """ Reconstructor : Encoded -> Original Not Functional """ weights.reverse() for i,item in enumerate(weights): encoded = encoded @ item.eval() + bias[i].eval() return encoded
e17aeb6a819a6eec745c5dd811460049fa4a92cd
706,071
import math def get_file_dataset_from_trixel_id(CatName,index,NfilesinHDF,Verbose=True):#get_file_var_from_htmid in Eran's library """Description: given a catalog basename and the index of a trixel and the number of trixels in an HDF5 file, create the trixel dataset name Input :- CatName - index - NfilesinHDF: number of datasets in an HDF5 files (default is 100) Output :- Filename: name of the HDF5 file where the trixel_dataset is stored - Datasetname: name of the trixel_dataset example: By : Maayane Soumagnac (original Matlab function by Eran Ofek) August 2018""" if Verbose==True: print('index is',index) num_file=math.floor(index/NfilesinHDF)*NfilesinHDF #equivalent to index//Nfiles*Nfiles Filename='%s_htm_%06d.hdf5' % (CatName, num_file) DatasetName='htm_%06d' % index return Filename,DatasetName
b9d0482780ae2a191175f1549513f46c047bb1cf
706,072
def find_correspondance_date(index, csv_file): """ The method returns the dates reported in the csv_file for the i-subject :param index: index corresponding to the subject analysed :param csv_file: csv file where all the information are listed :return date """ return csv_file.EXAMDATE[index]
915b9a493247f04fc1f62e614bc26b6c342783c8
706,074
import unicodedata def normalize_to_ascii(char): """Strip a character from its accent and encode it to ASCII""" return unicodedata.normalize("NFKD", char).encode("ascii", "ignore").lower()
592e59ae10bb8f9a04dffc55bcc2a1a3cefb5e7e
706,075
import functools def pass_none(func): """ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """ @functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) return wrapper
2264ca5978485d8fc13377d17eb84ee522a040b9
706,077
def arcmin_to_deg(arcmin: float) -> float: """ Convert arcmin to degree """ return arcmin / 60
9ef01181a319c0c48542ac57602bd7c17a7c1ced
706,078
def is_hex_value(val): """ Helper function that returns True if the provided value is an integer in hexadecimal format. """ try: int(val, 16) except ValueError: return False return True
6ba5ac1cfa9b8a4f8397cc52a41694cca33a4b8d
706,079
def list_to_str(input_list, delimiter=","): """ Concatenates list elements, joining them by the separator specified by the parameter "delimiter". Parameters ---------- input_list : list List with elements to be joined. delimiter : String, optional, default ','. The separator used between elements. Returns ------- String Returns a string, resulting from concatenation of list's elements, separeted by the delimiter. """ return delimiter.join( [x if isinstance(x, str) else repr(x) for x in input_list] )
4decfbd5a9d637f27473ec4a917998137af5ffe0
706,080
import warnings def _url_from_string(url): """ Generate actual tile url from tile provider definition or template url. """ if "tileX" in url and "tileY" in url: warnings.warn( "The url format using 'tileX', 'tileY', 'tileZ' as placeholders " "is deprecated. Please use '{x}', '{y}', '{z}' instead.", FutureWarning, ) url = ( url.replace("tileX", "{x}").replace("tileY", "{y}").replace("tileZ", "{z}") ) return {"url": url}
f3d4393163e48a7949f3229c55ea8951411dcd63
706,081
import socket def get_reverse_dns(ip_address: str) -> str: """Does a reverse DNS lookup and returns the first IP""" try: rev = socket.gethostbyaddr(ip_address) if rev: return rev[0] return "" # noqa except (socket.herror, socket.gaierror, TypeError, IndexError): return ""
58a27e25f7a9b11ab7dcddebeea743b7864f80f1
706,082
import inspect def get_current_func_name(): """for python version greater than equal to 2.7""" return inspect.stack()[1][3]
002d318bcab98639cab6c38317322f247a1ad0e0
706,083
def getParmNames(parmsDef): """Return a list of parm names in a model parm definition parmsDef: list of tuples, each tuple is a list of parms and a time constraint. Call with modelDict[modelname]['Parms]. Returns: List of string parameter names Here's an example of how to remove unused parms from Fcst, this can run in localConfig: parmsToRemove=[] for p in getParmNames(modelDict['Fcst']): pl=p.lower() for t in ['period','swell','wave','surf', 'surge']: if t in pl: parmsToRemove.append(p) break removeParms(modelDict,'Fcst',parmsToRemove) """ result=[] for pList,tc in parmsDef: # p is the parmDef tuple where first item is the parm name newParms=[p[0] for p in pList] result+=newParms return sorted(result)
785661200c388f23c5f38ae67e773a43fd8f57b3
706,084
import zlib import marshal def serialize(object): """ Serialize the data into bytes using marshal and zlib Args: object: a value Returns: Returns a bytes object containing compressed with zlib data. """ return zlib.compress(marshal.dumps(object, 2))
650cbc8937df5eae79960f744b69b8b12b623195
706,085
def str_to_dtype(s): """Convert dtype string to numpy dtype.""" return eval('np.' + s)
e0ff793404af5a8022d260fde5878329abbac483
706,086
from typing import Any from typing import get_origin def istype(obj: Any, annotation: type) -> bool: """Check if object is consistent with the annotation""" if get_origin(annotation) is None: if annotation is None: return obj is None return isinstance(obj, annotation) else: raise NotImplementedError("Currently only the basic types are supported")
c1903ea2ec6c0b6b9006a38f7c0720c88987b706
706,087
def get_file_info(repo, path): """we need change_count, last_change, nbr_committers.""" committers = [] last_change = None nbr_changes = 0 for commit in repo.iter_commits(paths=path): #print(dir(commit)) committers.append(commit.committer) last_change = commit.committed_date nbr_changes += 1 return nbr_changes, last_change, len(set(committers))
6ff99df399d35b79d0e2a5635b1e76e1f65fe0bd
706,088
import requests def __ping_url(url: str) -> bool: """Check a link for rotting.""" try: r = requests.head(url) return r.status_code in ( requests.codes.ok, requests.codes.created, requests.codes.no_content, requests.codes.not_modified, ) except Exception: return False
e680cec006127bbe889dcab0291be3149f30d10e
706,089
def duo_username(user): """ Return the Duo username for user. """ return user.username
92b2bfd5f6f3027787db493880139a8564597946
706,090
def parse_line(line,): """Return a list of 2-tuples of the possible atomic valences for a given line from the APS defining sheet.""" possap = [] for valence, entry in enumerate(line[4:]): if entry != "*": possap.append((valence, int(entry))) return possap
d27ed66cb35084c9927cae8658d7ea8a421c69a4
706,091
def decode(tokenizer, token): """decodes the tokens to the answer with a given tokenizer""" answer_tokens = tokenizer.convert_ids_to_tokens( token, skip_special_tokens=True) return tokenizer.convert_tokens_to_string(answer_tokens)
4bbb58a6a0ed0d33411f9beee35ad0f2fb43698f
706,092
def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True): """ Pads a rectangle by the specified values on each individual side, ensuring the padded rectangle falls within the specified bounds. The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). """ # Unpack the rectangle x, y, w, h = rect # Pad by the specified value x -= padLeft y -= padTop w += (padLeft + padRight) h += (padTop + padBottom) # Determine if we are clipping overflows/underflows or # shifting the centre of the rectangle to compensate if clipExcess == True: # Clip any underflows x = max(0, x) y = max(0, y) # Clip any overflows overflowY = max(0, (y + h) - bounds[0]) overflowX = max(0, (x + w) - bounds[1]) h -= overflowY w -= overflowX else: # Compensate for any underflows underflowX = max(0, 0 - x) underflowY = max(0, 0 - y) x += underflowX y += underflowY # Compensate for any overflows overflowY = max(0, (y + h) - bounds[0]) overflowX = max(0, (x + w) - bounds[1]) x -= overflowX w += overflowX y -= overflowY h += overflowY # If there are still overflows or underflows after our # modifications, we have no choice but to clip them x, y, w, h = padRect((x,y,w,h), 0, 0, 0, 0, bounds, True) # Re-pack the padded rect return (x,y,w,h)
032cafd373b59b725b8e2e28ba91e263ccae6e12
706,093
def extract(x, *keys): """ Args: x (dict or list): dict or list of dicts Returns: (tuple): tuple with the elements of the dict or the dicts of the list """ if isinstance(x, dict): return tuple(x[k] for k in keys) elif isinstance(x, list): return tuple([xi[k] for xi in x] for k in keys) else: raise NotImplementedError
c0730556786586011b0b22ae5003c2fe9ccb2894
706,095
import os import json def is_gcloud_oauth2_token_cached(): """Returns false if 'gcloud auth login' needs to be run.""" p = os.path.join(os.path.expanduser('~'), '.config', 'gcloud', 'credentials') try: with open(p) as f: return len(json.load(f)['data']) != 0 except (KeyError, IOError, OSError, ValueError): return False
8d02c1b41399d7f5c8550e4c0364108c251c3791
706,096
def _gen_off_list(sindx): """ Given a starting index and size, return a list of numbered links in that range. """ def _gen_link_olist(osize): return list(range(sindx, sindx + osize)) return _gen_link_olist
863ccdc08f6a7cadccc3c5ccfd0cb92a223aadda
706,097
def rationalize_quotes_from_table(table, rationalizeBase=10000): """ Retrieve the data from the given table of the SQLite database It takes parameters: table (this is one of the Quote table models: Open, High, Low, or Close) It returns a tuple of lists """ first_row = table.select().limit(1).get() rationalize_bull_1x_price = rationalizeBase / first_row.bull_1x_price rationalize_bear_1x_price = rationalizeBase / first_row.bear_1x_price rationalize_bull_3x_price = rationalizeBase / first_row.bull_3x_price rationalize_bear_3x_price = rationalizeBase / first_row.bear_3x_price indices = [] dates = [] bull_1x_prices = [] bear_1x_prices = [] bull_3x_prices = [] bear_3x_prices = [] for row in table.select(): indices.append(row.id) dates.append(row.date) bull_1x_prices.append(row.bull_1x_price * rationalize_bull_1x_price) bear_1x_prices.append(row.bear_1x_price * rationalize_bear_1x_price) bull_3x_prices.append(row.bull_3x_price * rationalize_bull_3x_price) bear_3x_prices.append(row.bear_3x_price * rationalize_bear_3x_price) return indices, dates, bull_1x_prices, bear_1x_prices, bull_3x_prices, bear_3x_prices
ee1c8310c12e7e53e9ca2677dd61d7d2525603fd
706,098
def k(func): """定义一个装饰器函数""" def m(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return m
3cc958033fd66547e523882435494f27ae81b096
706,099
import requests def get_playlist_object(playlist_url, access_token): """ playlist_url : url of spotify playlist access_token : access token gotten from client credentials authorization return object containing playlist tracks """ playlist_id = playlist_url.split("/")[-1] playlist_endpoint = f"https://api.spotify.com/v1/playlists/{playlist_id}" get_header = { "Authorization" : "Bearer " + access_token } # API request response = requests.get(playlist_endpoint, headers=get_header) playlist_object = response.json() return playlist_object
8c7ed1a1b9574e2e0870d3091452accf5909f982
706,100
import numpy as np def f_of_sigma(sigma,A=0.186,a=1.47,b=2.57,c=1.19): """ The prefactor in the mass function parametrized as in Tinker et al 2008. The default values of the optional parameters correspond to a mean halo density of 200 times the background. The values can be found in table 2 of Tinker 2008 ApJ 679, 1218 Parameters ---------- sigma: float Standard deviation of the linear power spectrum A,a,b,c: float, optional 0.186 by default Returns ------- f: float Value of f(sigma) """ f = A*((sigma/b)**(-a)+1)*np.exp(-c/sigma/sigma) return f
89abe82df8a4384e74eb556172c9d46193b731da
706,101
def value(iterable, key=None, position=1): """Generic value getter. Returns containing value.""" if key is None: if hasattr(iterable, '__iter__'): return iterable[position] else: return iterable else: return iterable[key]
df49496ab8fa4108d0c3d04035ffa318a9c6a035
706,102
def compact_interval_string(value_list): """Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15" """ if not value_list: return '' value_list.sort() # Start by simply building up a list of separate contiguous intervals interval_list = [] curr = [] for val in value_list: if curr and (val > curr[-1] + 1): interval_list.append((curr[0], curr[-1])) curr = [val] else: curr.append(val) if curr: interval_list.append((curr[0], curr[-1])) # For each interval collapse it down to "first, last" or just "first" if # if first == last. return ','.join([ '{}-{}'.format(pair[0], pair[1]) if pair[0] != pair[1] else str(pair[0]) for pair in interval_list ])
b479b45dc68a0bce9628a19be17185437f3edca6
706,103
def is_prime(num): """ Assumes num > 3 """ if num % 2 == 0: return False for p in range(3, int(num**0.5)+1, 2): # Jumps of 2 to skip odd numbers if num % p == 0: return False return True
e898026d0362967400cfee4e70a74ac02a64b6f1
706,104
def is_valid_orcid_id(orcid_id: str): """adapted from stdnum.iso7064.mod_11_2.checksum()""" check = 0 for n in orcid_id: check = (2 * check + int(10 if n == "X" else n)) % 11 return check == 1
5866e4465a24f46aa4c7015902eac53684da7b04
706,105
def calc_minimum_angular_variance_1d(var_r, phi_c, var_q): """Calculate minimum possible angular variance of a beam achievable with a correction lens. Args: var_r (scalar): real space variance. phi_c (scalar): real-space curvature - see above. var_q (scalar): angular variance of the beam. Returns: var_q_min (scalar): minimum possible angular variance of the beam. """ var_q_min = var_q - 4*phi_c**2/var_r return var_q_min
c5e2144f44b532acbf8eb9dfb83c991af3756abf
706,106
def calc_qpos(x, bit = 16): """ 引数の数値を表現できる最大のQ位置を返す。 :param x: float :return: int """ for q in range(bit): maxv = (2 ** (q - 1)) - 1 if x > maxv: continue return bit - q return bit
b85b458989425bc5698547cae93d8729bd452e76
706,107
def _follow_word_from_node(node, word): """Follows the link with given word label from given node. If there is a link from ``node`` with the label ``word``, returns the end node and the log probabilities and transition IDs of the link. If there are null links in between, returns the sum of the log probabilities and the concatenation of the transition IDs. :type node: Lattice.Node :param node: node where to start searching :type word: str :param word: word to search for :rtype: tuple of (Lattice.Node, float, float, str) :returns: the end node of the link with the word label (or ``None`` if the word is not found), and the total acoustic log probability, LM log probability, and transition IDs of the path to the word """ if word not in node.word_to_link: return (None, None, None, None) link = node.word_to_link[word] if link.word is not None: return (link.end_node, link.ac_logprob if link.ac_logprob is not None else 0.0, link.lm_logprob if link.lm_logprob is not None else 0.0, link.transitions if link.transitions is not None else "") end_node, ac_logprob, lm_logprob, transitions = \ _follow_word_from_node(link.end_node, word) if end_node is None: return (None, None, None, None) else: if link.ac_logprob is not None: ac_logprob += link.ac_logprob if link.lm_logprob is not None: lm_logprob += link.lm_logprob if link.transitions is not None: transitions += link.transitions return (end_node, ac_logprob, lm_logprob, transitions)
a21a20ee4ad2d2e90420e30572d41647b3938f4b
706,108
def rm_words(user_input, stop_words): """Sanitize using intersection and list.remove()""" # Downsides: # - Looping over list while removing from it? # http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python stop_words = set(stop_words) for sw in stop_words.intersection(user_input): while sw in user_input: user_input.remove(sw) return user_input
aead9c1cd5586bb20611ea8fbf57aa66aa3f5ede
706,110
def convert_xrandr_to_index(xrandr_val: float): """ :param xrandr_val: usually comes from the config value directly, as a string (it's just the nature of directly retrieving information from a .ini file) :return: an index representation of the current brightness level, useful for switch functions (where we switch based on indexes and not string values) Example: 0.2 is converted to 1 """ return int(xrandr_val * 10 - 1)
eed5f7a6c79f7dcb29c627521d31dc59e5cd430b
706,111
def get_message(name, value): """Provides the message for a standard Python exception""" if hasattr(value, "msg"): return f"{name}: {value.msg}\n" return f"{name}: {value}\n"
7755c63cc9a16e70ad9b0196d662ef603d82b5f6
706,112
import os def find_files(topdirs, py = False): """Lists all python files under any topdir from the topdirs lists. Returns an appropriate list for data_files, with source and destination directories the same""" ret = [] for topdir in topdirs: for r, _ds, fs in os.walk(topdir): ret.append((r, [ os.path.join(r, f) for f in fs if (f.endswith('.py') or not py)])) return ret
b273d067bb6237a8c7bb9950aa7c764854f1124b
706,113
def merge_dict_recursive(base, other): """Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively). >>> base = {'a': 1, 'b': {'c': 3}} >>> other = {'x': 4, 'b': {'y': 5}} >>> want = {'a': 1, 'x': 4, 'b': {'c': 3, 'y': 5}} >>> got = merge_dict_recursive(base, other) >>> got == want True >>> base == want True """ for (key, value) in list(other.items()): if (isinstance(value, dict) and (key in base) and (isinstance(base[key], dict))): base[key] = merge_dict_recursive(base[key], value) else: base[key] = value return base
10ea2bbcf7d2ee330c784efff684974339d48b5d
706,114
def url_path_join(*items): """ Make it easier to build url path by joining every arguments with a '/' character. Args: items (list): Path elements """ return "/".join([item.lstrip("/").rstrip("/") for item in items])
d864c870f9d52bad1268c843098a9f7e1fa69158
706,115
def utf8_german_fix( uglystring ): """ If your string contains ugly characters (like ü, ö, ä or ß) in your source file, run this string through here. This adds the German "Umlaute" to your string, making (ÄÖÜäöü߀) compatible for processing. \tprint( utf8_german_fix("ü߀") ) == ü߀ """ uglystring = uglystring.replace('ü','ü') uglystring = uglystring.replace('ö','ö') uglystring = uglystring.replace('ä','ä') uglystring = uglystring.replace('Ä','Ä') uglystring = uglystring.replace('Ö','Ö') uglystring = uglystring.replace('Ü','Ü') uglystring = uglystring.replace('ß','ß') # This was born out of necessity, as there were some issues with a certain API not processing German properly. # I am always looking for a smarter way to do this. nicestring = uglystring.replace('€','€') return nicestring
7ed12d819b384e3bb5cb019ce7b7afe3d6bb8b86
706,116
import os import sys def get_pcgr_bin(): """Return abs path to e.g. conda/env/pcgr/bin """ return os.path.dirname(os.path.realpath(sys.executable))
abd85ffc2ad348e2c5dee260561e1da2b18efca4
706,117
def _test(value, *args, **keywargs): """ A function that exists for test purposes. >>> checks = [ ... '3, 6, min=1, max=3, test=list(a, b, c)', ... '3', ... '3, 6', ... '3,', ... 'min=1, test="a b c"', ... 'min=5, test="a, b, c"', ... 'min=1, max=3, test="a, b, c"', ... 'min=-100, test=-99', ... 'min=1, max=3', ... '3, 6, test="36"', ... '3, 6, test="a, b, c"', ... '3, max=3, test=list("a", "b", "c")', ... '''3, max=3, test=list("'a'", 'b', "x=(c)")''', ... "test='x=fish(3)'", ... ] >>> v = Validator({'test': _test}) >>> for entry in checks: ... print v.check(('test(%s)' % entry), 3) (3, ('3', '6'), {'test': ['a', 'b', 'c'], 'max': '3', 'min': '1'}) (3, ('3',), {}) (3, ('3', '6'), {}) (3, ('3',), {}) (3, (), {'test': 'a b c', 'min': '1'}) (3, (), {'test': 'a, b, c', 'min': '5'}) (3, (), {'test': 'a, b, c', 'max': '3', 'min': '1'}) (3, (), {'test': '-99', 'min': '-100'}) (3, (), {'max': '3', 'min': '1'}) (3, ('3', '6'), {'test': '36'}) (3, ('3', '6'), {'test': 'a, b, c'}) (3, ('3',), {'test': ['a', 'b', 'c'], 'max': '3'}) (3, ('3',), {'test': ["'a'", 'b', 'x=(c)'], 'max': '3'}) (3, (), {'test': 'x=fish(3)'}) """ return (value, args, keywargs)
c011c9386392c4b8dc8034fee33bfcfdec9845ed
706,119
def format_sample_case(s: str) -> str: """format_sample_case convert a string s to a good form as a sample case. A good form means that, it use LR instead of CRLF, it has the trailing newline, and it has no superfluous whitespaces. """ if not s.strip(): return '' lines = s.strip().splitlines() lines = [line.strip() + '\n' for line in lines] return ''.join(lines)
cd691f2bfc8cc56db85f2a55ff3bf4b5afd5f30e
706,120
def load_room(name): """ There is a potential security problem here. Who gets to set name? Can that expose a variable? """ return globals().get(name)
14034adf76b8fd086b798cd312977930d42b6e07
706,121
def find_node_name(node_id, g): """Go through the attributes and find the node with the given name""" return g.node[node_id]["label"]
a4656659aeef0427a74822991c2594064b1a9411
706,122
def basic_pyxll_function_3(x): """docstrings appear as help text in Excel""" return x
3709d1bce92456b1456ed90d81002f71b7d9e754
706,123