content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def parse_degrees(coord):
"""Parse an encoded geocoordinate value into real degrees.
:param float coord: encoded geocoordinate value
:return: real degrees
:rtype: float
"""
degrees = int(coord)
minutes = coord - degrees
return degrees + minutes * 5 / 3 | c2c37d8770da2d6c8241dfcc7b0c9c7d889e65e0 | 337,452 |
def reshape_nd(data_or_shape, ndim):
"""Return image array or shape with at least ndim dimensions.
Prepend 1s to image shape as necessary.
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
... | c71796635a6d97c746eae1554a3e3a123c19f4df | 506,690 |
import json
def post_json(client, url, json_dict):
""" Send dict to url as json """
return client.post(
url,
data=json.dumps(json_dict),
content_type='application/json'
) | 087de58fa306a1bf710b3e0be2f71144df2d8562 | 168,800 |
import requests
def send_get_request(seq_id: str) -> requests.Response:
"""send_get_request
Simple function to send get request for sequence metadata, having this as a function makes
testing of different responses easier
Args:
seq_id: (str) sequence id to retrieve metadata for
Retu... | ae3df53c129a050ab699c6b8efd1f7b13cba4189 | 149,921 |
import requests
def get_page(url):
"""
Download a web page and returns it.
Args:
url (str): target webpage url
Returns:
html (str): page html code
"""
# request HTML page
response = requests.get(url)
html = response.text
return html | 4360be62a4de5aac8b897b726980386ecb8f1112 | 394,937 |
from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
... | 0002b28f2b4722c7554487db737327e333fbde54 | 626,879 |
def Storeligandnames(csv_file):
"""It identifies the names of the ligands in the csv file
PARAMETERS
----------
csv_file : filename of the csv file with the ligands
RETURNS
-------
lig_list : list of ligand names (list of strings)
"""
Lig = open(csv_file,"rt")
lig_aux = []
... | dc4510a4ea946eaf00152cb445acdc7535ce0379 | 199 |
import math
def present_value_csv(key, val, values_with_ci):
""" Turns a value into a state where it can be presented in a CSV file,
including its confidence interval if the column it appears in has
confidence intervals somewhere in it.
"""
if key in values_with_ci:
ciDown, ciUp = ... | ebfac0668ed9e10dcd71a6ce2a458854626e0e08 | 172,931 |
import logging
def restore_from_checkpoint(sess, saver, checkpoint_file_path):
"""
Restore session from checkpoint files.
Args:
sess: TensorFlow Session object.
saver: TensorFlow Saver object.
checkpoint_file_path: The checkpoint file path.
Return:
True if restore succe... | a6a7b45b601ea8c6763b3c8fa24462f8eedd53b0 | 597,249 |
def is_leap (year):
"""
Checks whether a year is a leap-year or not.
IF the year is divisible by 4 it is a leap year,
unless it is divisible by 100, unless it is also divisible
by 400.
2000 = leap-year: divisible by 4, 100, and 400 - 400 makes it leap
1900 = non-leap : divisible by 4, 100... | e157547b8d3575c7a97513efd69fc8e7a07b2675 | 436,750 |
def total_points(min_x, max_x, points_per_mz):
"""
Calculate the number of points for the regular grid based on the full width at half maximum.
:param min_x: the lowest m/z value
:param max_x: the highest m/z value
:param points_per_mz: number of points per fwhm
:return: total number of points
... | e0680e386559a9603b3b23b9627bd8648b23e65a | 702,052 |
def clean_name(value):
""" remove bad character from possible file name component """
deletechars = r"\/:*%?\"<>|'"
for letter in deletechars:
value = value.replace(letter, '')
return value | 2d9678b4994b85d7b01c91dbf02c87759610e688 | 283,747 |
def escape_char(string):
"""
Escape special characters from string before passing to makefile.
Maybe more characters will need to be added.
"""
string = string.replace("'", "\\'") # escape '
string = string.replace('"', '\\"') # escape "
string = string.replace("\n", "\\n") # escape \n
... | b6d97d082fab31ae7c8026be6d99948e0b1040ba | 466,966 |
def get_missing_columns(data, columns, category_column):
"""
Returns all of the given columns that are not in the given dataframe.
Parameters
----------
columns : List[str]
the columns to look for
category_column : str
the category column to look for, or None if there is no cate... | c6e7682aa4b9ed0078b6273938533df973cc668f | 145,600 |
from random import randint
def random_pick(board, available_nodes):
"""
Offers a node at random.
"""
index = randint(0, len(available_nodes) - 1)
return index | 746567fe4b66a9b111a24d6ce6823357c8dc290d | 514,711 |
def bps_to_mbps(value):
"""Bits per second to Mbit/sec"""
return round(int(value) / (1000**2), 3) | 156fb45a16f102235b40d9e026b9ae5f62dc6514 | 228,990 |
def moment(f, pmf, center=0, n=1):
"""
Return the nth moment of `f` about `center`, distributed by `pmf`.
Explicitly: \sum_i (f(i) - center)**n p(i)
Note, `pmf` is the joint distribution. So n=1 can be used even when
calculating covariances such as <xx> and <xy>. The first would actually
be ... | bfd5f3d149b232c99b4fc5cd0aa799a05a93a7ee | 314,227 |
from typing import Sequence
def _get_needed_orders(rdt_maps: Sequence[dict], feed_down: int) -> Sequence[int]:
"""Returns the sorted orders needed for correction, based on the order
of the RDTs to correct plus the feed-down involved and the order of the
corrector, which can be higher than the RDTs in case... | 77775574d9085ef58f4924a4e99c3b89af049f04 | 445,560 |
def get_luid(my_fn,
frame_label,
lemma,
pos):
"""
Given a frame, lemma, and pos
try to retrieve the lu identifier.
:param my_fn: loaded framenet using NLTK's FrameNetCorpusReader
:param str frame_label: a frame label
:param str lemma: a lemma, e.g., electi... | d0c493e53bba887a39449451415019458d6621b9 | 351,527 |
def get_label_yml(label):
"""Get yml format for label
Args:
label (dict): dictionnary if labels with keys color, name and description
as strings, possibly empty
Returns:
str: yml formatted dict, as a yml list item
"""
text = f' - name: "{label["name"]}"\n'
text += f' ... | be4564dd1865191d02f6d4d5fc929ae1ba21618f | 302,703 |
from typing import List
def diagonal_difference(size: int, matrix: List[List[int]]) -> int:
"""
>>> diagonal_difference(3, [[11, 2, 4], [4, 5, 6], [10, 8, -12]])
15
"""
# prim_diag = sec_diag = 0
# for i in range(size):
# prim_diag += matrix[i][i]
# sec_diag += matrix[-i-1][i] ... | 1987c8396402d91398c9f8d4424a11583255ed32 | 162,626 |
def find_by_uuid(_list: list, uuid: str):
"""
Finds a user in a leaderboard by their uuid
:param (list) _list: The leaderboard list
:param (str) uuid: Player's UUID
:returns (int) i: Placing of a user in the leaderboard
"""
for i, dic in enumerate(_list):
if dic['uuid'] == uuid:
... | 54b5bca4e67e0fc1c2af34f1f8060f582f7c3e08 | 366,095 |
import torch
def encode_batch(batch, tokenizer, max_seq_length, return_tokens=False):
"""
Tokenize and encode the given input; stack it in a batch with fixed length
according to the longest sequence in the batch.
Return a tuple. If asked to return tokens, return the encoded batch and a nested
li... | 20397b9ac8013646a7bca3da2fff7dfa569113f6 | 259,168 |
import csv
def file_to_position_depths(file_path):
"""Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth
as the value."""
# create the dictionary
result = {}
# read the position and depth data from the input csv file
with open(fil... | 461b9eac168795e4259f38800caa9c29fe620dec | 688,518 |
import torch
def get_loss_and_grads(model, train_x, train_y, flat=True, weights=None, item_loss=True,
create_graph=False, retain_graph=False):
"""Computes loss and gradients
Apply model to data (train_x, train_y), compute the loss
and obtain the gradients.
Parameters
... | 7abb2a9758ac641c5303583e2609407e84d8f91f | 136,928 |
def partition_nodes(ilist,bitpos):
"""return a tuple of lists of nodes whose next bit is zero, one or
a letter (others)"""
zeros = []
ones = []
others = []
zero = '0'
one= '1'
for inst in ilist:
bit = inst.ipattern.bits[bitpos]
if bit.value == zero:
zeros.append(inst)
... | 2f8ce1a85d18497512dac4708291d8c94fac7b87 | 125,799 |
def copyfragment(fragment0,newobj):
"""Copy the data in a fragment to another object.
The data in the source fragment 'fragment0' is copied to the
target object 'newobj', and 'newobj' is returned. 'newobj'
should be a fragment object or some subclass of fragment (such
as a 'program' object).
copyfragment ... | 3d1cf53584052af2aefd283137909e6e3b5b8c35 | 52,944 |
def model_to_dict(model, exclude=None):
"""
Extract a SQLAlchemy model instance to a dictionary
:param model: the model to be extracted
:param exclude: Any keys to be excluded
:return: New dictionary consisting of property-values
"""
exclude = exclude or []
exclude.append('_sa_instance_s... | 9500f5deb7be839196586ec27b4c785be9c9dcc2 | 189,348 |
def factorial(integer: int) -> int:
"""Return the factorial of a given integer.
Args:
integer (int): the integer whose factorial is going to be calculated
Returns:
int: the factorial of the provided integer
"""
if integer in {0, 1}:
return 1
return integer * factorial(... | 4d6457f5c3651d21ba6d831956e26e7522de553a | 588,679 |
def add_team_position_column(df):
"""Add 'team_position' column to DataFrame."""
tp_pat = r'\w{2,3}\s-\s[A-Z,]+'
tp_sr = df['player'].str.findall(tp_pat)
tp_lst = [tp[0] for tp in tp_sr]
df.insert(1, 'team_position', tp_lst)
return df | 0517f2f6b49fe26d4794406bd4d7145af2b62998 | 351,382 |
from typing import List
from typing import Dict
def find_values(item, keys: List[str]) -> Dict:
"""Find values for keys in item, if present.
Parameters
----------
item : Any
Any item
keys : List[str]
Keys whose value to retrieve in item
Returns
-------
Dict
Ma... | bab4c8a9695113390654e4eaf971559a98f4eb71 | 695,223 |
def bytes_to_bits(num_bytes: int) -> int:
"""
Converts number of bytes to bits.
:param num_bytes: The n number of bytes to convert.
:returns: Number of bits.
"""
return num_bytes * 8 | fab0ab0edee6565a6d76803239ffcff8931c5ffd | 518,628 |
import requests
def is_darksky_quota_error(err):
"""Return Tre if input 'err' is a DarkSky quota error, else False"""
tf = False
if isinstance(err, requests.exceptions.HTTPError):
resp = err.response
if resp.status_code == 403 and 'darksky' in resp.url:
tf = True
return tf | 5c6689580370b765d6fdfac884691dccac6768ac | 641,486 |
def _extract_options(line_part):
"""Return k/v options found in the part of the line
The part of the line looks like k=v,k=v,k=2 ."""
result = {}
pairs = line_part.split(",")
for pair in pairs:
if "=" not in pair:
continue
parts = pair.split("=")
key = parts[0].s... | 39089175a9f62655e7b60682792b0c7fa99a9f7d | 232,953 |
def fill_with(array, mask, fill):
"""fill an array where mask is true with fill value"""
filled = array.copy()
filled[mask] = fill
return filled | c7090511bc6dde523b3a88e9d97ec2b97235116e | 250,037 |
def remove_packaging(symbol: str):
"""Remove package names from lisp such as common-lisp-user::
Args:
symbol (str): string to have package name striped
Returns:
str: symbol input with package name removed (if present)
"""
split_symbol = symbol.split('::')
return symbol if len(s... | c1cc0b050d62cd5a5782360223ea426850620277 | 133,985 |
import inspect
def get_custom_class_mapping(modules):
"""Find the custom classes in the given modules and return a mapping with class name as key and class as value"""
custom_class_mapping = {}
for module in modules:
for obj_name in dir(module):
if not obj_name.endswith("Custom"):
... | c9682ee84c64019a17c5b4b1f3e12cba71e1463e | 654,356 |
def get_text(value):
"""Get text from langstring object."""
return value["langstring"]["#text"] | 1efaa8e2d5d06cb622227e75955cf2411c5079eb | 504,936 |
def ffmt(number: float) -> int|float:
"""
convert float to int when there are no decimal places.
:param number float: The float
:rtype int|float: The return number.
"""
if int(number) == number:
return int(number)
return number | 68b9507d847047182b71a24c05efd00513623e47 | 541,960 |
from typing import Sequence
from typing import Any
def _get_cont_out_labels(network_structure: Sequence[Sequence]) -> Any:
"""
Compute the contracted and free labels of `network_structure`.
Contracted labels are labels appearing more than once,
free labels are labels appearing exactly once.
Computed lists a... | f749b67789a00fe1cf0b2491a0a476d3882de9be | 698,114 |
from pathlib import Path
import binascii
def calculate_file_crc32(filename, block_size=1024 * 16):
"""
Calculate the crc32 of the contents of a given file path.
:type filename: str or Path
:param block_size: Number of bytes to read at a time. (for performance: doesn't affect result)
:return: Strin... | c9120fe8e7ce3bf50e7fcb289d78e6615045bb06 | 439,901 |
from bs4 import BeautifulSoup
import requests
def url_to_soup(url: str) -> BeautifulSoup:
"""URLからBeautifulSoupのオブジェクトを作る
Args:
url(str): 変換したいURL
Returns:
:obj:`bs4.BeautifulSoup` : BeautifulSoupのオブジェクト
"""
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
r... | 7c5b8a542086758cd1318a34e56e708e926e96a7 | 326,800 |
def format_gerald_header(flowcell_info):
"""
Generate comment describing the contents of the flowcell
"""
# I'm using '\n# ' to join the lines together, that doesn't include the
# first element so i needed to put the # in manually
config = ['# FLOWCELL: %s' % (flowcell_info['flowcell_id'])]
... | 0035925bd70cb15d724785b0350beabe54f04073 | 462,131 |
from typing import Union
from typing import List
from typing import Any
import math
def rewrite_inf_nan(
data: Union[float, int, List[Any]]
) -> Union[str, int, float, List[Any]]:
"""Replaces NaN and Infinity with string representations"""
if isinstance(data, float):
if math.isnan(data):
... | 14d202feb1098fefd9bcb215d9e19355bd236750 | 208,917 |
def _get_subsection_of_block(usage_key, block_structure):
"""
Finds subsection of a block by recursively iterating over its parents
:param usage_key: key of the block
:param block_structure: block structure
:return: sequential block
"""
parents = block_structure.get_parents(usage_key)
if... | 4a0e6d614ec9e5827d15203e9d0e9ff25824a351 | 335,009 |
def sortPkgObj(pkg1 ,pkg2):
"""sorts a list of yum package objects by name"""
if pkg1.name > pkg2.name:
return 1
elif pkg1.name == pkg2.name:
return 0
else:
return -1 | 5d6004588a076eb599d815ff0da2df9afc44e7ed | 414,651 |
import math
def distance(point_one, point_two):
"""Calculates the Euclidean distance from point_one to point_two
"""
return math.sqrt((point_two[0] - point_one[0]) ** 2 + (point_two[1] - point_one[1]) ** 2) | 92fe5b28046f6eb96fa6552e750ca62010d700da | 685,918 |
def positive_sum(arr):
"""Return the sum of positive integers in a list of numbers."""
if arr:
return sum([a for a in arr if a > 0])
return 0 | 30467034bdf7548f24e0f519f70b8d2a6cdedcf5 | 60,596 |
def fetch_remote_data(db, data_length, uuids):
""" Fetch VM data from the central DB.
:param db: The database object.
:type db: Database
:param data_length: The length of data to fetch.
:type data_length: int
:param uuids: A list of VM UUIDs to fetch data for.
:type uuids: list(str)
... | 17933bd99b409fd7787f63858c077abd4daf1202 | 155,417 |
def modpow(k, n, m):
""" Calculate "k^n" modular "m" efficiently.
Even with python2 this is 100's of times faster than "(k**n) % m",
particularly for large "n".
Note however that python's built-in pow() also supports an optional 3rd
modular argument and is faster than this.
"""
ans = 1
while n:
if... | bbe8de33ea07053956b15288f780491c8d24eea2 | 373,862 |
from typing import List
def write_floats_10e(vals: List[float]) -> List[str]:
"""writes a series of Nastran formatted 10.3 floats"""
vals2 = []
for v in vals:
v2 = '%10.3E' % v
if v2 in (' 0.000E+00', '-0.000E+00'):
v2 = ' 0.0'
vals2.append(v2)
return vals2 | 7e2f9b1a9e4560d3d9194c18601d22a57ed0811e | 30,782 |
def get_player_id(first_name, last_name, team):
"""
Returns a custom player ID of first initial + last name + team
i.e. for Tom Brady in New England that is T.Brady-NE
"""
if (team == None):
team = 'None'
return first_name[0] + "." + last_name + "-" + team | d44e1275b722e06d63166a750c88a7863246d9ab | 132,190 |
def read_metadata(metadata_file_fp):
"""Read metadata into dictionary.
"""
metadata = {}
with open(metadata_file_fp) as metadata_file_f:
for line in metadata_file_f:
line = line.strip().split('\t')
sample_id = line[0]
if sample_id not in metadata:
... | e1c4f4e2101cf6fca960158b63d10950c469f751 | 512,536 |
def get_milliseconds(time_sec: float) -> int:
"""
Convertit un temps en secondes sous forme de float en millisecondes
sous forme d'un int.
Args:
time_sec: Le temps en secondes.
Returns:
Le temps en millisecondes.
"""
assert isinstance(time_sec, float)
... | 4a3c15f926b9faf5934ece8069cdd4651d2efd9c | 277,704 |
def extract_individual_data(data):
"""
Separate data into different array for each individual
"""
ids = set(data[:,1])
id_A = min(ids)
id_B = max(ids)
dataA = data[data[:,1] == id_A, :]
dataB = data[data[:,1] == id_B, :]
# print(np.shape(dataA))
return dataA, dataB | dd04100bfd5e375736a1219e248741ddd9efeaad | 168,730 |
def reorder_exons(exon_ids):
"""
Reorder exons if they were out of order.
Parameters:
exon_ids (list of str): List of exons 'chrom_coord1_coord2_strand_exon'
Returns:
exons (list of str): List of same exon IDs ordered based on strand
and genomic location
"""
strand = exon_ids[0].split('_')[-2]
coords = ... | d3f52a24d4da1a05a1deceaf38927622c141a9ad | 27,161 |
import importlib
def get_module_element_from_path(opath):
""" Retrieve an element from a python module using its path <package>.<module>.<object>.
This can be for example a global function or a class.
Args:
opath: Object path
Returns:
Module object
"""
module, oname = opath.... | fa4d11fee4be5eac12ada83e4820b014591a00cc | 316,618 |
def texture_profile(df_soils):
"""
Assign mean texture profile for soil categories.
- Cl: clay
- SiCl: silty clay
- SaCl: sandy clay
- ClLo: clay loam
- SiClLo: silty clay loam
- SaClLo: sandy clay loam
- Lo: loam
- SiLo: silty loam
- SaLo: sandy loam
- Si: silt
- Lo... | a9fe7f8e59e4334df654d6e6d3dbcbfc56cee7aa | 273,477 |
import random
def randomize_strata(n_items, group_ids, seed=None):
"""Perform stratified randomization.
Maps a number of items into group ids by dividing the items into strata of
length equal to the number of groups, then assigning the group ids randomly
within each strata. If the number of items do not divid... | 0f830a9171837f3022ea131036ef8f498fdaffba | 454,386 |
def strike_through(text: str) -> str:
"""Returns a strike-through version of the input text"""
result = ''
for c in text:
result = result + c + '\u0336'
return result | a178dd99d124f537bc98bcf36cdc0690862fb0bd | 663,271 |
import math
def get_simple_distance(coords1, coords2):
"""
Calculates the simple distance between two x,y points
:param coords1: (Tuple) of x and y coordinates
:param coords2: (Tuple) of x and y coordinates
:return: (float) The distance between the two points
"""
return math.sqrt((coords1[... | 504ccd5d5d30bf1cebba2bc23644136767ccd46c | 399,336 |
def load_smarts_fdef(fname):
""" Load custom feature definitions from a txt file. The file must contain a
SMARTS string follwed by the feature name. Example:
# Aromatic
a1aaaaa1 Aromatic
a1aaaa1 Aromatic
Lines started with # are considered as comments
... | c629b4ebde56c906e80a1599ea58e13c99578ae6 | 339,900 |
def get_eps(dist, x):
"""Z = (X - mu) / sigma."""
return (x - dist.loc) / dist.scale | 882208f782e7c30075d40c79cec6ea62310fa0fe | 329,311 |
def capture_group(s):
"""
Places parentheses around s to form a capure group (a tagged piece of
a regular expression), unless it is already a capture group.
"""
return s if (s.startswith('(') and s.endswith(')')) else ('(%s)' % s) | 17da31a3403522fe0f852ca64684c1b5ea8d315c | 490,693 |
def index_select_multidim_nojit(input, indices):
"""
Like torch.index_select, but on multiple dimensions,
on first dimensions only (0, 1, ...)
NB: Clamp indices if out of range
@param input tensor of size (n_1, .., n_k, ...u)
@param indices tensor of integers of size (...v, k)
@return tenso... | 7d778d31ac87aafc326bb2930e6d8db5873c91a7 | 232,964 |
def lcs_recursive(s1, s2):
"""
Given two strings s1 and s2, find their longest common subsequence (lcs).
Basic idea of algorithm is to split on whether the first characters of
the two strings match, and use recursion.
Time complexity:
If n1 = len(s1) and n2 = len(s2), the runtime is O(2^(n1+n2... | 45ce789716d4f6194b89efa1745ee7587c17179b | 204,772 |
def word_capital(text):
"""
Capitalizes the first character of each word, it converts a string into
titlecase by making words start with an uppercase character and keep the
remaining characters.
"""
if text and len(text) > 0:
return ' '.join([s[0].upper() + s[1:] for s in text.split(' ')... | fbb20324204f62344af5b76f74fad98810f6fee0 | 19,346 |
def add_log_parser_arguments(parser):
"""Add log arguments to command line parser.
Defines the following command line arguments:
--log: path to log file (if any)
-v: verbosity level. More => more verbose log messages.
Args:
parser (argparse.ArgumentParser): parser to add arguments to.
... | 5b083364262f836247fda4a8e89e4dfc5f3a2335 | 478,631 |
def format_variant(variant):
"""
Return None for null variant and strips trailing whitespaces.
Parameters
----------
variant : str, optional.
HGVS_ formatted string.
Returns
-------
str
"""
if variant is None:
return variant
return variant.strip() | f88050c62c8efd1798f1ea909f366e38544ae7b6 | 451,845 |
def get_all_image_class_ids(self):
""" Retrieves class ids for every image as a list (used as inputs for BalancedBatchSampler)"""
return [image_info['class_id'] for image_info in self.image_infos.values()] | 26bbe7f6b9e8474ce16e499300ae7fccb66600e1 | 134,036 |
def HasRootMotionBone(obj, rootBoneName):
"""
Returns True if the root bone is named @rootBoneName
@obj (bpy.types.Object). Object.type is assumed to be 'ARMATURE'
@rootBoneName (string). Name of the root motion bone to compare with
"""
bones = obj.data.bones
for bone in bones:
#prin... | d58a61fb7902d5f6e7303de099db7e665d5d2508 | 92,184 |
def check_template_sample(template_object, sample_set):
"""
check_template_sample checks if a template has a sample associated in the samples/ folder
Args:
template_object: the template dict to check, which got parsed from the file content
sample_set: set of sample kinds (string) built by b... | 547a9240b06b943a578e773b020b8701fb75278e | 181,774 |
def read_dict(filename, div='='):
"""Read file into dict.
A file containing:
foo = bar
baz = bog
results in a dict
{
'foo': 'bar',
'baz': 'bog'
}
Arguments:
filename (str): path to file
div (str): deviders between dict keys and values
Ret... | 26bc9ec287d8e338cd7a5fef3a9f0de49ebf6138 | 673,856 |
import re
def chuvaSateliteONS(nomeArquivo):
"""
Lê arquivos texto com chuvas verificadas por satélite. Estes arquivos são disponibilizados
pelo ONS.
Argumento
---------
nomeArquivo : caminho completo para o arquivo de chuvas verificada por satélite.
Retorno
-------
... | 6254962976cb04c2eecf5aceaef45d4566cadfd9 | 79,415 |
import re
def strip_variable_text(rdf_text):
"""
Return rdf_text stripped from variable parts such as rdf nodeids
"""
replace_nid = re.compile('rdf:nodeID="[^\"]*"').sub
rdf_text = replace_nid('', rdf_text)
replace_creation = re.compile('<ns1:creationInfo>.*</ns1:creationInfo>', re.DOTALL).s... | 2c4ac4aa5d6dca534f03e501398863445c8977ea | 451,159 |
def resize(bbox, in_size, out_size):
"""Resize bouding boxes according to image resize operation.
Parameters
----------
bbox : numpy.ndarray
Numpy.ndarray with shape (N, 4+) where N is the number of bounding boxes.
The second axis represents attributes of the bounding box.
Speci... | 621eb71ad28eecab3d80131b4b429f35ec8b4a13 | 341,703 |
def remote_nodes(graph):
""" Return remote nodes
Remote nodes are isolated nodes that are not connected to anything
:param graph:
:return:
"""
return [u for u in graph.nodes() if len(list(graph.neighbors(u))) == 0] | af05c209cde7bb8f9a2e498ea0b4150debfaa245 | 563,886 |
def DecodeContent(data: bytes):
"""Convert utf-8 encoded bytes to a string."""
unpadded = data.rstrip(b"\00")
content = unpadded.decode("utf-8", "strict")
return content | 387de22ba6d70da36085457d7ebc3cbb332e0ca4 | 410,882 |
def hyphen_last(s):
"""Converts '-foo' to 'foo-', so that 'foo-' comes after 'foo'
which is useful for sorting."""
if s.startswith('-'):
return s[1:] + '-'
return s | b791ac758eb5a9e6949a83576a2fa19c09154324 | 135,352 |
def get_line_list(path) -> list:
"""
Returns a file as a list of lines.
"""
return path.read_text().splitlines() | c1ef2c648dc0ede205d96db857eb221505035bc8 | 188,000 |
from io import StringIO
def ase_to_xyz(atoms, comment="", file=True):
"""Convert ASE to xyz
This function is useful to save xyz to DataFrame.
"""
xyz = StringIO()
symbols = atoms.get_chemical_symbols()
natoms = len(symbols)
xyz.write("%d\n%s\n" % (natoms, comment))
for s, (x, y, z) i... | dcacdb5550c1cea2706190912556d84acae0094d | 43,446 |
def get_isa_field_name(field):
"""
Return the name of an ISA field. In case of an ontology reference, returns
field['name'].
:param field: Field of an ISA Django model
:return: String
"""
if type(field) == dict:
return field['name']
return field | 79480fb09a1f2a717d1c54472748207b8bf3f6f3 | 653,176 |
def run_program(codes, noun = None, verb = None):
"""
>>> run_program([1, 0, 0, 0, 99])
[2, 0, 0, 0, 99]
>>> run_program([2, 3, 0, 3, 99])
[2, 3, 0, 6, 99]
>>> run_program([2, 4, 4, 5, 99, 0])
[2, 4, 4, 5, 99, 9801]
>>> run_program([1, 1, 1, 4, 99, 5, 6, 0, 99])
[30, 1, 1, 4, 2, 5, 6... | a016feacf662f3e8f0b53659ff7d317e9bc2eb31 | 200,678 |
def f4(x):
"""Evaluate the estimate x**4+x**3+x**2+x."""
return x*(x*(x*x+x)+x)+x | 6a5e258d77992e8c15a6dddb04627a7d5c8467d9 | 16,278 |
def is_valid_port(port):
"""Check if given port is valid"""
return(0 <= int(port) <= 65535) | 5318f312573f68e364a4e8b80a92af4038f5bdf1 | 405,739 |
def check_in(position, info_pos_line_pairs):
"""
Check if position corresponds to the starting position of a pair in info_pos_line_pairs
(return pair if found, empty list otherwise)
:param position: list
:param info_pos_line_pairs: list of lists
:return: list
"""
# pos_pair form: [info,... | 26231ec22468e6fccd14d55b30b818a8c1773b78 | 685,235 |
def in_permissions(permissions, value):
"""
Given a permissions mask, check if the specified permission value is within those permissions.
:param permissions: permissions set as integer mask
:param value: permission value to look for
:type permissions: int
:type value: int
:return: is val... | 50a4a0db406c24799caf17e0f109a82a480ea100 | 570,812 |
def ret_start_point(pn: str, keyword: bytes):
"""
1) return cid and tid from this example line
CALLID[3] TID[3756] IJ T2M 0x63621040->0x65cf6450(avformat-gp-57.dll!avformat_open_input+0x0)
2) for now, this function is case sensitive
"""
with open(pn, 'rb') as f:
lines = f.readlines()
... | 435fa2f5a65b93ca427d6afb0b1e817f44bfef10 | 76,758 |
def get_diff(url, client):
"""Uses client to return file diff from a given URL."""
return client.get(url) | e2fce7d01f4eee2e806393c865e54dd5ffe1a339 | 54,174 |
def write_tag_file_text(tags, delimiter="\n"):
"""
Write the text entries for a lit of tags.
Parameters
----------
tags: list
delimiter: str
Returns
-------
text: str
"""
text = ""
for t in tags:
text += f"{t}{delimiter}"
return text | 1a7a7133a672d9183361813dde38e8819755b76c | 443,185 |
def kl_div(mean, logvar):
"""Computes KL Divergence between a given normal distribution
and a standard normal distribution
Parameters
----------
mean : torch.tensor
mean of the normal distribution of shape (batch_size x latent_dim)
logvar : torch.tensor
diagonal log variance of... | 39fc74df4190a023e5b03132cd3102dc562a0401 | 659,646 |
import math
def get_page_total(total_number, per_page_number):
"""
Given a total page number and number of items per page, calculate the page total
Parameters
----------
total_number: int
Total number of pages
per_page_number: int
Number of items per page
Returns
----... | 99e50a600051090db233b50081f52942d4938713 | 507,530 |
import collections
def combine_dicts(dict_list):
"""Combines the dictionaries in dict_list.
Args:
dict_list: A list of dicts. Each dict maps integers to lists.
Returns:
combined: A dict that has for every key the 'combined' values of all dicts
in dict list that have that key. Combining the values ... | 197636dca7070c6aba53ad3e1f32d0f7db8d545e | 256,100 |
def split_evr(version):
"""
Return a tuple of epoch, version, release from a version string
"""
if '~' in version:
epoch, version = version.split('~', 1)
else:
epoch, version = ('0', version)
release = None
if '-' in version:
version, release = version.rsplit('-', 1)... | 9e437c473b3fb0275f62b5fbf9dad64058d56b50 | 50,146 |
def bytes_coutwildrnp_zip(path_coutwildrnp_zip):
"""The zip file's bytes"""
with open(path_coutwildrnp_zip, 'rb') as src:
return src.read() | bd62d1ce2a2b20570ca45a8361e5ddb19c269725 | 543,419 |
def get_partial_index(df, start=None, end=None):
"""Get partial time index according to start and end
Parameters
----------
df: pd.DatFrame or pd.Series
start: str, optional, e.g., '2000-01-01'
end: str, optional, e.g., '2017-08-31'
Returns
-------
pd.DatetimeIndex
"""
if s... | 17b2426ae29eb5ba9a10a1d672bc9b954c69f504 | 628,006 |
def read_lines(filename):
"""Read all lines from a given file."""
with open(filename) as fp:
return fp.readlines() | f3005b1e1bc8a98fe543a1e364eec70ad4d85188 | 678,789 |
def is_valid_read(read):
"""Check if a read is properly mapped."""
if (read.mapping_quality >= 20 and read.reference_end and read.reference_start):
return True
return False | 1ad54406c86a5375b880d6cc00afad3a173fda58 | 642,079 |
def sum_arithmetic_sequence(a_n: int) -> int:
"""
Returns 1 + 2 + ... + a_n.
>>> sum_arithmetic_sequence(4)
10
>>> sum_arithmetic_sequence(5)
15
"""
return int((a_n * (a_n + 1)) / 2) | 1a70e88c5defe674dc0bf3067252b6133148584e | 200,762 |
def IncludeCompareKey(line):
"""Sorting comparator key used for comparing two #include lines.
Returns the filename without the #include/#import prefix.
"""
for prefix in ('#include ', '#import '):
if line.startswith(prefix):
return line[len(prefix):]
return line | 85f3cf7f4cdd3910e78a0239d9c3c566447869d5 | 569,128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.