content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy def toCol( v ): """ v is a vector """ return numpy.matrix( v.reshape(v.size,1) )
64deae90f617f223aa42abc98236a49a3032f30b
21,546
import warnings def _check_for_expected_keys(_dict, expected_keys, place="session", raise_error=False): """ ensures that all of the expected keys are in place """ missing_elements = [] for elem in expected_keys: if elem not in _dict.keys(): if raise_error: raise ValueError("{} not in {}".format(elem, place)) else: warnings.warn("{} not in {}".format(elem, place)) missing_elements.append(elem) # check for unexpected elements for elem in _dict.keys(): if elem not in expected_keys: warnings.warn("{} not an expected element in {}".format(elem, place)) return missing_elements
bc2365a2fd7f6eeac18739a438f8abf821d16173
21,547
import subprocess import shlex import pathlib def get_gmx_dir(): """Find absolute location of the gromacs shared library files This function uses a quick and dirty approach: GROMACS is called and stdout is parsed for the entries 'Executable' and 'Data prefix'. """ call = 'gmx -h' try: feedback = subprocess.run( shlex.split(call), stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8' ) except FileNotFoundError: return None, None if feedback.returncode != 0: return None, None _feedback = feedback.stderr.split('\n') gmx_exe = None gmx_shared = None for line in _feedback: if line.startswith('Executable'): gmx_exe = pathlib.Path(line.split()[-1]) if line.startswith('Data prefix'): gmx_shared = pathlib.Path(line.split()[-1]) / 'share/gromacs/top' return gmx_exe, gmx_shared
8f462cd3f506683b9a8146e11da6ce2b1aec38a7
21,549
def maxintegervalue(input): """ Function Docstring """ totalsum = 0 totalmult = 1 negative = False for c in input: # Reading one character at a time if c == '-': # cheking negative = True else: totalsum += int(c) totalmult *= int(c) if negative is True: totalsum = -1 * totalsum totalmult = -1 * totalmult return max(totalsum, totalmult)
6522898b3ae567e9560367a88dfdc0fe7d0a3359
21,550
import re def word_count(text: str) -> int: """ Counts the total words in a string. Parameters ------------ text: str The text to count the words of. Returns ------------ int The number of words in the text. """ list_words = re.split(' |\n|\t', text) #Splits along spaces list_words = list(filter(str.strip, list_words)) return len(list_words)
869afd06172c9ffb61430489804cac20706ca245
21,551
def tobin(i): """ Maps a ray index "i" into a bin index. """ #return int(log(3*y+1)/log(2))>>1 return int((3*i+1).bit_length()-1)>>1
a32bf5895071ac111bbd0c76a3fa8b630feb252d
21,552
def get_model_path(model): """Return the qualified path to a model class: 'model_logging.models.LogEntry'.""" return '{}.{}'.format(model.__module__, model.__qualname__)
ab6b631aa4fb3acac0355c587f792441ecf25702
21,553
from datetime import datetime import random def tweet_content(): """Generate tweet string (140 characters or less) """ # potential responses yes_opts = [ 'YEAAAA', 'awwww yea', 'you betcha', 'BOOYAH', 'well, whatdya know?', 'does a giraffe have a long neck?', 'how about that?!', 'yes' ] no_opts = [ 'no', 'of course not', 'big tall glass of nope', 'how about no, scott', 'hang tight', 'gotta wait it out', 'yes, if today is also opposite day', 'nope nope nope nope', 'nuh uh', 'inconceivably, no', 'def no' ] # check Thursday (= 3) against current weekday (Monday=0) if datetime.now().weekday() == 3: return random.choice(yes_opts) else: return random.choice(no_opts)
3121704ab53082263ea541cbc3dde38e371441d6
21,554
from typing import List from typing import Tuple from typing import Optional import sys def get_macros() -> List[Tuple[str, Optional[str]]]: """ returns list of macros that the extension needs to define """ if sys.platform == "win32": return [("_WIN32", None)] return []
0ec219a40b2a334da79a49d108f6d24d00371685
21,557
def get_image_data(image): """ Return a mapping of Image-related data given an `image`. """ exclude = ["base_location", "extracted_to_location", "layers"] image_data = { key: value for key, value in image.to_dict().items() if key not in exclude } return image_data
684cd2a358599b161e2311f88c3e84c016ad2fef
21,558
def proceed() -> bool: """ Ask to prooceed with extraction or not """ while True: response = input("::Proocced with extraction ([y]/n)?") if response in ["Y", "y", ""]: return True elif response in ["N", "n"]: return False else: continue
6d4c93ee7a216d9eb62f565657cf89a2e829dd30
21,559
def clean_input(text): """ Text sanitization function :param text: User input text :return: Sanitized text, without non ascii characters """ # To keep things simple at the start, let's only keep ASCII characters return str(text.encode().decode("ascii", errors="ignore"))
974a24e4d516faac650a9899790b66ebe29fc0a2
21,560
def ua_mock(ua_mocks): """Generate a single ua mock w/o connection to a ctrl.""" return ua_mocks[0]
0e68c16f7cef444b58704ff30af0c1971112eb31
21,562
import torch def normalize_tensor_by_standard_deviation_devision(tensor): """Normalize tensor by dividing thorugh its standard deviation. Args: tensor (Tensor): Input tensor. Returns: Tensor: Normalized input tensor. """ mean = torch.std(tensor) tensor = tensor.div(mean) return tensor
bdb17853adcc569e04d11e34cffeec1759633111
21,563
import requests def get_player_stats_from_pfr(player_url, year): """ Function that returns the HTML content for a particular player in a given NFL year/season. :param player_url: URL for the player's Pro Football Reference Page :param year: Year to access the player's stats for :return: String containing all content of the player's gamelogs for the given year """ get_url = player_url + year response = requests.get(get_url) return response.content
d6e4b34de9498dd8dff80bf5e6bd0bdc9f44255b
21,564
def euclidean_rhythm(beats, pulses): """Computes Euclidean rhythm of beats/pulses From: https://kountanis.com/2017/06/13/python-euclidean/ Examples: euclidean_rhythm(8, 5) -> [1, 0, 1, 0, 1, 0, 1, 1] euclidean_rhythm(7, 3) -> [1, 0, 0, 1, 0, 1, 0] Args: beats (int): Beats of the rhythm pulses (int): Pulses to distribute. Should be <= beats Returns: list: 1s are pulses, zeros rests """ if pulses is None or pulses < 0: pulses = 0 if beats is None or beats < 0: beats = 0 if pulses > beats: beats, pulses = pulses, beats if beats == 0: return [] rests = beats - pulses result = [1] * pulses pivot = 1 interval = 2 while rests > 0: if pivot > len(result): pivot = 1 interval += 1 result.insert(pivot, 0) pivot += interval rests -= 1 return result
c1ded4891dfc658a4ba1e92db7b736c70f25f4f5
21,566
def get_bits_from_bytes(int_value, index, size): """ :param int_value: The integer from which to extract bits. :param index: Start index of value to extract from data. Least significant bit of data is index zero. :param size: Size in bits of the value to extract from data. :return: The extracted bits. """ if index < 0 or size < 0: raise RuntimeError("Index and size provided to get_bits_from_bytes must be positive. Index: {0}, size: {1}".format(index, size)) num_bits = 32 if index + size > num_bits: raise RuntimeError("Invalid values provided to get_bits_from_bytes. Size + index must be less than or equal to size in bit of data.\nSize of data: {0} bits, size of field: {1} bits, index: {2}".format(num_bits, size, index)) int_value >>= index mask = (1 << size) - 1 return int_value & mask
4b9c2d51bb509d872f122fbf91966ceadb109a77
21,567
import csv def get_device_name(file_name, sys_obj_id, delimiter=":"): """Get device name by its SNMP sysObjectID property from the file map. :param str file_name: :param str sys_obj_id: :param str delimiter: :rtype: str """ try: with open(file_name) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: if len(row) >= 2 and row[0] == sys_obj_id: return row[1] except OSError: pass # file does not exist return sys_obj_id
3074dffc5274d882bb99c13a0e642b05fd68cb9c
21,568
def get_replaces_to_rule(rules): """Invert rules dictionary to list of (replace, rule) tuples.""" replaces = [] for rule, rule_replaces in rules.items(): for replace in rule_replaces: replaces.append((replace, rule)) return replaces
de3fd8235eb8926682544def49de500412ee3084
21,569
def query_epo_desc_table(src_table: str): """ Return the query generating the aggregate table to compute descriptive statistics on the EPO full text database :param src_table: str, table path to EPO full-text database on BigQuery e.g. 'project.dataset.table' :return: str """ query = f""" WITH tmp AS ( SELECT publication_number AS publication_number, publication_date, title.text IS NOT NULL AS has_title, title.LANGUAGE AS title_language, abstract.text IS NOT NULL AS has_abstract, abstract.LANGUAGE AS abstract_language, description.text IS NOT NULL AS has_description, description.LANGUAGE AS description_language, claims.text IS NOT NULL AS has_claims, claims.LANGUAGE AS claims_language, amendment.text IS NOT NULL AS has_amendment, amendment.LANGUAGE AS amendment_language, url.text IS NOT NULL AS has_url, url.LANGUAGE AS url_language, FROM `{src_table}`) SELECT family_id AS family_id, tmp.* FROM tmp, `patents-public-data.patents.publications` AS p WHERE tmp.publication_number = p.publication_number """ return query
20f114cc4c54e03261362458140b2f7bc7318ea4
21,570
def _get_metadata_map_from_client_details(client_call_details): """Get metadata key->value map from client_call_details""" metadata = {metadatum[0]: metadatum[1] for metadatum in (client_call_details.metadata or [])} return metadata
1d0b843b41f2777685dad13b9269410033086b02
21,571
def snake_to_camel_case(name: str, initial: bool = False) -> str: """Convert a PEP8 style snake_case name to CamelCase.""" chunks = name.split('_') converted = [s.capitalize() for s in chunks] if initial: return ''.join(converted) else: return chunks[0].lower() + ''.join(converted[1:])
1669c0a1065da8133771d83ebbc7ed4c393d4a8f
21,572
def get_mock_mysql_conn_info(): """mock mysql的连接信息""" return '{"host": "host.host", "password": "pwd", "port": 3306, "user": "user.user"}'
4adc01897600118ddbc37876ba5fa524ba2466ff
21,573
def get_detector_information(ifo): """ Return information on selected detector ------ ifo: str The two-character detector string, i.e. H1, L1, V1, K1, G1 ______ latitude, longitude, elevation, xarm_azimuth, yarm_azimuth, xarm_tilt, yarm_tilt """ if ifo=='H1': latitude = 0.81079526383 longitude = -2.08405676917 elevation = 142.554 xarm_azimuth = 2.1991043855 yarm_azimuth = 3.7699007123 xarm_tilt = -6.195e-4 yarm_tilt = 1.25e-5 elif ifo=='L1': latitude = 0.53342313506 longitude = -1.58430937078 elevation = -6.574 xarm_azimuth = 3.4508039105 yarm_azimuth = 5.0216002373 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='V1': latitude = 0.76151183984 longitude = 0.18333805213 elevation = 51.884 xarm_azimuth = 1.2316334746 yarm_azimuth = 2.8024298014 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='K1': latitude = 0.6355068497 longitude = 2.396441015 elevation = 414.181 xarm_azimuth = 0.5166831721 yarm_azimuth = 2.0874762035 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='G1': latitude = 0.91184982752 longitude = 0.17116780435 elevation = 114.425 xarm_azimuth = 2.02358884 yarm_azimuth = 0.377195322 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='I1': latitude = 0.2484185302005 longitude = 1.334013324941 elevation = 0. xarm_azimuth = 2.1991043855 yarm_azimuth = 3.7699007123 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='ET': latitude = 0.76151183984 longitude = 0.18333805213 elevation = 51.884 xarm_azimuth = 1.2316334746 yarm_azimuth = 2.2788310258 xarm_tilt = 0. yarm_tilt = 0. elif ifo=='CE': latitude = 0.81079526383 longitude = -2.08405676917 elevation = 142.554 xarm_azimuth = 2.1991043855 yarm_azimuth = 3.7699007123 xarm_tilt = -6.195e-4 yarm_tilt = 1.25e-5 else: raise ValueError("Can't get information from input detector.\n Please check you use a correct name, i.e. H1, L1, V1, K1, G1") return latitude, longitude, elevation, xarm_azimuth, yarm_azimuth, xarm_tilt, yarm_tilt
cf634a806256af3966e28828163743bcd79608bd
21,575
def filter_default(input_dict, params_default): """ Filter input parameters with default params. :param input_dict: input parameters :type input_dict : dict :param params_default: default parameters :type params_default : dict :return: modified input_dict as dict """ for i in params_default.keys(): if i not in input_dict.keys(): input_dict[i] = params_default[i] return input_dict
5cae639c2a18c6db7a858ebe4ce939bf551088c2
21,577
def propose_placements(block, grid, z): """ Returns a mapping of a block to each point in the grid. """ f = lambda point : block.moveto(point, z) return list(map(f, grid))
489f90a8d1335d08dc43cd9c7d62ba2dc743392c
21,578
def is_even(n): """Determines whether `n` is even """ # even = n % 2 == 0 even = not(n & 1) return even
cfb0d961bf456fe84b99ba3dd81ec34b2bdd4f2f
21,579
import time def minutesTillBus(busTimepoint, nowTime = None): """ given a bus timepoint record from getTimepointDepartures, return the number of minutes until that bus, as a float. nowTime is the current time since unix epoch, but leave it out to just use the system time. """ t = busTimepoint["DepartureTime"] if nowTime is None: nowTime = time.time() secondsFromNow = float(t[6:-2].split('-')[0])/1000.0 - nowTime return secondsFromNow / 60.0
b26f194fd07160a2e7b2d5a059a6242af636d1fe
21,580
import base64 def read_file_as_b64(image_path): """ Encode image file or image from zip archive to base64 Args: image_path (bytes or str): if from a zip archive, it is an image in bytes; if from local directory, it should be a string specifying the filepath Returns: b64_string (str): encoded image file ready to be sent to server """ # If input is from zip archive, it will be in bytes if type(image_path) is bytes: b64_bytes = base64.b64encode(image_path) else: # Or it is from a directory with open(image_path, "rb") as image_file: b64_bytes = base64.b64encode(image_file.read()) b64_string = str(b64_bytes, encoding='utf-8') return b64_string
516200ba2c7a129f236c92dbf7952592f449b6e3
21,581
from typing import Iterable import functools def prod(iterable: Iterable[int]) -> int: """ Calculates the product of an iterable. In Python 3.8 this can be replaced with a call to math.prod """ return functools.reduce(lambda x, y: x * y, iterable)
219aec67b87fb1b4b16e6d4e70f8d1deca3a4388
21,582
def vstat(self, **kwargs): """Lists the current specifications for the array parameters. APDL Command: *VSTAT Notes ----- Lists the current specifications for the *VABS, *VCOL, *VCUM, *VFACT, *VLEN, and *VMASK commands. This command is valid in any processor. """ command = f"*VSTAT," return self.run(command, **kwargs)
06dbe878cb688b6ac2ccf9fb9f48e3629fa73c09
21,583
def read_bytes_sync(sock, nbytes): """ Read number of bytes from a blocking socket This is not typically used, see IOStream.read_bytes instead """ frames = [] while nbytes: frame = sock.recv(nbytes) frames.append(frame) nbytes -= len(frame) if len(frames) == 1: return frames[0] else: return b''.join(frames)
5e311824b3a1eb8765b8ac7bda692b35bda59839
21,584
def return_int(user_input): """Function to check and return an integer from user input""" try: user_int = int(user_input) except ValueError: print("Oops! Not a valid integer format.") else: return user_int
01dccefb92e3b854029ec6100a11d02bc51af240
21,585
def get_clusterID(filename): """given a file name return the cluster id""" return filename.split(".")[0]
43de7ab212d41d4e7c1d40e6dadb988c178db1f4
21,586
def flatten_json(obj: dict) -> dict: """ Flatten json obj; doesn't handle lists """ out = {} def flatten(obj, name=""): if type(obj) is dict: for key, value in obj.items(): flatten(value, name + key + "_") else: out[name[:-1]] = obj flatten(obj) return out
98320015557c7dabc0ab6eecff6013791c2f6b6b
21,588
def postWidth(thread, post): """:return number of columns to fill""" return '11' if all(p != thread.op for p in (post, post.parent)) else '12'
a00480d1eb2e34058fc52f3d133c54b13e1eef35
21,589
def selectionSort(array): """returns sorted array""" length = len(array) for i in range(length - 1): unsortedElementIdx = i minElementIdx = i+1 for j in range(i+1, length): if array[j] < array[minElementIdx]: minElementIdx = j if array[minElementIdx] < array[unsortedElementIdx]: array[minElementIdx], array[unsortedElementIdx] = array[unsortedElementIdx], array[minElementIdx] return array
7da9af1e913411f2f74c904383f55304bf11c4c0
21,590
def tag_to_string(gallery_tag, simple=False): """ Takes gallery tags and converts it to string, returns string if simple is set to True, returns a CSV string, else a dict-like string """ assert isinstance(gallery_tag, dict), "Please provide a dict like this: {'namespace':['tag1']}" string = "" if not simple: for n, namespace in enumerate(sorted(gallery_tag), 1): if len(gallery_tag[namespace]) != 0: if namespace != 'default': string += namespace + ":" # find tags if namespace != 'default' and len(gallery_tag[namespace]) > 1: string += '[' for x, tag in enumerate(sorted(gallery_tag[namespace]), 1): # if we are at the end of the list if x == len(gallery_tag[namespace]): string += tag else: string += tag + ', ' if namespace != 'default' and len(gallery_tag[namespace]) > 1: string += ']' # if we aren't at the end of the list if not n == len(gallery_tag): string += ', ' else: for n, namespace in enumerate(sorted(gallery_tag), 1): if len(gallery_tag[namespace]) != 0: if namespace != 'default': string += namespace + "," # find tags for x, tag in enumerate(sorted(gallery_tag[namespace]), 1): # if we are at the end of the list if x == len(gallery_tag[namespace]): string += tag else: string += tag + ', ' # if we aren't at the end of the list if not n == len(gallery_tag): string += ', ' return string
654628eee6938adfdd24b261927869b011ee927d
21,591
import os def scriptdir(): """ Returns the directory where this script is located. """ return os.path.dirname(os.path.realpath(__file__))
cb9a02188c9ce53b371d60d26ce8ae1f6f9b498f
21,592
import json def to_json(value): """A filter that outputs Python objects as JSON""" return json.dumps(value)
386a27290c2f9e1f0a926143bc7e54e2ca98912b
21,594
def apply_gradient(main_image, gradient_img, gradient_alpha): """ The gradient on the image is overlayed so that text looks visible and clear. This leaves a good effect on the image. Args: main_image (Image): The main image where gradient has to be applied gradient_img (Image): The gradient image gradient_alpha (Numpy.Array): The 4th channel, the alpha channel of the gradient Returns: Image: Gradient applied image """ for channel in range(0, 4): main_image[-gradient_img.shape[0] :, -gradient_img.shape[1] :, channel] = ( gradient_alpha * gradient_img[:, :, channel] ) + (1 - gradient_alpha) * ( main_image[-gradient_img.shape[0] :, -gradient_img.shape[1] :, channel] ) return main_image
38b164203faa6d82919dc0f3033099babfdec5a7
21,596
def get_mac_addr_from_dbus_path(path): """Return the mac addres from a dev_XX_XX_XX_XX_XX_XX dbus path""" return path.split("/")[-1].replace("dev_", '').replace("_", ":")
a8603f2f7b6202ab9bafe5f911606efd8dc54358
21,599
import typing def compute_parent( tour_edges: typing.List[int], ) -> typing.List[typing.Optional[int]]: """Compute parent from Euler-tour-on-edges. Args: tour_edges (typing.List[int]): euler tour on edges. Returns: typing.List[typing.Optional[int]]: parent list. the tour root's parent is None. Examples: >>> tour_edges = [0, 1, 4, -5, 2, -3, -2, 3, -4, -1] >>> compute_parent(tour_edges) [None, 0, 1, 0, 1] """ n = len(tour_edges) >> 1 parent: typing.List[typing.Optional[int]] = [None] * n st = [tour_edges[0]] for u in tour_edges[1:]: if u < 0: st.pop() continue parent[u] = st[-1] st.append(u) return parent
5887a22faf42fae32b81fab902de9490c5dc4b00
21,600
import tempfile import os def temporary_file(request): """Return a temporary file path.""" file_handle, path = tempfile.mkstemp() os.close(file_handle) def cleanup(): """Remove temporary file.""" try: os.remove(path) except OSError: pass request.addfinalizer(cleanup) return path
647eda7ca7f0e8e6c9562df2b9f341359a268403
21,601
from typing import Optional def build_netloc(host: str, port: Optional[int] = None) -> str: """Create a netloc that can be passed to `url.parse.urlunsplit` while safely handling ipv6 addresses.""" escaped_host = f"[{host}]" if ":" in host else host return escaped_host if port is None else f"{escaped_host}:{port}"
56e44584b2f5e76142c40b639919951772f75aed
21,602
import numpy def _gsa_acceleration(total_force, mass): """Convert force to acceleration, given mass. In GSA paper, mass is M_i """ return numpy.divide(total_force, mass)
7b25b72ac04fbb35a7e75effee799782b00be755
21,603
def Nullable(oftype): """Generate a converter that may be None, or :oftype. field = Nullable(DateConverter) would expect either null or something to convert to date""" def _(it): if it is None: return None else: return oftype(it) return _
375e37f7f8ddd41e187e26900d17bfca3b97d788
21,604
import collections def entries_dict_ids_argument(entries_dict): """Add entries in dictionary.""" entries_dict_ids = collections.defaultdict(dict) for entry_id, entry_att in entries_dict.items(): entry_identifiers = {} for label, value in entry_att.items(): if 'bdb' in label: entry_identifiers[label] = value else: entries_dict_ids[entry_id][label] = value entries_dict_ids[entry_id]['identifiers'] = entry_identifiers return entries_dict
b6d04d4ad0d92e0cc2c645ce5814c088301516a8
21,605
def _fix_data(cube, var): """Specific data fixes for different variables.""" mll_to_mol = ['po4', 'si', 'no3'] if var in mll_to_mol: cube.data = cube.data / 1000. # Convert from ml/l to mol/m^3 if var == 'o2': cube.data = cube.data * 44.661 / 1000. # Convert from ml/l to mol/m^3 return cube
4fef0ba57f37cc6f037ef6b7b24f815401f8836d
21,606
def error404(e): """ 404 error handler. """ return ''.join([ '<html><body>', '<h1>D20 - Page Not Found</h1>', '<p>The only endpoint available on this entropy micro-service is <a href="/api/entropy">/api/entropy</a>.</p>', '<p>For more information including the complete source code, visit <a href="https://github.com/AgalmicVentures/D20">the D20 repository</a>.</p>', '</body></html>', ]), 404
35ab121b88e84295aaf97e2d60209c17acffd84d
21,607
import torch def one_cls_dice(output, target, label_idx): """ Calculate Dice metrics for one channel :param output:Output dimension: Batch x Channel x X x Y (x Z) float :param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel] :param label_idx: :return: """ eps = 0.0001 with torch.no_grad(): pred = torch.argmax(output, 1) pred_bool = (pred == label_idx) target_bool = (target == label_idx) intersection = pred_bool * target_bool return (2 * int(intersection.sum())) / (int(pred_bool.sum()) + int(target_bool.sum()) + eps)
7a9cb628348571320911e1ec86d222d98751fd4a
21,608
import string import random def id_generator( size=6, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits ): """ Creates a unique ID consisting of a given number of characters with a given set of characters """ return ''.join(random.choice(chars) for _ in range(size))
9a6bf02c63e5ad933340be70e95c812683a69dee
21,609
import sys import subprocess def runTestWithPython(display_name, executable): """ Runs `$(PYTHON) setup.py test -q` """ cmd = '%s setup.py test -q' % executable sys.stdout.write(' Running tests against %s ... ' % display_name) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() retcode = p.poll() if retcode == 0: sys.stdout.write('OK\n') return True else: sys.stdout.write('FAILED\n') sys.stdout.write(stdout.decode('ascii', 'ignore')) sys.stdout.write(stderr.decode('ascii', 'ignore')) return False
691599a748acde390dc96ef3570b7b2f977a0bf2
21,610
def convert_hubs_to_datastores(hubs, datastores): """Get filtered subset of datastores as represented by hubs. :param hubs: represents a sub set of datastore ids :param datastores: represents all candidate datastores :returns: that subset of datastores objects that are also present in hubs """ hubIds = [hub.hubId for hub in hubs] filtered_dss = [ds for ds in datastores if ds.value in hubIds] return filtered_dss
14e7231f9c6a1e273c217bf77b8a7d3b3632709c
21,611
import six def is_number(value): """:yaql:isNumber Returns true if value is an integer or floating number, otherwise false. :signature: isNumber(value) :arg value: input value :argType value: any :returnType: boolean .. code:: yaql> isNumber(12.0) true yaql> isNumber(12) true """ return (isinstance(value, six.integer_types + (float,)) and not isinstance(value, bool))
13c66d47990fc54ccf0843776f0bc83d810f81fe
21,612
def inspect_chain(chain): """Return whether a chain is 'GOOD' or 'BAD'.""" next_key = chain.pop('BEGIN') while True: try: next_key = chain.pop(next_key) if next_key == "END": break except KeyError: return "BAD" if len(chain) > 0: return "BAD" return "GOOD"
083886aa31fa81cc90d4c7bd30149c5575a5a675
21,613
def _delta_to_str(delta): """ Pretty-print timedelta for emails :param delta: a timedelta object """ seconds = abs(int(delta.total_seconds())) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) parts = [] if days > 0: parts.append('%dd' % days) if hours > 0: parts.append('%dh' % hours) if minutes > 0: parts.append('%dm' % minutes) if seconds > 0: parts.append('%ds' % seconds) return ', '.join(parts)
978196b1cb1e8f19172554bfcc210e086dda417c
21,614
def longuest_sub_array(arr): """ This function caculates the longuest sub array in a list A sub array is an array which doesn't contain any 0 It returns the index of the last element which composes the sub array and the length of the sub array """ sub_arrays = [] last_index = 0 length = 0 for i,l in enumerate(arr): if l != 0 : length += 1 last_index = i else: if last_index == i-1: sub_arrays.append((last_index, length)) length=0 if sub_arrays == [(0,0)]: print('The image cannot be cropped vertically') return None return max(sub_arrays, key=lambda p: p[1])
233ad72b773514b66063e993e2d283b910d52dd1
21,615
def get_content_type(request): """Return the MIME content type giving the request Return `None` if unknown. """ if hasattr(request, 'content_type'): conttype = request.content_type else: header = request.META.get('CONTENT_TYPE', None) if not header: return None conttype = header.partition(';')[0] # remove ";charset=" return conttype
f355a2bef6cfc130a6ae897701fff6b2f037040d
21,619
import os def load_npy(ds) -> str: """The statement that imports a NumPy NPY file into Veusz. """ if os.name == "nt": fpath = str(ds.path.resolve()).replace('\\', '\\\\') else: fpath = str(ds.path.resolve()) return f"ImportFilePlugin(u'Numpy NPY import', u'{fpath}', linked=True, name=u'{ds.name}')"
96a9a725e03b40bb60db24eef7abdc698581674f
21,620
def send_files_sftp(con, filepaths, remote_path): """ Send a list of files to the provided remote path via SFTP. Unspecified (read: all) exceptions result in the remaining files not uploading. :param con: a connected Paramiko client :param list filepaths: list of pathlib Path objects :param str remote_path: remote path to send all files to :return list: list of booleans of which plots uploaded sucessfully """ bools = [] try: con.chdir(remote_path) for file in filepaths: try: con.put(str(file), file.name) bools.append(True) except Exception: bools.append(False) except Exception: while len(bools) < len(filepaths): bools.append(False) return bools
163945d8b62a256bab9100c3d29fa7a75208054c
21,621
def get_seamus_id_from_url(url): """ gets seamus ID from URL """ if url.startswith('http://www.npr.org') or url.startswith('http://npr.org'): url_parts = url.split('/') id = url_parts[-2] if id.isdigit(): return id return None
90aa3bdd7042d3c2badbddd508cf824215917a66
21,623
def hex(string): """ Convert a string to hex. """ return string.encode('hex')
66ff8fe8797c840d5471dbb4693e0ae6ef32fb8e
21,624
import ast def literal(str_field: str): """ converts string of object back to object example: $ str_literal('['a','b','c']') ['a', 'b', 'c'] # type is list """ return ast.literal_eval(str_field)
25d23f55e52cdb4727f157a3db13614932bcbec7
21,626
def tail_logfile(logfile=''): """Read n lines of the logfile""" result = "Can't read logfile: {}".format(logfile) lines = 40 with open(logfile) as f: # for line in (f.readlines()[-lines:]): # print(line) result = ''.join(f.readlines()[-lines:]) return result
61a4046d2a7bfb8be907a325253424b2d425b410
21,627
from typing import Dict from typing import Any from typing import Optional import requests def request_data(url: str, params: Dict[str, Any]) -> Optional[str]: """Request data about energy production from Entsoe API. Args: url (str): Entsoe API url. params (Dict[str, str]): Parameters for the API get requests. Returns: Optional[str]: If response status is ok returns xml response as a string. """ headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:83.0) Gecko/20100101 Firefox/83.0' } r = requests.get(url, params=params, headers=headers) if r.status_code == 200: return r.text return None
187d134f3457616d830ec5c78b02a11f880c981e
21,629
import argparse import sys def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser( description='Evaluate a Faster R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--output_dir', dest='output_dir', help='output directory', default=None, type=str) parser.add_argument('--input_dir', dest='input_dir', help=('the dir should have image_list,' 'label_list, and label_name three files.' 'See github wiki'), default=None, type=str) parser.add_argument('--model_dir', dest='model_dir', help=('caffe network prototxt dir.' 'Trained model weights should exist.' 'cfg_file should also exist.'), default=None, type=str) parser.add_argument('--eval_result_name', dest='eval_result_name', help='the name of the evaluation result folder') parser.add_argument('--comp', dest='comp_mode', help='competition mode', action='store_true') if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
789a20b362d077dfc8a680acf408fba2f7dfff7c
21,630
def minimum_katcp_version(major, minor=0): """Decorator; exclude handler if server's protocol version is too low Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions Examples -------- >>> class MyDevice(DeviceServer): ... '''This device server will expose ?myreq''' ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 1) ... ... @minimum_katcp_version(5, 1) ... def request_myreq(self, req, msg): ... '''A request that should only be present for KATCP >v5.1''' ... # Request handler implementation here. ... >>> class MyOldDevice(MyDevice): ... '''This device server will not expose ?myreq''' ... ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0) ... """ version_tuple = (major, minor) def decorator(handler): handler._minimum_katcp_version = version_tuple return handler return decorator
bcaefb29af78400cd283895fef0d4fd94f175112
21,631
def keep_adding_nums(): """ 047 Ask the user to enter a number and then enter another number. Add these two numbers together and then ask if they want to add another number. If they enter “y", ask them to enter another number and keep adding numbers until they do not answer “y”. Once the loop has stopped, display the total. """ num1 = int(input("Entrer une chifre: ")) num2 = int(input("Entrer un'autre chifre: ")) total = num1 + num2 trigger = False while not trigger: answer = input("Voulez-vous entrer un'autre chifre?: ") if answer == "y": num_x = int(input("Entrer un'autre chifre: ")) total += num_x else: trigger = True return f"Total: {total}"
b1fdd699ed583932c6990694fd93591cbfabd12d
21,632
def newick_to_json(newick_string, namestring = "id", lengthstring = "branch_length", childrenstring = "children", generate_names=False): """Parses a newick string (example "((A,B),C)") into JSON format accepted by NetworkX Args: newick_string: The newick string to convert to JSON. Names, branch lengths and named internal nodes accepted. If no names are given, an ID is generated for the name if generate_names=True. namestring: The label for node name to use in the JSON (default "id"). lengthstring: The label for branch length to use in the JSON (default "branch_length"). childrenstring: The label for children arrays to use in the JSON (default "children"). generate_names: Whether or not to generate names if none are given """ def __split_into_children(children_string): """ Helper function for splitting a newick string into siblings """ string = children_string opened = 0 closed = 0 pieces = [] last_stop = 0 for i, s in enumerate(string): if s == "(": opened += 1 if s == ")": closed += 1 if s == "," and opened == closed: pieces.append(string[last_stop:i]) last_stop = i+1 pieces.append(string[last_stop:]) return(pieces) newick_string = newick_string.strip(";") node = dict() info = newick_string[newick_string.rfind(")")+1:] info = info.split(":") name = info[0] node[namestring] = name length = "" if len(info) > 1: length = info[1] node[lengthstring] = float(length) children_string = newick_string[0:newick_string.rfind(")")+1] if children_string != "": if children_string[-1] == ")": children_string = children_string[1:-1] children_string = __split_into_children(children_string) child_nodes_JSON = [] for child_string in children_string: child_JSON = newick_to_json(child_string, namestring, lengthstring, childrenstring, generate_names) if (not name) and generate_names: node[namestring] += child_JSON[namestring] child_nodes_JSON.append(child_JSON) node[childrenstring] = child_nodes_JSON return node
b116869f46467390b6dd2463bf2b982f01a95a13
21,633
def __str2key(_): """Make string a valid jinja2 template key e.g. dictionary.key Ref: https://jinja.palletsprojects.com/en/3.0.x/templates/#variables """ return _.replace('.', '')
7980e8d38576211f9bd02bcedd817c5d0087e415
21,635
import re def compile_re(pattern): """ Compile a regular expression with pattern Args: pattern (str): a string representing the pattern e.g. "NoviPRD-.*" means strings that start with "NoviPRD-" e.g. ".*\.csv" means strings that end with ".csv" e.g. ".*xxx.*" means strings that contain "xxx" in the middle Returns: regular expression object """ return re.compile(pattern)
f5fa043b9472bf19e350c880bbaf6200739234f5
21,636
import warnings def check_args(parsed_args): """ Function to check for inherent contradictions within parsed arguments. For example, batch_size < num_gpus Intended to raise errors prior to backend initialisation. Args parsed_args: parser.parse_args() Returns parsed_args """ if 'resnet' not in parsed_args.backbone: warnings.warn('Using experimental backbone {}. Only resnet50 has been properly tested.'.format(parsed_args.backbone)) return parsed_args
160f4bacc40d6187191c6b8ec18e0bc214856d4d
21,640
def email_associated(env, email): """Returns whether an authenticated user account with that email address exists. """ for row in env.db_query(""" SELECT value FROM session_attribute WHERE authenticated=1 AND name='email' AND value=%s """, (email,)): return True return False
4f5ff9954cf7a73eca17529f74f3004835c6a07d
21,641
import numpy def int64_to_uint64(as_int64: int): """ Returns the uint64 number represented by the same byte representation as the the provided integer if it was understood to be a int64 value. """ return numpy.int64(as_int64).astype(numpy.uint64).item()
528fab1329dfd4d7f4d741b9d2d899e4cf4667c9
21,642
def _ListOpToList(listOp): """Apply listOp to an empty list, yielding a list.""" return listOp.ApplyOperations([]) if listOp else []
1c6aefacdbadc604a2566b85483894d98d116856
21,644
def format_float(n): """Converts the number to int if possible""" return ('{:n}' if n == int(n) else '{:.8g}').format(n)
5f117603d0b2f906cfa07e18785feef21e6c4ed3
21,645
def calc_rectangle_bbox(points, img_h, img_w): """ calculate bbox from a rectangle. Parameters ---------- points : list a list of two points. E.g. `[[x1, y1], [x2, y2]]` img_h : int maximal image height img_w : int maximal image width Returns ------- dict corresponding bbox. I.e. `{ 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax }` """ lt, rb = points xmin, ymin = lt xmax, ymax = rb xmin = min(max(0, xmin), img_w) xmax = min(max(0, xmax), img_w) ymin = min(max(0, ymin), img_h) ymax = min(max(0, ymax), img_h) return { 'xmin':xmin, 'ymin':ymin, 'xmax':xmax, 'ymax':ymax }
45be9537c80d54e26a54dc4a04ece3759d988feb
21,646
def __en_omelete(soup): """ Helper function to get Omelete News :param soup: the BeautifulSoup object :return: a list with the most read news from a given Omelete Page """ news = [] anchors = soup.find('aside', class_='c-ranking c-ranking--read').find_all('a') for a in anchors: link = 'http://www.omelete.com.br' + a['href'] title = a.find('div', class_='c-ranking__text').string news.append(dict(title=title, link=link)) return news
3c18168ca3f4656182e09c5dbde98ce1665b425d
21,647
def flatten_columns(columns, sep = '_'): """flatten multiple columns to 1-dim columns joined with '_' """ l = [] for col in columns: if not isinstance(col, str): col = sep.join(col) l.append(col) return l
def685043534543ea1284edb915f69f6a7c1f37d
21,648
def display_edit_subjects(): """ 110 Using the Names.txt file you created earlier, display the list of names in Python. Ask the user to type in one of the names and then save all the names except the one they entered into a new file called Names2.txt. :return: """ with open("docs/names.txt", "r") as f: names = f.read().split("\n") print(names) sel = input("Type one of the displayed names: ").title() while sel not in names: print(names) sel = input("Type one of the displayed names: ").title() else: names.pop(names.index(sel)) with open("docs/names.txt", "w") as f: f.write("\n".join(names)) return ""
0d377926acc674f2428920cc100ae03116aaba0d
21,649
def trailing_zeros(n): """Count trailing zero bits in an integer.""" if n & 1: return 0 if not n: return 0 if n < 0: n = -n t = 0 while not n & 0xffffffffffffffff: n >>= 64; t += 64 while not n & 0xff: n >>= 8; t += 8 while not n & 1: n >>= 1; t += 1 return t
dd25d3f855500ae4853130c3b84601c51b64d9f0
21,651
def extract_node_attribute(graph, name, default=None): """ Extract attributes of a networx graph nodes to a dict. :param graph: target graph :param name: name of the attribute :param default: default value (used if node doesn't have the specified attribute) :return: a dict of attributes in form of { node_name : attribute } """ return { i : d.get(name, default) for i, d in graph.nodes(data=True) }
5ec1b7124ecbe048107d4d571c18fe66436d0c7b
21,653
import struct def Rf4ceMakeFCS(data): """ Returns a CRC that is the FCS for the frame (CRC-CCITT Kermit 16bit on the data given) Implemented using pseudocode from: June 1986, Kermit Protocol Manual https://www.kermitproject.org/kproto.pdf """ crc = 0 for i in range(0, len(data)): c = ord(data[i]) q = (crc ^ c) & 15 #Do low-order 4 bits crc = (crc // 16) ^ (q * 4225) q = (crc ^ (c // 16)) & 15 #And high 4 bits crc = (crc // 16) ^ (q * 4225) return struct.pack('<H', crc)
81add4f980ded4e26b78252257933a191be8721c
21,654
def _best_streak(year_of_commits): """ Return our longest streak in days, given a yeare of commits. """ best = 0 streak = 0 for commits in year_of_commits: if commits > 0: streak += 1 if streak > best: best = streak else: streak = 0 return best
3d0f042dc9565d5ef7002b6729550a76d01d3b00
21,655
from pathlib import Path import os def _fetch_test_content(): """Get a local copy of HTML file. We do some path manipulations so the tests can be run via py.test from any directory. """ this_dir = Path(__file__).resolve().parent test_html_path = os.path.join(this_dir, "test.html") with open(test_html_path, "r") as f: data = f.read() return data
6d715a6165ecb797d4376b6f6ad8771ec8f5e8cc
21,657
def get_dict_keys(data, files): """ filters all the keys out of data Args: data: (list of lists of dictionaries) files: (list) Returns: keys: (list) set of keys contained in data """ key_list = [] for i in range(len(data)): data_file = data[i] # iterating over the dicts- list (extracting the essence again) key_list.append(list(data_file)) keys = [] for n in range(len(files)): for i in range(len(key_list[n])): keys.append(key_list[n][i]) keys = list(set(keys)) return sorted(keys)
c0b556a65892d66ed0881bf4b1c5432b3e4b4daa
21,659
def adds_arguments(**kwargs): """A factory for noop decorators. Pylint will inspect kwargs of this instantiatiosn of this factory to determine what arguments it provides. """ def inner(func): """Return the original function, so that when adds_arguments is used as a decorator there is no actual runtime impact. """ return func return inner
ed596b28a525195470cfac818d5f45c8a9600a73
21,660
def labels_to_clusters(X, labels): """Utility function for converting labels to clusters. Args: X (ndarray[m, n]): input dataset labels (ndarray[m]): labels of each point Returns: clusters (list, ndarray[i, n]): list of clusters (i denotes the size of each cluster) """ return [X[labels==i] for i in range(labels.max() + 1)]
d3e316f8563d0e8c4853754bddb294b51462d724
21,661
import requests def get_page(url): """ Get a single page of results. """ response = requests.get(url) data = response.json() return data
d7d31ea8abbaa13523f33aa9eb39fca903d5cb21
21,662
import argparse def parse_command_line_args(args): """ Parse the arguments passed via the command line. Parameters ---------- args : str Raw command line arguments. Returns ------- argparse.Namespace Parsed command line arguments. """ parser = argparse.ArgumentParser( description='Utility to read and convert Bluetooth pairing key configurations across OS.' ) parser.add_argument( 'source_dir', help=( 'Path to the directory containing Bluetooth configuration files to convert. ' 'The format of the files depends on the source OS' ) ) parser.add_argument( 'destination_dir', help=( 'Path to the directory where the converted output will be written. ' 'The format of the files depends on the destination OS' ) ) parser.add_argument( '--source-format', help='Source operating system (linux, windows, macos)', required=True, metavar='FMT', choices=['linux', 'windows', 'macos'], ) parser.add_argument( '--destination-format', help='Destination operating system (linux, windows, macos)', required=True, metavar='FMT', choices=['linux', 'windows', 'macos'], ) parsed_args = parser.parse_args(args) return parsed_args
9b029cf39ebd9c41ac637dab6ea799daf1685647
21,663
def get_uid(): """ Authorization function which returns the current user_id for the user. In our case it always returns 1 """ return 1
ac82726e470ba528c57b14b8b2ff994e182fb33f
21,664
def lst_to_ans(ans_lst): """ :param ans_lst: list[str], contains correct guesses the user entered and undeciphered character. :return: str, turns the list into string. """ ans = '' for i in range(len(ans_lst)): ans += ans_lst[i] return ans
b1f0c196a53dc88e76967481d573bdff591597b9
21,665
def augmentCrlStatus(msg): """Augment CRL message with status of ``COMPLETE`` or ``INCOMPLETE``. Check the CRL message for completeness. Will add a ``status`` field to the message with a value of ``COMPLETE`` or ``INCOMPLETE``. ``COMPLETE`` messages meet the following criteria: - Doesn't have an overflow (i.e. has more the 138 reports). - Has no reports. - All reports are in the database (including both text and graphics if indicated). Args: msg (dict): CRL message dictionary to be augmented. Returns: dict: ``msg`` dictionary with new ``status`` field indicating completeness. """ reports = msg['reports'] # A no document report is a complete report. if len(reports) == 0: msg['status'] = 'COMPLETE' return msg # An overflow CRL is also incomplete if ('overflow' in msg) and (msg['overflow'] == 1): msg['status'] = 'INCOMPLETE' return msg for reportNumber in reports: if not ('*' in reportNumber): msg['status'] = 'INCOMPLETE' return msg msg['status'] = 'COMPLETE' return msg
bd35db88259f2b4e1dad08a98973ef5413829542
21,666
def check_if_hits(row, column, fleet): """ This method checks if the shot of the human player at the square represented by row and column hits any of the ships of fleet. :param row: int :param column: int :param fleet: list :returns result: bool - True if so and False otherwise """ result = False for i in range(len(fleet)): # check if guess already in hits set: if (row, column) in fleet[i][4]: break for j in range(fleet[i][3]): # if horizontal if fleet[i][2]: if row == fleet[i][0] and column == fleet[i][1] + j: result = True break # if vertical else: if row == fleet[i][0] + j and column == fleet[i][1]: result = True break return result
2f62285d68c190b63a0934698cc209a59f15d445
21,668
from typing import Dict def find_best_proba_success(trajectories_time_and_caught_proba) -> Dict: """ Trie la liste des trajectoires, par rapport à leur taux d'echec Et renvoie le 1er élement, celui qui a le taux d'echec le plus faible Ajoute également un champs "odds_of_success" au résultat pour indiquer les chances de succès :param trajectories_time_and_caught_proba: La liste de toute les trajectoires avec les différentes combinaisons d'arrêt et leur taux d'echec :return: La trajectoire ayant le taux d'echec le plus bas """ def take_caught_proba(elem): """ Fonction pour sort la liste d'entrée :param elem: Element à comparer :return: La valeur de "caught_proba" """ return elem["caught_proba"] trajectories_time_and_caught_proba.sort(key=take_caught_proba) lowest_caught_proba = trajectories_time_and_caught_proba[0]["caught_proba"] # Ajoute un champs "odds_of_success" au résultat # On ne l'ajoute qu'a ce moment pour éviter plein de calcul inutile pendant les parcours trajectories_time_and_caught_proba[0]["odds_of_success"] = (1 - lowest_caught_proba) * 100 return trajectories_time_and_caught_proba[0]
d980d48576db1831eb65f5878691334e020c62f9
21,669
def difference_in_ages(ages: list) -> tuple: """ This function returns 'min', 'max' in ages and calculate the difference between them. """ return (min(ages), max(ages), max(ages) - min(ages))
89463494e9497dae510b821a086d9bfce7efde36
21,670
import hashlib def encrypt_string(string: str, salt1: str, salt2="") -> str: """ Returns an encrypted string for anonymization of groups and names / phones """ salt = salt1 + salt2 return hashlib.pbkdf2_hmac('sha256', string.encode(), salt.encode(), 1).hex()
7a8f0738655de109e27900efa085d8834b41fb46
21,671
def get_codon_dictionary(codon_dictionary, string): """ Returns a dictionary with codon as key and its frequency as value """ # iterates on every 3th item; remove remainders by: len(string) - len(string) % 3 for i in range(0, len(string) - len(string) % 3, 3): codon = "{first}{second}{third}".format(first=string[i], second=string[i+1], third=string[i+2]) if codon in codon_dictionary: codon_dictionary[codon] += 1 else: codon_dictionary[codon] = 1 return codon_dictionary
32301f29b580d04f967d3714fae762b680c6049e
21,672
import re def del_digits(text): """Delete words compound only by digits.""" return re.sub('(\s*)\d+(\s*)',' ',text)
668d369ee384982bf194d06db7f5672836403944
21,673