content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def coding_problem_47(prices):
"""
Given a array of numbers representing the stock prices of a company in chronological order, write a function that
calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you
can sell it. For example, given [9, 11, ... | c2a844dd2e0404000a405f415a1ed585c687cce6 | 601,866 |
def is_next_east_cell_empty(i, j, field):
"""
check if next to the right cell is empty
:param i:
:param j:
:param field:
:return: True if next right cell of the field is empty, False otherwise
"""
if j == len(field[0]) - 1:
if field[i][0] == '.':
return True
r... | 75da08d76653648002ab36cdb68b72bc58ace52a | 305,524 |
def _process_mbar_lambdas(secp):
"""
Extract the lambda points used to compute MBAR energies from an AMBER MDOUT file.
Parameters
----------
secp: .out file from amber simulation.
Returns
-------
mbar_lambdas: lambda values used for MBAR energy collection in simulation.
"""
in... | 4a3b5f0e812fdaeeb8b182e5ef79ce370a1c847d | 384,977 |
def get_key(dict, key):
"""Trivial helper for the common case where you have a dictionary and want one value"""
return dict.get(key, None) | 1a2c4f0bba9e1176569c86e9deabccfc840a9229 | 106,602 |
def _SanitizeBaseName(base_name):
"""Make sure the base_name will be a valid resource name.
Args:
base_name: Name of a template file, and therefore not empty.
Returns:
base_name with periods and underscores removed,
and the first letter lowercased.
"""
# Remove periods and underscores.
san... | 2266d90624ed49f3c315687fd0adf817ede89ae3 | 381,269 |
def fib(n):
"""Compute the nth Fibonacci number"""
pred, curr = 0, 1
k = 1
while k < n:
pred, curr = curr, curr + pred
k += 1
return curr | 22e5e4e238c07675f8d1dd9fa09a2cec95ebbe91 | 321,612 |
def hostname_from_fqdn(fqdn):
"""Will take a fully qualified domain name and return only the hostname."""
split_fqdn = fqdn.split('.', 1) # Split fqdn at periods, but only bother doing first split
return split_fqdn[0] | 3717199a1df7d64f14c7ef3cea66e51217ac252b | 509,046 |
from typing import Dict
from typing import Any
def normalize_dict(from_dict: Dict[str, Any], key_mapping: Dict[str, str]) -> Dict[str, Any]:
"""
Return a subset of the values in ``from_dict`` re-keyed according to the
mapping in ``key_mapping``. The key mapping dict has the format of
``key_mapping[ne... | b3de8c70342f86c5f8a0586e08c9d688803101fc | 432,250 |
import signal
def translate_exit_code(exit_code):
""" @brief Check exit code and convert it to a human readable string
@param exit_code The exit code from a program
@return tuple containing a human readeable representation of the exit code
and a boolean value indicating succcess of the e... | cffa455fc96fa3fa3b0f1bea66255e4617328917 | 98,759 |
import calendar
def dt2jsts(mdatetime):
"""
Given a python datetime, convert to javascript timestamp format (milliseconds since Jan 1 1970).
Do so with microsecond precision, and without adding any timezone offset.
"""
return calendar.timegm(mdatetime.timetuple())*1e3+mdatetime.microsecond/1e3 | f2622b58373b2f150783573418d39d98b4ff5e8a | 137,160 |
import json
def load_schema(path):
"""Loads a JSON schema file."""
with open(path) as json_data:
schema = json.load(json_data)
return schema | e5164cf49150ffdf57be62d74212ac4b53942557 | 155,216 |
def issue_to_dict(issue):
"""
Convert an issue to a dictionary suitable for outputting to csv
"""
issue_data = {}
issue_data['id'] = issue.id
issue_data['title'] = issue.title
issue_data['description'] = issue.description
issue_data['due_date'] = issue.due_date
issue_data['labels'] =... | 3ae05441a873a54c04588684f45581d2d7d17b04 | 667,915 |
def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'):
"""
Convert n bytes into a human readable string based on format.
Symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> bytes2human(0)
'0.0 B'
>>> bytes2human(0.9)
... | 95e2a386b3f1c3fb75457d3a1d15368a18dc4452 | 468,108 |
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback):
"""
Build the feedback when an user has completed the quiz and has failed the quiz.
:param actor_name: Name of the user that has completed the quiz.
:type actor_name: str
:param quiz_name: Name of the quiz.... | b447fb45c742e9f13b0b67b149cd65f5ccb354c2 | 666,578 |
def smoothed_epmi(matrix, alpha=0.75):
"""
Performs smoothed epmi.
See smoothed_ppmi for more info.
Derived from this:
#(w,c) / #(TOT)
--------------
(#(w) / #(TOT)) * (#(c)^a / #(TOT)^a)
==>
#(w,c) / #(TOT)
--------------
(#(w) * #(c)^a) / #(TOT)^(a+1))
==>
#(w,c)
... | e2f72c4169aee2f394445f42e4835f1b55f347c9 | 706,482 |
from pathlib import Path
def _build_path(file_name: str) -> Path:
"""Build path to test data file based on file name."""
test_dir = Path(__file__).parent
return test_dir / "testdata" / file_name | f597630b33d280370d27c66fcac087cbd3a2656c | 402,275 |
def format_verify_msg(status):
"""Format validation message in color"""
OK = '\033[92m OK \033[0m'
FAIL = '\033[91mFAIL\033[0m'
if status:
return OK
else:
return FAIL | b20fb9ffd375ee9faac08198997f39f090b89d20 | 668,859 |
def cleanup_favorite(favorite):
"""Given a dictionary of a favorite record, return a new dictionary for
output as JSON."""
favorite_data = favorite
favorite_data["user"] = str(favorite["user"])
favorite_data["post"] = str(favorite["post"])
favorite_data["id"] = str(favorite["_id"])
del ... | 48cd8469a7918e1b02062a5f804ea78d855199a4 | 490,707 |
import math
def get_bound_radius(rect):
""" Returns the radius of a circle that bounds the given rect """
return math.sqrt((rect.height/2)**2 + (rect.width/2)**2) | 9b44a82532645a95f7a84852e58de6a2d8c5eac2 | 228,546 |
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
hand... | 8eee69c02c01f8ef31195c56213889228c1fb8bd | 129,222 |
from typing import Tuple
def _parse_repo_info(repo: str) -> Tuple[str, str, str]:
"""
Gets the repo owner, name and ref from a repo specification string.
"""
repo_owner = repo.split("/")[0]
repo_name = repo.split("/")[1].split(":")[0]
if ":" in repo:
repo_ref = repo.split("/")[1].split... | 9fd8fc4f91580217b7b5deeb3674b9a676a3061e | 390,402 |
def fixture(cls):
""" A simple decorator to set the fixture flag on the class."""
setattr(cls, '__FIXTURE__', True)
return cls | abb835d9f99e9d4df7d055303ef0789e86b5bd91 | 432,144 |
def dist_median(distribution, count):
"""Returns the median value for a distribution
"""
counter = 0
previous_value = None
for value, instances in distribution:
counter += instances
if counter > count / 2.0:
if (not count % 2 and (counter - 1) == (count / 2) and
... | ac0ad2c538101ef0f44b07a3967fa8cf8cae8602 | 213,296 |
import functools
def flatten(x):
"""Flatten a list of lists once
"""
return functools.reduce(lambda cum, this: cum + this, x, []) | 6d776f8367831ed03ba662f9d04945b50c39b443 | 132,430 |
def get_url(sandbox=True):
"""Return the url for the sandbox or the real account
Usage::
url = get_url(sandbox=sandbox)
:type sandbox: bool
:param sandbox: determines whether you get the url for the sandbox
account (True) or the real account (False).
:rtype: str
:returns: the entr... | 3f0f32ee000c7f8c9ede28739209ae79e77dd279 | 291,794 |
def state2iset(s):
"""
Return a set that contains the index of each 1 in the binary representation of non-negative number s
"""
iset = []
i = 0
while s > 0:
if (s & 1) != 0:
iset.append(i)
s = s >> 1
i += 1
return iset | d5ed00faa49cb215dc93c2cf7dc01876f625ac5b | 192,050 |
def capacity_translate(capacity):
"""
容量单位自动转换
:param capacity: capacity 以B为的单位的值
:return: 自适应单位
"""
unit_list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
idx = 0
capacity = float(capacity)
while True:
capacity /= 1024
if capacity > 1024:
idx +... | 019ebf58cd44b4f0708fe72d6339feeda439f6e2 | 202,773 |
def isolate_rightmost_0_bit(n: int) -> int:
"""
Isolate the rightmost 0-bit.
>>> bin(isolate_rightmost_0_bit(0b10000111))
'0b1000'
"""
return ~n & (n + 1) | 1abac335b8570474121bbf307f52f7af2f0c736f | 642,901 |
def determine_set_y_logscale(cfg, metadata):
"""
Determine whether to use a log scale y axis.
Parameters
----------
cfg: dict
the opened global config dictionairy, passed by ESMValTool.
metadata: dict
The metadata dictionairy for a specific model.
Returns
----------
... | c6def09b9b7468d9e5aec073d73ab9ad29146ea5 | 78,406 |
def get_frequency(samples, element) -> float:
"""Find the frequency of the given element in given samples
Args:
samples: List of elements
element: Element whose frequency needs to be determined
Returns:
Frequency of the element
"""
return samples.count(element) / len(sample... | 4c3f95392ab2185bebc47b8e0a38b4c2c940e765 | 498,272 |
import json
def json_from_file(filepath):
"""Load JSON from file."""
with open(filepath) as fp:
return json.load(fp) | 362db738e21fd07db68b6b2acc35dc56ff594327 | 358,103 |
def get_user_profile_url(user):
"""Return project user's github profile url."""
return 'https://github.com/{}'.format(user) | 41e8f7c7cfdb479622766224c827f7611f906484 | 94,780 |
def single_value_fetcher(cursor):
""" Return the first value in the first row of the cursor. """
return cursor.fetchall()[0][0] | 0773bbe4107d72bd5366d40ad0698c4625e61e9b | 573,845 |
from typing import List
def calculate_initial_prices(ps_recipes:List[List[int]], max_price_per_category:float)->List[float]:
"""
Calculate a vector of initial prices such that
(a) the sum of prices in all recipes is the same
(b) the price in each category is at most max_price_per_category (a neg... | fc51cefc23a30fa9462bab84ff99363d51b79ea6 | 554,670 |
import math
def round_up(number, ndigits=0):
"""Round a floating point number *upward* to a given precision.
Unlike the builtin `round`, the return value `round_up` is always
the smallest float *greater than or equal to* the given number
matching the specified precision.
Parameters
---------... | 5662baabe4a56424526749fdc61d4140a170fe61 | 95,389 |
import builtins
from typing import Optional
from typing import Tuple
from typing import Any
def tuple(
env_var: builtins.str,
default: Optional[Tuple[Any, ...]] = None,
) -> Optional[Tuple[Any, ...]]:
"""
Parse environment variable value into a tuple.
Args:
env_var (str): Name of desired ... | 76016fe3c89e7ebd530b5afb6d0c90183f5c1bfc | 267,911 |
def same_prefix(cebuano_word, word):
"""
Vérifie si deux mots ont le même préfixe (longueur 2 ou 3)
Si les premières lettres sont des voyelles on les considère similaires
"""
if cebuano_word and word:
if cebuano_word[0] in "aeiou" and word[0] in "eaiou":
return cebuano_word[1:2] ... | 0b3b8951fd82cc31ab62a9a72ba02b4b52404b77 | 696,768 |
def _iam_ident_to_email(ident):
"""Given IAM identity returns email address or None."""
for p in ('user:', 'serviceAccount:'):
if ident.startswith(p):
return ident[len(p):]
return None | ada4ce18470d67d2311ccd6536d261a464ebe8b9 | 69,494 |
def is_page_phpbb(soup):
"""Detect if page is phpBB, from soup"""
return (soup.find('body', id='phpbb') is not None) | 58dc83a974fb80d9230aca6b3c96044b3777a378 | 508,157 |
def has_permission(page, request):
"""Tell if a user has permissions on the page.
:param page: the current page
:param request: the request object where the user is extracted
"""
return page.has_page_permission(request) | d17a56e45a371dc0d7b26aa081c5905bfacd32b8 | 274,297 |
def intersect2D(segment, point):
"""
Calculates if a ray of x->inf from "point" intersects with the segment
segment = [(x1, y1), (x2, y2)]
"""
x, y = point
#print(segment)
x1, y1 = segment[0]
x2, y2 = segment[1]
if (y1<=y and y<y2) or (y2<=y and y<y1):
x3 = x2*(y1-y)/(y1... | 403bf09794036572d4eb198951e89379634825c8 | 688,809 |
from typing import List
def parameter_order(config) -> List[str]:
"""
Return the order in which the parameters occur in the given dockerfile.
This is needed for optimising the order in which the images are built.
"""
order = list()
for line in config.dockerfile:
order += [
... | 4f02e4c04c9afb936699323714d3d9c2e0cc2317 | 650,871 |
def parse_line(line):
"""Parse line to (instruction, value) tuple."""
return [int(part) if part.isdigit() else part for part in line.split()] | 9521d236ecf77a727a233385c901dc5c17a6f5a0 | 622,461 |
def getBasesLinear(cls, stop_at=object):
"""Return a list of the linear tree of base classes of a given class."""
bases = [cls]
next_base = cls.__bases__[0]
while next_base != stop_at:
bases.append(next_base)
next_base = next_base.__bases__[0]
bases.append(next_base)
return bases | f49a191ddc6b49e0835f5b03d5420e0297212666 | 114,279 |
def lstDiff(a, b):
"""Intelligently find signed difference in 2 lsts, b-a
Assuming a clockwise coordinate system that wraps at 24=0
A value ahead clockwise is "larger" for subtraction purposes,
even if it is on the other side of zero.
Parameters:
-----------
a : np.float32, float
... | f35ed768e4b67239b6f4fe499b30e0f74c524990 | 389,407 |
def get_unique_groups(input_list):
"""Function to get a unique list of groups."""
out_list = []
for item in input_list:
if item not in out_list:
out_list.append(item)
return out_list | a31f44154c3a553a3ac5e1c96e0694b70dd266fd | 281,935 |
def get_number_rows(ai_settings, ship_height, alien_height):
"""calculate how many row can the screen hold"""
available_space_y = ai_settings.screen_height-3*alien_height-ship_height
number_rows = int(available_space_y/(2*alien_height))
return number_rows | 4cd769a162bc47447293d0ac34ff86298e9beb65 | 35,206 |
def get_mixture_weights_index_tuples(n_mixtures):
"""Index tuples for mixture_weight.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
Returns:
ind_tups (list)
"""
ind_tups = []
for emf in range(n_mixtures):
ind_tups.append(("mixtu... | 03bd80c9ec6d7df1b7e43bde899b199876adacf5 | 577,720 |
def rank_scoring(rank: float, num_players: int) -> float:
"""Convert rank into a score (points).
Args:
rank: float, rank value
num_players: int, number of players in league
Returns:
_: float, score value (points)
"""
return rank/num_players | 78a2a4671027f0f82cc99865cf8d30ed93b9102b | 543,841 |
def datetime_from_msdos_time(data, timezone):
"""
Convert from MSDOS timestamp to date/time string
"""
data_high = (data & 0xffff0000) >> 16
data_low = data & 0xffff
year = 1980 + ((data_low & 0xfe00) >> 9)
month = ((data_low & 0x1e0) >> 5)
day = data_low & 0x1f
hour = (data_high & ... | 7326043515aa7c20ea5c87fdb8bdbafd5f98671a | 654,859 |
def GetTitle( text ):
"""Given a bit of text which has a form like this:
'\n\n Film Title\n \n (OmU)\n '
return just the film title.
"""
pp = text.splitlines()
pp2 = [p.strip() for p in pp if len(p.strip()) >= 1]
return pp2[0] | d152282610072fa88c7a45a3aca2991b6fedb79c | 20,493 |
def _create_buckets(size, years):
"""
Assigns buckets for the given years, of a given size
Args:
size (int): Size of buckets in years
years (list[int]): List of years to bucket (must be consecutive)
Returns:
dict: key=year, value=bucket_id
"""
buckets = {}
bucket_id ... | 0d28221a0444c9399999e8dc280cadfb2a9817f4 | 211,679 |
from typing import Sequence
from typing import List
import copy
def cut_list_to_limit_concatenated_str_length(
target_list: Sequence[str], separator: str,
max_total_str_length: int) -> List[str]:
"""Removes the last items from the list to limit the length of concatenated string of the items.
For example,... | cc366ce2c251b80bdff186aa22c115ae5dd6d039 | 153,231 |
import random
def MERB_config(BIM):
"""
Rules to identify a HAZUS MERB configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifies a specific configration wi... | 53ab72ed19ebeb3e55f83fcccb80bff665de955e | 680,166 |
import csv
def read_csv_fieldnames(filename, separator, quote):
"""
Inputs:
filename - name of CSV file
separator - character that separates fields
quote - character used to optionally quote fields
Ouput:
A list of strings corresponding to the field names in
the given CS... | ead8b5ff5ca11d47771cf793309a640e2b1410a1 | 696,717 |
import math
def pearson_C_calc(chi_square, POP):
"""
Calculate Pearson's C (C).
:param chi_square: chi squared
:type chi_square: float
:param POP: population or total number of samples
:type POP: int
:return: C as float
"""
try:
C = math.sqrt(chi_square / (POP + chi_square... | ffbc8c033cbda9a6204297d1443956672bf1d341 | 93,215 |
import random
def number(minimum=0, maximum=9999):
"""Generate a random number"""
return random.randint(minimum, maximum) | b3f06823431cfaca549e3dc9544e68fd13171571 | 61,314 |
from typing import Dict
def get_request_organization_id(request_data: Dict) -> str:
"""
Get the organization ID from the request data.
Args:
request_data (Dict): Request data as a dictionary.
Returns:
str if organization_id is included in request_data.
Raises:
rest_frame... | 1ec26da5b6a6a3dd08367c5db1c72217a631356c | 558,547 |
def filter_ignore(annotations, filter_fns):
""" Set the ``ignore`` attribute of the annotations to **True** when they do not pass the provided filter functions.
Args:
annotations (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of annotations
... | f59e6c481eb744245ae9503ae07ed88d1f3f8253 | 8,850 |
def homo_degree_dist_filename(filestem):
"""Return the name of the homology degree distribution file."""
return f"{filestem}-degreedist.tsv" | ca75ec91578d7c7cb9e61636c8d8399eced5e6d5 | 360,069 |
import keyword
def is_correct_variable_name(string: str) -> bool:
"""
Check if string is a valid variable name and is not a reserved keyword.
:param string: string to check
:return: True/False
"""
return string.isidentifier() and not keyword.iskeyword(string) | 68cf772b78ccaaafd8a22ea4db430a83868723f0 | 587,770 |
def format_list_entry(str_list: list) -> str:
"""
Converts list of strings into a single string with values separated by comma.
:param list str_list: list of strings
:return: formatted string
"""
out_str = ''
for elm in str_list:
out_str += elm
out_str += ', '
return out_... | 6586c4e47825db3b2978a79a780802d2744feed4 | 407,284 |
def count_consonants(string: str) -> int:
"""
Counts the number of consonants in the given string
:param string: String to count
:return: int
Example:
>>> count_consonants("Hello World")
>>> 7
"""
return sum(1 for char in string if char.lower() in 'bcdfghjklmnpqrstvwxyz') | 85f293199e71406bfbec1ff4f10db62568f6bd97 | 600,545 |
def IsCoverageBuild(env):
"""Returns true if this is a coverage build.
Args:
env: The environment.
Returns:
whether this is a coverage build.
"""
return 'coverage' in env.subst('$BUILD_TYPE') | 9742599d8173812f2d995d801dd6a03688941934 | 634,975 |
import random
def weighted_choice(choices):
"""
Provides a weighted version of random.choice
:param choices: A dictionary of choices, with the choice as the key and weight the value
:type choices: list of tuple of (str, int)
"""
total = sum(weight for choice, weight in choices)
rand = ran... | b95c046fb009414f3b16bb78652169d0c7bdae84 | 631,159 |
from typing import Union
from typing import Tuple
from typing import List
def fields_to_device_number(fields: Union[Tuple[int, int], List[int]]) -> int:
"""
Joins the two 8 bit fields into a 16 bit device number
Example with fields 3 and 232
3: 0b00000011
232: 0b11101000
1000: (3 <<... | e6873ffcc6c4f88d58ad25eccc2893a47ec9f3de | 328,646 |
def concatenate_or_append(value, output): # O(1)
"""
Either concatenate a list or append to it, in order to keep list flattened
as list of lists
>>> concatenate_or_append([42], [])
[[42]]
>>> concatenate_or_append([[42, 49]], [[23, 35]])
[[23, 35], [42, 49]]
""... | 3123dc5b57fdb5792a5d65647088e1aea45abf19 | 100,786 |
def bin_widths(bin_edges):
"""Return array of bin widths given an array of bin edges"""
return bin_edges[1:] - bin_edges[:-1] | f5db56912f1ed6a4e2f5a7d8080f0767aa31ce0e | 434,474 |
def has_label(l):
""" return a function that accepts a race and returns true
if the race is labeled with l """
return lambda race: (race.filter(labels=l).count() > 0) | 81b312e336ebec1ddaf48ac40eb606c5c9d8314e | 373,521 |
import operator
def reverse_sort_lists(list_1, list_2):
"""Reverse sorting two list based on the first one"""
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2), key=operator.itemgetter(0), reverse=True))
return list_1_sorted, list_2_sorted | bf9be3111c17c83e5ef3b87f14ee77d502ff3e0e | 452,860 |
import string
import random
def _generate_random_sequence(sequence_length=6) -> str:
"""
Generates a random string of letters and digits.
From https://pynative.com/python-generate-random-string/
:param sequence_length: length of the output string
"""
sequence_options = string.ascii_letters + string.digits
re... | 25dceeb343752ab9e04faeefb9862a6af6c941d7 | 486,876 |
import re
def get_name_and_email(address):
"""
Function to get name and email from addresses like
Company <contact@company.com>, returned as tuple (name, email)
"""
custom_sender_name = re.search(r'^([^<>]+)\s<([^<>]+)>$', address)
if custom_sender_name:
return custom_sender_name.group... | 20cc05de3317ffc8d7bd7724ab61296e01f1c532 | 634,200 |
def parser_mod_shortname(parser):
"""short name of the parser's module name (no -- prefix and dashes converted to underscores)"""
return parser.replace('--', '').replace('-', '_') | 7088e25d295339e1988d23a87b177f838f6bf1f6 | 502,892 |
def point_on_rectangle(rect, point, border=False):
"""
Return the point on which ``point`` can be projecten on the
rectangle. ``border = True`` will make sure the point is bound to
the border of the reactangle. Otherwise, if the point is in the
rectangle, it's okay.
>>> point_on_rectangle(Rect... | 761d3cd918b353e18195f8817292b9c2c9ec4f40 | 673,070 |
def reversedbinary(i,numbits):
"""Takes integer i and returns its binary representation
as a list, but in reverse order, with total number of bits
numbits. Useful for trying every possibility of numbits choices
of two."""
num = i
count = 0
revbin = []
while count < numbits:
revbi... | dd9f394a60f796481917f2c67568c1538a6cb071 | 421,977 |
def position_to_number(func):
"""Decorator that transforms volleyball positions
into numerical positions.
Description
-----------
The usal positions on a volleyball court are:
4 3 2
-----------
5 6 1
Setter -> 1
Outside Hitter -> 2
Midd... | 6e4465db1430fcec45f9d1dd145a4c0c75b9043f | 357,884 |
def datenum_to_season(path, datenum):
""" Transform %Y%m%d into %Y%SEASON, e.g. 20180506 --> 2018S2 """
month_season_table = {"01":"S1", "02":"S1", "03":"S1",
"04":"S2", "05":"S2", "06":"S2",
"07":"S3", "08":"S3", "09":"S3",
"10":"S4"... | 87ea8fe77e974856d3fb0ca2faacbccadd6b5ea5 | 576,503 |
from functools import reduce
def bcc(data):
"""
Calculate BCC (Block Check Character) checksum for data
:param data:
:type data: string
:return: BCC checksum
:rtype: int
"""
return reduce(lambda a,b: a^b, bytearray(data)) | 399f4e4e8135f31029fe29addf42c4d27f5930ac | 493,529 |
def clip_line(line, size):
"""
:param line: (xmin, ymin, xmax, ymax)
:param size: (height, width)
:return: (xmin, ymin, xmax, ymax)
"""
xmin, ymin, xmax, ymax = line
if xmin < 0:
xmin = 0
if xmax > size[1] - 1:
xmax = size[1] - 1
if ymin < 0:
ymin = 0
if ... | 8ea9c09e70a61b8c9d4bdfc9039bc192add6e5d4 | 269,687 |
import yaml
def read_config(file_path):
"""Read the configuration file and load the YAML data.
:param file_path: The path of the YAML config file.
:type file_path: str
:return: The complete configuration data loaded into a dictionary.
:rtype: dict
"""
with open(file_path) as config_file:
... | 7946dd2b013d0a0451c3df185aa28acc4cd1df41 | 132,800 |
def sublist(full_list, index):
""" returns a sub-list of contiguous non-emtpy lines starting at index """
sub_list = []
while index < len(full_list):
line = full_list[index].strip()
if line != "":
sub_list.append(line)
index += 1
else: break
return sub_lis... | ee4ed5e730829a22cb825e39aa95b19e037dda00 | 686,617 |
import imaplib
def open_session(imap_url, username, password):
"""Function creates and returns an object of the connection with specified credentials and imap_url"""
con = imaplib.IMAP4_SSL(imap_url)
con.login(username, password)
return con | f19a342e562bfc0352af54b642f79a332fd818c7 | 416,382 |
def trdata(trin):
"""Obtain data points from a trace-table record"""
return trin.data() | 832c36015d0923a4cd1e899751dad3828d8fdc99 | 343,318 |
def add_row(content, row_index, row_info=[]):
"""
From the position of the cursor, add a row
Arguments:
- the table content, a list of list of strings:
- First dimension: the columns
- Second dimensions: the column's content
- cursor index for col
- cursor ... | 99b256ed6581462488d396ece5261ef5fa431b45 | 597,736 |
def clamp(value, parameter):
""" Clamp value to parameter's min and max values
"""
value = parameter.min if value < parameter.min else value
value = parameter.max if value > parameter.max else value
return value | 7bd154e9221c288810ab9470e37beca9cb58b068 | 634,490 |
def get_length(self, is_pattern=False):
"""Returns the length of the axis taking symmetries into account.
Parameters
----------
self: DataPattern
a DataPattern object
is_pattern: bool
return length of pattern
Returns
-------
Length of axis
"""
if is_pattern:
... | d1b8eb0d51a3f699aa252a191de41b17d20df9ef | 277,898 |
def _utf8_encoded_json(request):
"""Checks if content of the request is defined to be utf-8 encoded json.
'Content-type' header should be set to 'application/json;
charset=utf-8'. The function allows whitespaces around the two
segments an is case-insensitive.
"""
content_type = request.META.ge... | f279b095fda6b3f0a55fc7ecaec65cd813036f7a | 179,522 |
def binding_array_names(experiment_proto):
"""Return all binding array names from an Experiment proto.
Args:
experiment_proto: selection_pb2.Experiment describing the experiment.
Returns:
List of strings in sorted order.
"""
names = [array.name for array in experiment_proto.binding_arrays]
return ... | d9777fd2f4dabf3d11eda0668afda1e5b4845613 | 412,757 |
def tab(s):
"""indent multiline text"""
s = s.split("\n")
s = [f" {l}" for l in s]
s = "\n".join(s)
return s | 324e3f1625c230f8c4c8daa84abe5d861b518ba0 | 422,037 |
import struct
def read_plain_int96(fo):
"""Reads a 96-bit int using the plain encoding"""
tup = struct.unpack("<qi", fo.read(12))
return tup[0] << 32 | tup[1] | 39d924fe211a17192b4b3158340d40b3f28948d1 | 22,587 |
import pickle
def dump_obj(path, obj):
"""
Dump obj in path
Args:
path (string): path where dump the obj
obj (object): object to dump
Returns:
path where you dumped
"""
with open(path, "wb") as fp:
pickle.dump(obj, fp)
return path | 9a107a2e18e1c2d5f923c62bf16c6b882f9724c7 | 224,316 |
def get_labels_from_sample(sample):
"""
Each label of Chinese words having at most N-1 elements, assuming that it contains N characters that may be grouped.
Parameters
----------
sample : list of N characters
Returns
-------
list of N-1 float on [0,1] (0 represents no split)
"""
... | 4b21b878d1ae23b08569bda1f3c3b91e7a6c48b9 | 707,651 |
def dirs(obj, st='', caseSensitive=False):
"""
I very often want to do a search on the results of dir(), so
do that more cleanly here
:param obj: the object to be dir'd
:param st: the strig to search
:param caseSensitive: If False, compares .lower() for all, else doesn't
:return: The results... | 35a4ec780cf99396cbdb57c8f21633b8242b3764 | 610,109 |
def clamp(val, min, max):
""" Clamps the number """
if val > max:
return max
elif val < min:
return min
return val | 59174310981e65cfdf6b4c1fb83ab8565478ac9e | 309,094 |
def check_more_than_one_row(df_test):
"""
This function can verify that the dataframe has at least one row
Input: dataframe
Output: Boolean value (If the dataframe has at least one row,
then return True, otherwise return False)
"""
if df_test.shape[0] < 1:
return False
return... | b01ef000be3700d480656e494db8a34d4ae7db05 | 312,865 |
from datetime import datetime
def time_compare(a, b=None):
""" Compare datetime objects a and b. If a < b, that is, a means time
before b, return -1. If b < a, return 1. Otherwise return 0.
If b is not given, assume b is now. """
if b == None:
b = datetime.now()
if a < b:
... | e81198b34b88e0a9ec6f4a464cf982a50736481d | 210,562 |
def _start_stop_block(size, proc_grid_size, proc_grid_rank):
"""Return `start` and `stop` for a regularly distributed block dim."""
nelements = size // proc_grid_size
if size % proc_grid_size != 0:
nelements += 1
start = proc_grid_rank * nelements
if start > size:
start = size
... | e7ac2edba2ff57e96adde139afc5fc09218063bc | 484,892 |
def get_coordinates( x,y,direction ):
"""
Given (x,y) coordinates and direction, this function returns the
coordinates of the next tile
The strange coordinate system used to represent hexagonal grids here
is called the 'Axial Coordinate System'.
Reference: https://www.redblobgames.co... | 67aa21e3648b7273e5e9a8b7221e6abe20db37be | 225,352 |
def get_module_masses(massfile):
"""Parse input file to get masses of each module.
Input file has the mass of each module on its own line.
Return list of module masses.
"""
module_masses = []
with open(massfile, "r") as infile:
module_masses = [int(line) for line in infile]
retur... | 129eafe214cf17572379e0ba0a54a71d9ddf213e | 362,152 |
def make_rowid(city: str, date: str, num: str, name: str) -> str:
"""Create a unique row ID for the horse entry."""
return "{}_{}_{}_{}".format(city, date.replace("/", ""), num, name.replace(" ", "")) | 98cb86a38670a33f0495599a62620b426881cf93 | 142,226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.