content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def buffer_polygon(ft):
"""Applies a buffer to a polygon"""
return ft.buffer(-30, 1) | aec0b7903c9810fa55911115cfea0a1853e82320 | 659,836 |
def _make_list(obj):
"""Returns list corresponding to or containing obj, depending on type."""
if isinstance(obj, list):
return obj
elif isinstance(obj, tuple):
return list(obj)
else:
return [obj] | 9ac452733209033f1c6b5d6953680191971eb4d9 | 659,838 |
from pathlib import Path
import sys
def get_conda_path():
"""Get conda source path."""
return Path(
Path(sys.executable).parents[3],
'etc', 'profile.d', 'conda.sh'
) | 63bc221000960cf7aa8833bcecaf4157e3b784ec | 659,839 |
def _str_to_bool(string: str) -> bool:
"""
XML only allows "false" and "true" (case-sensitive) as valid values for a boolean.
This function checks the string and raises a ValueError if the string is neither "true" nor "false".
:param string: String representation of a boolean. ("true" or "false")
... | 146bba8733768bbadf07c95839eb6db48fc50c12 | 659,840 |
def wilders_loop(data, n):
"""
Wilder's Moving Average Helper Loop
Jit used to improve performance
"""
for i in range(n, len(data)):
data[i] = (data[i-1] * (n-1) + data[i]) / n
return data | 60d47f03dae3083992d2e6d5341351a971c82a74 | 659,841 |
def _normalise(s):
"""
normalise the string to our preferred format - camel case
"""
camel = "".join([w[0].upper() + w[1:] for w in s.lower().split(" ") if w != ""])
return camel[0].lower() + camel[1:] | 9757468dcf2a3b8dc15d9d20a12926ba010bbade | 659,842 |
def str_to_enum(name):
"""Create an enum value from a string."""
return name.replace(" ", "_").replace("-", "_").upper() | 17b8f2448d59eccc6b0b34d2b8fb15daf00b7a57 | 659,843 |
from typing import Sequence
import torch
from typing import List
def accum_grads(grads: Sequence[Sequence[torch.Tensor]]) -> List[torch.Tensor]:
"""
Compute accumulated gradients
Parameters
----------
grads : Sequence[Sequence[torch.Tensor]]
List of gradients on all previous tasks
Re... | c1e60c1e4622cc2bcbe83996fc78101b2bed6864 | 659,844 |
import argparse
def parse_all_args():
""" Parses all arguments.
Returns:
argparse.Namespace: the parsed argument object
"""
parser = argparse.ArgumentParser()
# Executable Settings
command = parser.add_mutually_exclusive_group(required=True)
command.add_argument("--comman... | 9c1a86cc1a0b3dc7a5f4349e607e55992308463b | 659,845 |
import click
def confirmation(text, *args, **kwargs):
"""
Args:
text:
*args:
**kwargs:
"""
return click.confirm(click.style(text, fg='yellow'), *args,
**kwargs) | ca8f0d6d4701eaeb3abc390378b512ac2b25be66 | 659,846 |
from bs4 import BeautifulSoup
import requests
def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict:
"""
Return a dict of current worldwide COVID-19 statistics
"""
soup = BeautifulSoup(requests.get(url).text, "html.parser")
keys = soup.findAll("h1")
values = s... | 7840425d5c091c1cb967d2b06a957bb8b68493e3 | 659,847 |
import pathlib
def convert_to_module_path(filepath: pathlib.Path) -> str:
"""converts path to an import reference"""
parts = list(filepath.parts)
module = (parts.pop()).replace(".py", "")
return ".".join(parts) + f".{module}" | 0513519af4def3ccfca2b439f64af0670ee75ec6 | 659,848 |
import string
import re
def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
consonants = ''.join([c for c in string.ascii_lowercase if c not in 'aeiou'])
word = word.lower()
match = re.match(f'([{consonants}]+)?([aeiou])(.*)', word)
if match:
p1 = match.gro... | d31aaef8cf354b57c7cb1a2b6869a5190b9a445f | 659,849 |
def uninterleave_data(data):
"""
Remove interleaving of real. imag data in last dimension of data.
"""
return data.view('complex64') | 446d54d169bb3480309f200a7bf45640a00c816a | 659,850 |
def ascending(list: list) -> bool:
"""
Check if a list is in ascending ordering
:rtype: bool
:param list: a non empty list to check
:return: if the list is in ascending order
"""
for i in range(len(list) - 1):
if list[i] < list[i + 1]:
return True
return False | 1d0b091f9be7a49e15f8163e9d409040d88f93d2 | 659,854 |
def mock_requests_get(mocker):
"""Fixture to mock reqeust.get calls."""
mock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.return_value = {
"title": "Lorem Ipsum",
"extract": "Lorem ipsum dolor sit amet",
}
return mock | 3cf15ee601371efbd249130a6b2a1fd7bbb5dc55 | 659,855 |
def _get_dependencies(dependencies):
"""Method gets dependent modules
Args:
dependencies (dict): dependent modules
Returns:
list
"""
mods = []
for key, val in dependencies.items():
mods.append(val['package'])
return mods | 7f9083fc198d252ac3643d1b11aee8cba5114cf4 | 659,856 |
def build_command_string(ctx, modules=[]):
"""Builds a command string that can be used to create an environment with
the designated modules."""
option_string = ""
if modules:
options = ""
for module in modules:
options += f"--module {module} "
option_string = f"{opt... | 0597fff6b1c6226ac7eddf04141bad63345d2601 | 659,857 |
async def _validate_1(resp):
"""Validates for CASv1"""
text = await resp.text()
# "Parse" the response
(valid, user) = text.splitlines()
if valid == 'yes':
return {'user': user}
else:
return False | 6347f7e6341350c8158781e0f140f53623a65d1c | 659,859 |
def add_additonal_datetime_variables(df):
"""Adding variables derived from datetime: dropoff_month, *_week_of_year, *_day_of_year, *_day_of_month, *_weekday, *_is_weekend, *_hour"""
print("adding additonal datetime variables")
do_dt = df.dropoff_datetime.dt
as_cat = lambda x: x.astype('category')... | 474c10eaeeb0e98a94bd29f040861e05f3df38b8 | 659,860 |
def get_read_stop_position(read):
"""
Returns the stop position of the reference to where the read stops aligning
:param read: The read
:return: stop position of the reference where the read last aligned
"""
ref_alignment_stop = read.reference_end
# only find the position if the reference e... | b9398e6e11ea052e017371dc368cb52f72dfc5b8 | 659,861 |
import re
def saf_number_fmt(phone_number):
"""Checks if a given number is a valid Safaricom number.
Checks the formats mentioned in http://bit.ly/2N3XB9b
"""
saf_number_regex = re.compile(
r"^(?:254|\+254|0)?(7(?:(?:[129][0-9])|(?:0[0-8])|(5[789])|"
"(4[0-1]))[0-9]{6})$"
)
va... | 7b1161a3c04d02f4625bef03de92c951937bdc96 | 659,862 |
def player_table_variable_add(df, player_id, pos, year, player_name):
"""Adds specific variables as columns in a dataframe"""
df = df.copy()
df['player_id'] = player_id
df['pos'] = pos
df['year'] = year
df['player_name'] = player_name
return df | 66a165fe1de8e1b135d11108a824c86112a6fb55 | 659,863 |
def avg(l):
"""Returns the average of a list of numbers
Parameters
----------
l: sequence
The list of numbers.
Returns
-------
float
The average.
"""
return(sum(l) / float(len(l))) | 97fc58a6065023fe4c53b9a9e2ab39a9f4b9df6b | 659,864 |
def _format_table(rows):
"""
Formats a right justified table using None as column separator.
"""
# compute column widths
column_widths = [0, 0, 0]
for row in rows:
widths = [0, 0, 0]
j = 0
for cell in row:
if cell is None:
j += 1
el... | 1dda74e08acac58f4e7a4386308768b7fd55ac91 | 659,865 |
def leiadinheiro(num):
"""
:param num: Texto a ser mostrado no input
:return: Retorna o valor na forma monetária
"""
ndef = str(input(num)).strip()
if ndef.replace('.', '').isnumeric() or ndef.replace(',', '').isnumeric():
return float(ndef.replace(',', '.'))
while True:
pri... | 40c31d7e437548944319bcb0ff1d33e06d164087 | 659,866 |
def cnvt_nested_grpby_to_lst_dict(dicdic, grpby, lvl=0):
"""
Recursive func that transform nested dict created by
cnvt_grpby_to_nested_dict to list of dicts with
good order define in grpby
"""
grp = grpby[lvl]
grpvals = grp["values"]
def keyfunc(key):
if key in grpvals:
... | 6638e2be3be7a850f1195ff330064682692529f2 | 659,867 |
def get_edit_log_amounts(table, checked=False):
"""Get the user-input amounts from the table used to add or edit log entries.
:param table: A QTableWidget object, with each row representing one food dictionary or log entry.
:param checked: If True, only the input amounts corresponding to the checked entrie... | f9d121859910e31b75d5fad82976650d77f01884 | 659,868 |
import math
def sum_log_scores(s1: float, s2: float) -> float:
"""Sum log odds in a numerically stable way."""
# this is slightly faster than using max
if s1 >= s2:
log_sum = s1 + math.log(1 + math.exp(s2 - s1))
else:
log_sum = s2 + math.log(1 + math.exp(s1 - s2))
return log_sum | 7e41d5e0838a3bf78b0dd7a5c2b01ddcd1216247 | 659,869 |
def parse_geocensus_response(response):
"""
Parse the geocensus response.
:param dict result: geocensus response
"""
d = {}
if response and response.get('result', {}).get('addressMatches'):
first_match = response.get('result', {}).get('addressMatches', [])[0]
latitude = first_ma... | 6af88b25fdf4a492b51bd5a6abb56bab9b8361db | 659,870 |
def validateNumber(n):
"""check if the input is a valid number"""
try:
n = float(n)
if n < 0:
exit()
return n
except:
print("invalid input")
exit(1) | 3f64487a5affe84b9a332f136091c83c7bce704d | 659,871 |
def get_types(field):
"""
Returns a field's "type" as a list.
:param dict field: the field
:returns: a field's "type"
:rtype: list
"""
if 'type' not in field:
return []
if isinstance(field['type'], str):
return [field['type']]
return field['type'] | f09e0eac4470d6c21832b054f7988588e80dbaa3 | 659,873 |
def rescale_time(temporal_network, new_t0, new_tmax):
"""Rescale the time in this temporal network (inplace).
Parameters
==========
temporal_network : :mod:`edge_lists` or :mod:`edge_changes`
new_t0 : float
The new value of t0.
new_tmax : float
The new value of tmax.
Re... | ea78615dc0d72b7b4a261265ef5f9968a593e1e1 | 659,874 |
def compute_endpoints(vals,idxs,pos_neg,vel_min=2.5,duration_min=.25,duration_max=2.5,fps=30):
"""Find endpoints and determine whether rising or falling"""
# idx are either rising(1) or falling(-1)
endpoints = []
t = len(vals)
count_max = fps * duration_max
count_min = fps * duration_min
for i,idx in enum... | 7956281a24fc57a99253ae0a38528658e648a1e9 | 659,875 |
def tokenize_char(sent):
"""
Tokenize a string by splitting on characters.
"""
return list(sent.lower()) | d54e149f79598472d61eba42b77826942d1bd981 | 659,876 |
def get_c_elf_extra_flags(board, database):
"""Get library path, defines and flags to the linker.
"""
libpaths = database["boards"][board]["libpath"]
ldflags = database["boards"][board]["ldflags"]
ldflags = [ldflag for ldflag in ldflags if "-Wl,-Map" not in ldflag]
return " ".join(ldflags
... | 04fb9ea74f1f4496c448a4c6fcf40145bb44a128 | 659,877 |
def euler100(lim=1000000000000):
"""Solution for problem 100."""
# P(BB) = (b/t) * ((b-1)/(t-1))
# P(BB) = 1/2
# => 2 * b * (b - 1) = t * (t - 1)
# https://oeis.org/A046090
b0, b1 = 1, 3
r0, r1 = 0, 1
while True:
if b0 + r0 > lim:
return b0
b0, b1 = b1, 6 * b... | 394f0ba7bb57a8b4ff06ca38d9018080bc465663 | 659,878 |
def unordlist(cs):
"""unordlist(cs) -> str
Takes a list of ascii values and returns the corresponding string.
Example:
>>> unordlist([104, 101, 108, 108, 111])
'hello'
"""
return ''.join(chr(c) for c in cs) | eb4f92a103b62428576a3129fdb95969c95f2cec | 659,879 |
def get_force_datakeeper(self):
"""
Generate DataKeepers to store by default results from force module
Parameters
----------
self: VarLoadFlux object
Returns
-------
dk_list: list
list of DataKeeper
"""
dk_list = []
return dk_list | 8ca0802eb75dd08b8aa70c037f2b3fd904711249 | 659,880 |
def is_vararg(param_name):
"""
Determine if a parameter is named as a (internal) vararg.
:param param_name: String with a parameter name
:returns: True iff the name has the form of an internal vararg name
"""
return param_name.startswith('*') | f9fda2b98038740c35b08222ed6c4fb929273b83 | 659,881 |
import random
def shuffle(liste):
"""
brief: choose randomly in the given liste
Args:
tab :a list of values, raise Exception if not
Returns:
the value selected randomly
Raises:
ValueError if input tab is not a list
"""
if not(isinstance(liste, list)):
raise ... | 1b68a33b42ebb2d838aca1154d57b3f9ad2c3a33 | 659,882 |
def populate_cells(worksheet, bc_cells=[]):
"""
Populate a worksheet with bc_cell object data.
"""
for item in bc_cells:
if item.cellref:
worksheet[item.cellref].value = item.value
else:
worksheet.cell(
row=item.row_num, column=item.col_num, value=... | 4b5529ebbb63ebb3d0904d218807166af4bbff38 | 659,883 |
def get_query_types(query_list):
"""
This function is used to parse the query_ticket_grouping_types string from the app.config
:param query_list: the string to parse into ticketType groupingType pairs for querying Securework ticket endpoint
:return: List of json objects. Each json entry is a ticketType... | fdd78b4c655e9018597c65eba9cc361e3f526266 | 659,884 |
def severe_cases_by_time(infections):
"""
This is the estimated number of severe positive
cases that will require hospitalization to recover.
"""
return (infections * (15/100.0)) | 154c9f99935808a173b624d96788a3b86b773d8d | 659,887 |
def lastLetter (s):
"""Last letter.
Params: s (string)
Returns: (string) last letter of s
"""
return s[-1] | 2d1f5f9a1ae3fcc35fd7edcc4673d76627ffef95 | 659,888 |
def fib(n):
"""
O(2**n) time and space
"""
if n < 2:
return n
return fib(n-1) + fib(n-2) | 9aa28a7c7be6d6394bbf4c4088ae5dee01dfca96 | 659,889 |
def parsetrusteesresponse(response):
"""Parse the response to GetTrustees from the WoT plugin.
:returns: [(name, {InsertURI: ..., ...}), ...]
>>> resp = parseownidentitiesresponse({'Replies.Nickname0': 'FAKE', 'Replies.RequestURI0': 'USK@...', 'Replies.InsertURI0': 'USK@...', 'Replies.Comment0': 'Fake', '... | 1e663958dcdcc76d4e5684b04ae20ab098977ebf | 659,890 |
from typing import List
import itertools
import random
def get_separators(
space_count: int, sep_count: int, padding_count: int, shuffle: bool
) -> List[str]:
"""Create a list of separators (whitespaces)
Arguments:
space_count : minimum number of spaces to add between workds (before padding)
sep... | 17506e4c94d497eb4c5167862ac63df370e4c783 | 659,891 |
import time
def get_signature(user_agent, query_string, client_ip_address, lang):
"""
Get cache signature based on `user_agent`, `url_string`,
`lang`, and `client_ip_address`
"""
timestamp = int(time.time()) / 1000
signature = "%s:%s:%s:%s:%s" % \
(user_agent, query_string, client_ip_... | 1e4a56f066a60fe29db3a9a522a472fde5a977b3 | 659,892 |
def is_typed_tuple(tpl: object, obj_type: type, allow_none: bool = False, allow_empty: bool = True) -> bool:
"""
Check if a variable is a tuple that contains objects of specific type.
:param tpl: The variable/list to check
:param obj_type: The type of objects that the tuple should contain (for the chec... | fc6fe687d8334d1ee177f262221560bf9c46dbd7 | 659,893 |
def rotate(grid):
"""Rotate grid 90 deg to the right."""
rows = grid.split('\n')
return '\n'.join(''.join(chars) for chars in zip(*reversed(rows))) | 418786c3a23620c7747d3f93584fafc68c521dda | 659,894 |
import operator
def get_act_list(act_data, frameidx, bgid):
"""Given a frameidx, get this person' activities."""
# act_data is a list of sorted (start,end,actclassid)
# return current act list,
current_act_list = [(actid, e - frameidx) for s, e, actid in act_data
if (frameidx >= s) and ... | 16f95eb6691a271efe3ea49acc72f608b3dfb35c | 659,895 |
import re
def find_all(s, pattern):
"""
return ordered list of indexes where [pattern] appears in [s];
"""
shift_on_match = 1
indexes = []
i = re.search(pattern, s)
if i:
i, j, k = i.start(), i.end(), i.groups()
indexes.append((i,j,k))
return indexes | 58396ebb5d7fb6f287bcad2c2245d1a07d91c749 | 659,896 |
def get_chain_offsets(chainlist, chainlength, chainpadding):
"""Generates chain offsets
:param chainlist: Sorted list of chain letters
:param chainlength: chain length dictionary
:param chainpadding: chain padding dictionary
:return: dictionary of chain offsets
"""
chainoffset = {}
for ... | ef4aaa97e3d4d581ecde5100455fe6de0e33fc1f | 659,897 |
import copy
def _set_name(dist, name):
"""Copies a distribution-like object, replacing its name."""
if hasattr(dist, 'copy'):
return dist.copy(name=name)
# Some distribution-like entities such as JointDistributionPinned don't
# inherit from tfd.Distribution and don't define `self.copy`. We'll try to set
... | a802dad26a2b8c54b1a395635d3cf967b8645e7a | 659,898 |
def rayleigh_Z(n, r):
"""
Compute rayligh Z statistic
:param n: sample size
:param r: r-value (mean vector length)
"""
return n * (r**2) | ac72cce053eaac647ef5139257a189c1e7b79279 | 659,899 |
from bs4 import BeautifulSoup
from typing import List
from typing import Dict
def get_author_names_from_grobid_xml(raw_xml: BeautifulSoup) -> List[Dict[str, str]]:
"""
Returns a list of dictionaries, one for each author,
containing the first and last names.
e.g.
{
"first": first,
... | d731db1c4109490867bbc20b6a1a59a50b70bbf3 | 659,900 |
def insight_dataframe(dataframe, dataframe_name):
"""Summary of the shape of a dataframe and view of the first 5 rows of the dataframe
Parameters:
dataframe (DataFrame): The dataframe we want to analyse
dataframe_name (str) : Name of the dataframe
Returns:
str:Returning summary of the da... | 412ed73cd3a2442bbb43828d3a05fdd1cd3f3199 | 659,901 |
def pr(x):
""" Display a value and return it; useful for lambdas. """
print(x)
return x | 0a89752040852c4f9ba331eab939accde5b94cea | 659,902 |
def default_window(win_id):
"""return default config for one window"""
win = {}
win['win_id'] = win_id
win['mfact'] = 0.55
win['nmaster'] = 1
win['layout'] = 'horizontal'
win['zoomed'] = False
win['num_panes'] = 1
win['last_master_pane_id'] = None
win['last_non_mas... | 37c3a4753a8d2590676937e9355fb405ddc70dd9 | 659,903 |
def config_from_onnx_model(model, granularity='model', default_precision='ap_fixed<16,6>', default_reuse_factor=1):
"""Generate configuration dictionary from an ONNX model.
Parameters
----------
model : ONNX model object.
Model to be converted to hls model object.
granularity : string, ... | f145adf74d5c950f6d4f33434bb67b99f2c1d5e1 | 659,904 |
def Euclidean_Distance(x,y,Boundaries = 'S',Dom_Size=1.0):
"""
Euclidean distance between positions x and y.
"""
d = len(x)
dij = 0
#Loop over number of dimensions
for k in range(d):
# Compute the absolute distance
dist = abs( x[k] - y[k] )
#Extra condition for periodic BCs:
if Boundaries == 'P' o... | a91ea771da229d43f4209a9ffc02a0e9b231e97e | 659,905 |
def matrix3d_F2to128(n1=[]):
"""
Calculate the vector in the finite field with 128 element.
Parameters:
n(int): Integer in {0, 1}
Returns:
(vector): Field element
"""
matrix =[]
for i in range(len(n1)):
n = []
for j in range(len(n1[0])):
row = []
for k in rang... | 0913042afebfb6a42859a5d175a6dee1c5bcea81 | 659,906 |
import re
def _GetRcData(comment, rc_path, rc_data, pattern=None):
"""Generates the comment and `source rc_path` lines.
Args:
comment: The shell comment string that precedes the source line.
rc_path: The path of the rc file to source.
rc_data: The current comment and source rc lines or None.
patt... | 7d1c340a042f7449a92fd7295deba9557ca147eb | 659,907 |
def unique(s):
""" Return a list of the elements in list s in arbitrary order, but without duplicates """
n = len(s)
if n == 0:
return []
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
del u # move onto the next record
else:
return list(u.keys... | c9c0938fdf4e3f4b2f65ca85f106dcebdb881e27 | 659,908 |
def inconsistent_typical_range_stations(stations):
"""Given list of stations, returns list of stations with inconsistent data"""
inconsiststations = []
for i in stations:
if i.typical_range_consistent() == False:
inconsiststations.append(i)
return inconsiststations | 30b5a95ba1715e6781554a04d9c502ebc8d69709 | 659,909 |
import numpy
def peaks_vs_area(pmap):
"""Get scatter data for field peak rates vs field area in cm^2
A PlaceMap (or subclass) instance must be passed in.
Returns 2-row (peak, area) array.
"""
fdata = pmap.get_field_data()
return numpy.c_[fdata['peak'], fdata['area']].T | ece580d6d2c7ad50650b895511beadeca5881ec3 | 659,910 |
def intersection(u, v):
"""Return the intersection of _u_ and _v_.
>>> intersection((1,2,3), (2,3,4))
[2, 3]
"""
w = []
for e in u:
if e in v:
w.append(e)
return w | 683aa5c8a0ced935cd252b782af163bfd1a4e7d2 | 659,911 |
import os
def getcwd(symlinks=True):
"""Get the current working directory.
:param symlinks: If True, then get the path considering symlinks. If false,
resolve the path to the actual path.
:type symlinks: bool
:returns: the current working directory
:rtype: str
"""
cwd = ''
# Get... | 30d7d7fcd2c975aa009f6d415fd9ba74f486fe7c | 659,912 |
import random
def sameDate(numPeople, numSame):
"""Two arguments, number of people in the group and the number of people that
we ask if they have birthday the same day."""
# I am assuming that every birthday is equally likely
possibleDates = range(366)
# Table that keeps track of number of people ... | c20e0fce2d1c61ffadafad949d6ac408bf6c225a | 659,913 |
import re
def get_title(name):
"""
Use a regular expression to search for a title.
Titles always consist of capital and lowercase letters, and end with a period.
"""
title_search = re.search(" ([A-Za-z]+)\.", name)
if title_search:
return title_search.group(1)
return "" | b04ac3752d402021c3ffba709a02b8c9bfa41557 | 659,914 |
def optimal_sequence_linear(n):
"""
Solve by calculating min-steps for each i in 1..n
"""
steps = [0] * (n + 1)
# calculate array
for i in range(1, n + 1):
prev = [ steps[i - 1] ]
if not i % 3:
prev.append(steps[i // 3])
if not i % 2:
prev.append(... | 9f2f342495dfbc9ebfd562c4642991172713bc6d | 659,915 |
def per_capita(value, population, per=10000, fail_silently=True):
"""
Accepts two numbers, a value and population total, and returns
the per capita rate.
By default, the result is returned as a per 10,000 person figure.
If you divide into zero -- an illegal operation -- a null value
is returned ... | e716180fd3e1d3c239ae41178ae874a6320d06ea | 659,916 |
def importName(modulename, name):
""" Import a named object from a module in the context of this function.
"""
try:
module = __import__(modulename, globals(), locals(), [name])
except ImportError:
return None
return getattr(module, name) | 3698aedbc39331cccfa849903c6465bde24c3f41 | 659,917 |
def module_equals(model1, model2):
"""Check if 2 pytorch modules have the same weights
"""
for p1, p2 in zip(model1.parameters(), model2.parameters()):
if p1.data.ne(p2.data).sum() > 0:
return False
return True | cf23a7da62d95b80f6f878dc77f65e14db74dba6 | 659,918 |
import requests
from bs4 import BeautifulSoup
def get_all_player_links(url):
"""Get the all_players links from the base url"""
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
player_table_links = soup.find_all("a", text="View Player Stats")
return player_table_links | 3fa854a27d64d43e797c14007e0078f780f3722c | 659,919 |
def diff(data: list[int]) -> list[int]:
"""Calculate the difference between numeric values in a list."""
previous = data[0]
difference = []
for value in data[1:]:
difference.append(value - previous)
previous = value
return difference | 008ae124f2306ce27c4bafed14d8e204fcbd6f2e | 659,920 |
def bchunk2bpacket(form):
""" Converts the old binary chunk packet form into the v2 api
"""
encounter = form.cleaned_data['procedure_guid']
node = form.cleaned_data['element_id']
subnode = form.cleaned_data['binary_guid']
node = '%s-%s'% (node, subnode)
type = form.cleaned_data['element_type... | 12665e1016e283554b6ce112c7011474d1d5ac57 | 659,921 |
def plot_histograms(ax, prng, nb_samples=10000):
"""Plot 4 histograms and a text annotation."""
params = ((10, 10), (4, 12), (50, 12), (6, 55))
for a, b in params:
values = prng.beta(a, b, size=nb_samples)
ax.hist(values, histtype="stepfilled", bins=30, alpha=0.8, density=True)
# Add a s... | 022ae87044b2f84f544736aa4cf7f65a0a0e4c3d | 659,922 |
import json
def _extract_multi_block_from_log(log_content, block_name):
"""
Extract multiple data blocks from a simultaneous REFL1D fit log.
The start tag of each block will be [block_name]_START
and the end tag of each block will be [block_name]_END.
:param str log_content: strin... | 5bfaf61474811fda022a0bc2387837a9c2d6080d | 659,923 |
def rayDamCoe(xi,ome):
"""
Returns Rayleigh damping coefficients.
Initial stiffness is used.
Coefficients are computed once for all in the beginning of the analysis.
-------
Inputs:
xi: strutural damping ratio (same for all modes)
ome: eigen angular frequencies
-------
Output:
... | c8d7ebad6f5f0cacc3a702e3b969ef7762a6f2c8 | 659,924 |
def strip_path_prefix(path, prefix):
"""
Strip a prefix from a path if it exists and any remaining prefix slashes.
Args:
path: The path string to strip.
prefix: The prefix to remove.
Returns:
The stripped path. If the prefix is not present, this will be the same as the input.
... | 765c3ff2639ad346cc525b080822de79ba710c01 | 659,925 |
import argparse
def parse_args():
"""
Parse our inputs including help and support messages to guide the user.
Returns an argparse object that can be used to access results
"""
# Our constants for help
returns_val = """
If you schedule this script via cron or similar, please add the --cron opti... | 19ca1b3472b1a1a825bd89670f3b4f3ce5460233 | 659,926 |
def get_select_field_choices(raw_choices_data,
key_type=None,
value_type=None,
fail_silently=True):
"""Get select field choices.
Used in ``radio``, ``select`` and other choice based
fields.
:param str raw_choices_da... | 9896c12895aa1256c02344c4e3efd5ad297d761b | 659,927 |
import requests
from bs4 import BeautifulSoup
import re
def get_games_year(year, cursor):
"""takes (year, cursor) and pulls game ids not in db for a SPECIFIC SEASON"""
url = "https://www.pro-football-reference.com/years/" + str(year) + "/games.htm"
req = requests.get(url)
soup = BeautifulSoup(req.text... | 3611341f30a3595bbc3ab461339d4570f92f95a1 | 659,928 |
def build_cohorte_for_pm(data_file_name):
"""
-> Build a cohorte for pattern mining
-> data_file_name is the name of the file containing data,
supposed to be dichotomized data
-> return a matrix (list of list)
"""
cohorte = []
variables_list = []
file_data = open(data_file_name, "r")
cmpt_line ... | 0f5fbd3cc3604f5bc5d4d3707a51a006bf21d2b9 | 659,929 |
import pkgutil
def all_modules(package_path):
""""Return a generator of all modules in the given package path."""
def load_module(module_info):
"""Load and return the module referred to by the given ModuleInfo."""
name = module_info.name
return module_info.module_finder.find_module(na... | 10dfc749b025992e602b08aa3b96fa8a8c1dda57 | 659,930 |
def convert_bin_magnitude(val, orders):
"""Convert a number to another binary order of magnitude.
Args:
val (int, float): Value to convert.
orders (int): Orders of magnitude, such as 3 to convert a value in
bytes to gibibytes (GiB), or -2 to convert a value in
tebibytes ... | c1eec9e82e79b1a2ad9b87236a369fee70edcec4 | 659,931 |
def gen_numbers(words=[]):
"""
Function to mix words with commonly used numbers patterns.
"""
word_list = []
if len(words) <= 0:
return word_list
num_list = ['0', '01', '012', '0123', '01234', '012345', '0123456', '01234567', '012345678', '0123456789',
'1', '12', '123', '1234','123... | 763153346a624cfc0be1f3e314e558cbdd21d73f | 659,932 |
def developer_token() -> str:
"""The developer token that is used to access the BingAds API"""
return '012345679ABCDEF' | 76926fb74e049e37e6fef0e56ff53cb59a5566a4 | 659,933 |
def n_puissance_p(n,p):
""" n^p implémentation de la multiplication avec gestion de la retenue """
lx=[1]
lx2=[]
retenue =0
for j in range(p):
for i in lx[::-1] : # parcours inverse de la liste
t=i*n + retenue
if t < 10:
lx2.insert(0,t)
... | dec877326afca34aaee758e3356670ad17788a7c | 659,934 |
def centerCropImage(img, targetSize):
""" Returns a center-cropped image. The returned image is a square image
with a width and height of `targetSize`. """
# Resize image while keeping its aspect ratio
width, height = img.size
if height < targetSize:
print(str(height) + " height < targetSiz... | 4e89f0f0099c968989a203b4b64d6f64f4015ba3 | 659,935 |
import subprocess
def stat():
"""Return full output of ibstat"""
return subprocess.check_output(["ibstat"]) | 331ffb91681d418c4854272f62089cb4696b82ec | 659,936 |
def get_string_between_nested(base, start, end):
"""Extracts a substring with a nested start and end from a string.
Arguments:
- base: string to extract from.
- start: string to use as the start of the substring.
- end: string to use as the end of the substring.
Returns:
- The substring if found... | ed36a5a0c6f293aa6fd40a2898c3255cd726f1bf | 659,937 |
def convert_str_color_to_plt_format(txt):
"""
Converts an rgb string format to a tuple of float (used by matplotlib format)
Parameters
----------
txt : str
a string representation of an rgb color (used by plotly)
Returns
-------
A tuple of float used by matplotlib format
E... | 0fe890867c18ff961ea39151a4eb1a36279323a6 | 659,938 |
import re
def escape(in_txt, backwhack=re.compile(r'([][\`*_{}()#+-.!])')):
""" HTML escaping is not the same as markdown escaping
"""
return re.sub(backwhack, r'\\\1', str(in_txt)) | 7e6dfe4e0693283826cd5d06c397dd6a6867c7c7 | 659,939 |
def my_sum(iterable):
"""Sum implemetnation."""
tot = 0
for i in iterable:
tot += i
return tot | fe1bc8423911ea35e2a4e2b2cc0caa6625b92ac9 | 659,940 |
import json
def create_new_user():
"""Prompt user to enter desired username"""
username = input('Vad är ditt användarID?: ')
filename = 'user_db.json'
with open(f'txt_files/{filename}', 'w') as f:
json.dump(username, f)
return username | 2405d9414f3713171915a12e4b2364d648277e18 | 659,941 |
async def get_ltd_product_urls(session):
"""Get URLs for LSST the Docs (LTD) products from the LTD Keeper API.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
Returns
---... | bad9b327ad4c0f2def43096b3820f2d8a2bfd33e | 659,942 |
def init_queue(index, weights_set, num_class, dq_num, cq_num):
"""
初始化候选队列和支配队列
:param index:
:param weights_set: h5py dataset对象
:param num_class:
:param dq_num:
:param cq_num:
:return:
"""
data, candidate_label_idx = index.search(weights_set[:num_class], cq_num)
dominant_lab... | 1900f4a34582babe71d89a093484cf1145273325 | 659,943 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.