content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def string(obj):
"""
Returns the string representation of the object
:param obj: any object
:return: string
"""
return str(obj) | 190ff4e0a1b75ff428119989fa60d657a641aa71 | 556,786 |
def align(items, attr, strength='weak'):
"""
Helper function to generate alignment constraints
Parameters
----------
items: a list of rects to align.
attr: which attribute to align.
Returns
-------
cons: list of constraints describing the alignment
"""
cons = []
for i i... | 2358285f1a4bd9b8f7d7464ee9ef41f9027cefe6 | 362,519 |
def status(prog_comp, obs_comp):
"""
Compute weighting factor representative of observation and program status.
- 1.0 if observation and program have not been observed
- 1.5 if program has been partially observed
- 2.0 if observation has been partially observed
Parameters
------... | cec07dca621ac402fe9260b12a063c9c0291c164 | 594,265 |
def filter_type(type):
"""Filter the type of the node."""
if "[" in type or "]" in type:
return "arrayType"
elif "(" in type or ")" in type:
return "fnType"
elif "int" in type:
return "intType"
elif "float" in type:
return "floatType"
else:
return "type" | bf9e55f70d2f16c7ac67066659deb8b9822c8457 | 430,842 |
def mapValues( d, f ):
"""Return a new dict, with each value mapped by the given function"""
return dict([ ( k, f( v ) ) for k, v in d.items() ]) | 0e0c7281be3a8b6e4c7725f879ae1636b4216e1d | 499,467 |
def get_width(image):
"""get_width(image) -> integer width of the image (number of columns).
Input image must be rectangular list of lists. The width is
taken to be the length of the first row of pixels. If the image is
empty, then the width is defined to be 0.
"""
if len(image) == 0:
r... | 6532d7e543735e4a0991f52bc0c65d1cc820738f | 107,896 |
import hashlib
def is_placeholder_image(img_data):
"""
Checks for the placeholder image. If an imgur url is not valid (such as
http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image.
@param: img_data (bytes) - bytes representing the image.
@return: (boolean) True if placeholder image otherwise... | 59d92b6cbde9e72d6de19a300ce90f684cf6ca69 | 661,562 |
from typing import Tuple
import re
def exception_matches(e: Exception, patterns: Tuple[Exception, ...]) -> bool:
"""
Whether an exception matches one of the pattern exceptions
Parameters
----------
e:
The exception to check
patterns:
Instances of an Exception type to catch, wh... | 4c3515eb83c06c9749b85e567769a979405610df | 216,954 |
def grow_capacity(capacity):
# type: (int) -> int
"""Calculates new capacity based on given current capacity."""
if capacity < 8:
return 8
return capacity * 2 | d4b3cdcdfc97627428ce1ac430d7b8943db0abf8 | 475,352 |
def sanity_check_args(args):
"""
Check that command-line arguments are self-consistent.
"""
if args.weeks_ahead and (args.gw_start or args.gw_end):
raise RuntimeError("Please only specify weeks_ahead OR gw_start/end")
elif (args.gw_start and not args.gw_end) or (args.gw_end and not args.gw_s... | da4d9333f79eb923dcadd2023a4756f562e35f7a | 595,962 |
def contains_unquoted_target(x: str,
quote: str = '"', target: str = '&') -> bool:
"""
Checks if ``target`` exists in ``x`` outside quotes (as defined by
``quote``). Principal use: from
:func:`contains_unquoted_ampersand_dangerous_to_windows`.
"""
in_quote = False
... | 2e66a4d06a1401407f62c938bd82fc1f42426247 | 91,286 |
def even_or_odd(num):
"""Returns the string even, odd, or unknown"""
if num % 2 == 0:
return "even"
elif num % 2 == 1:
return "odd"
else:
return "UNKNOWN" | 7a7bacc139e426c6c08e32f6c2744037f26603a2 | 286,455 |
def copyAttrs(srcobj, destobj):
"""
Copies attributes from one HDF5 object to another, overwriting any
conflicts
"""
for k in srcobj.attrs.keys():
destobj.attrs[k] = srcobj.attrs[k]
return True | b4fc98a1f1c6076283d6782b8623a9fcd9d32450 | 183,022 |
def string_concatenation(a: str, b: str, c: str) -> str:
"""
Concatenate the strings given as parameter and return the concatenation
:param a: parameter
:param b: parameter
:param c: parameter
:return: string concatenation
"""
return a + b + c | 8e503035facd9cee3d65790b36e9e8f2143e9d6d | 341,353 |
def cat_and_mouse(x, y, z):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to
determine which cat will reach the mouse first, assuming the mouse doesn't m... | 3a4e7f3b60fd11d5488156d40c4968c7da81be45 | 283,820 |
import copy
def merge_dicts(dict1, dict2):
"""Recursively merge two dictionaries.
Values in dict2 override values in dict1. If dict1 and dict2 contain a dictionary as a
value, this will call itself recursively to merge these dictionaries.
This does not modify the input dictionaries (creates an intern... | b3dccd6301be21a096bb3d299793b4cf1461c3d9 | 699,686 |
def lower_keys(x):
"""Recursively make all keys lower-case"""
if isinstance(x, list):
return [lower_keys(v) for v in x]
if isinstance(x, dict):
return dict((k.lower(), lower_keys(v)) for k, v in x.items())
return x | f7c4537e09f3900c369a7c67a307b8b064e9e9ba | 64,046 |
def merge_resources(resource1, resource2):
"""
Updates a copy of resource1 with resource2 values and returns the merged dictionary.
Args:
resource1: original resource
resource2: resource to update resource1
Returns:
dict: merged resource
"""
merged = resource1.copy()
... | e3b2f27e29fb773b119ad22ab89b297e0425a65d | 695,178 |
def with_lock(lock, fn):
"""
Call fn with lock acquired. Guarantee that lock is released upon
the return of fn.
Returns the value returned by fn, or raises the exception raised
by fn.
(Lock can actually be anything responding to acquire() and
release().)
"""
lock.acquire()
try... | d8ed4c4a933483ac0aa5291c815b8afa64ca3957 | 665,311 |
def adjust_index_pair(index_pair, increment):
"""Returns pair of indices incremented by given number."""
return [i + increment for i in index_pair] | 43968980998f6d12457e922c3c70d2ceba6d6b2e | 14,750 |
import collections
def product_counter_v3(products):
"""Get count of products in descending order."""
return collections.Counter(products) | 22c57d50dc36d3235e6b8b642a4add95c9266687 | 704,745 |
def _get_union_pressures(pressures):
""" get list of pressured where rates are defined for both mechanisms
"""
[pr1, pr2] = pressures
return list(set(pr1) & set(pr2)) | d25d2be0ce8703c79514ce46f6c86b911b2df19d | 559,735 |
def create_test_results(suite_name, test_name, timestamp, command_args_printable, rc):
"""
Create a minimal test results object for test cases that did not produce their own
:param suite_name: the name of the subdirectory for the suite this test was run in
:param test_name: the name of the subdirectory... | 2af568e094b64a08a8b32afb702492e17c1f8fcb | 689,474 |
import re
def _parse_url_token(url_token):
"""Given activation token from url, parse into expected components."""
match = re.fullmatch(
'^([0-9A-Za-z_\-]+)/([0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
url_token
)
if match:
return match.group(1), match.group(2)
return None, None | 48a3c4cd3aeada3b4c07fbfe6646e5d96441d920 | 235,815 |
def double(f):
""" Return a function that applies f twice.
f -- a function that takes one argument
>>> def square(x):
... return x**2
>>> double(square)(2)
16
"""
def repeated(x):
return f(f(x))
return repeated | 88e48a069a031590a4de8efa873bd4efec931bcd | 340,804 |
def strip_prefix(prefix, string):
"""Strip prefix from a string if it exists.
:param prefix: The prefix to strip.
:param string: The string to process.
"""
if string.startswith(prefix):
return string[len(prefix):]
return string | 07dd3cc154dde290d77bfbf4028e8be34179a128 | 676,253 |
def equals(field, value):
"""Return function where input ``field`` value is equal to ``value``"""
return lambda x: x.get(field) == value | 2b49e8b1c803e22cc9f236f35d6498f3bb2a0189 | 93,974 |
import toml
def readToml(filename):
"""Read a single TOML configuration file, or return an empty dict
if it doesn't exist.
"""
try:
with open(filename, encoding='utf-8') as fp:
return toml.load(fp)
except OSError:
return {}
except toml.TomlDecodeError as err:
... | b5d0761015cd1fbeb94bfb771a7ac30fb2c35d3d | 18,165 |
import tempfile
def get_temp_file_name(format):
"""
Gets a temporary file name for the image
Parameters
------------
format
Format of the target image
"""
filename = tempfile.NamedTemporaryFile(suffix='.' + format)
return filename.name | 2ade2cbdb9f013c3e631290a50dd153f5cb28a74 | 505,320 |
import re
def is_mixed_case(s):
"""
>>> is_mixed_case('HiThere')
True
>>> is_mixed_case('Hi There')
True
>>> is_mixed_case('hi there')
False
>>> is_mixed_case('h')
False
>>> is_mixed_case('H')
False
>>> is_mixed_case(None)
False
"""
if not isinstance(s... | 9f7244597fc0823e70db584f32d5e3d66df759b0 | 616,196 |
def _format_paths(paths, indent_level=1):
"""Format paths for inclusion in a script."""
separator = ',\n' + indent_level * ' '
return separator.join(paths) | aa51a16d1f9574d32272465f02de93744d896cea | 190,762 |
from typing import OrderedDict
def task_list_table_format(result):
"""Format task list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Task Id'] = item['id']
table_row['State'] = item['state']
table_row['Exit Code'] = str(item['exec... | 9aad66622ad228f941e367d0b0e6b9e4db03f255 | 327,588 |
def get_object(arr, str_card):
""" Get Card Object using its User Input string representation
Args:
arr: array of Card objects
str_card: Card descriptor as described by user input, that is a 2 character
string of Rank and Suit of the Card. For example, KH for King of Hearts.
Returns:
object pointer corresp... | 94666c1b6415a1b167f7d0b50591efe193cf5ca8 | 617,426 |
def _convert_native_shape_to_list(dims):
"""
Takes a list of `neuropod_native.Dimension` objects and converts to a list of python types
"""
out = []
for dim in dims:
if dim.value == -2:
# It's a symbol
out.append(dim.symbol)
elif dim.value == -1:
#... | dd2db666a19600a1bb7ad48cc78bf9765ec373d8 | 227,240 |
def _sumround(i):
"""sum all values in iterable `i`, and round the result to
the 5th decimal place
"""
return round(sum([n for n in i if n]), 5) | ffa244c6be363efb80888186e4f19fc0b6fd0b5e | 355,949 |
def last_scan_for_person(scan_set, person):
"""Return the last scan in the set for the given person."""
scans_found = [s for s in scan_set if s.person == person]
return scans_found[-1] | 5174d9255ce4b836e885e04f68a35fe13c11808e | 514,778 |
def get_facts(cat_file="facts.txt"):
"""Returns a list of facts about cats from the cat file (one fact
per line)"""
with open(cat_file, "r") as cat_file:
return [line for line in cat_file] | b2e9666bc1a833d25e73e61529c256f43bfb5c3b | 44,498 |
def snapToGround(world, location, blueprint):
"""Mutates @location to have the same z-coordinate as the nearest waypoint in @world."""
waypoint = world.get_map().get_waypoint(location)
# patch to avoid the spawn error issue with vehicles and walkers.
z_offset = 0
if blueprint is not None and ("vehicle" in blueprin... | 19c8cfe080aa96a01819f26c3bdcae8bb6a4c3be | 233,913 |
import torch
def evaluate_ece(confidences: torch.Tensor,
true_labels: torch.Tensor,
n_bins: int = 15) -> float:
"""
Args:
confidences (Tensor): a tensor of shape [N, K] of predicted confidences.
true_labels (Tensor): a tensor of shape [N,] of ground truth labe... | 052ca3804019bd319ec9c6b7451c088aa47e9f62 | 572,257 |
def tracks_of_artist(df, column=str, artist=str):
"""
Calcula las caciones del artista seleccionado
:param df: dataframe a analizar
:param column: columna a selccionar con el nombre del artista
:param artist: nombre del artista
:return: int, la cantidad de canciones que tiene el artita
"""
... | eb7b0b597fc8948d4efe5ae20ab59bcf49c74c1a | 146,614 |
def filter_and_drop_frame(df):
"""
Select in-frame sequences and then drop that column.
"""
return df.query('frame_type == "In"').drop('frame_type', axis=1) | 57745b684271772f00cf43e5eb5a6393b91fcb73 | 143,372 |
def get_last_month(month, year):
"""
Get last month of given month and year
:param month: given month
:param year: given year
:return: last month and it's year
"""
if month == 1:
last_month = 12
last_year = year - 1
else:
last_month = month - 1
last_year =... | a78de7164ee652903712f02d8c71a262eeb2e4f4 | 585,779 |
def get_cmdb_detail(cmdb_details):
"""
Iterate over CMDB details from response and convert them into RiskSense context.
:param cmdb_details: CMDB details from response
:return: List of CMDB elements which includes required fields from resp.
"""
return [{
'Order': cmdb_detail.get('order'... | aa2750b3754d2a776d847cfa22ff2b84f53bb351 | 20,932 |
def gcd(a,b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a | 59e7afdb04968c9d63ab0fce69fa75e2834eeebb | 508,641 |
def nbr(b8, b12):
"""
Normalized Burn Ratio \
(García and Caselles, 1991. Named by Key and Benson, 1999).
.. math:: NBR = (b8 - b12) / (b8 + b12)
:param b8: NIR.
:type b8: numpy.ndarray or float
:param b12: SWIR 2.
:type b12: numpy.ndarray or float
:returns NBR: Index value
.... | 7679148b18da62834f05c48e69536037f5ba40a3 | 386,338 |
def _get_caption(table):
"""
Get the caption of the associated wiki table.
Parameters
----------
table: BeautifulSoup
Returns
-------
str
"""
caption_text = None
caption = table.find("caption")
if caption:
caption_text = caption.text.strip()
return c... | 552925afb8e788e2f6cf03ff84ca1a4062f085ff | 69,189 |
def nir_mean(msarr,nir_band=7):
"""
Calculate the mean of the (unmasked) values of the NIR (near infrared) band
of an image array. The default `nir_band` value of 7 selects the NIR2 band
in WorldView-2 imagery. If you're working with a different type of imagery,
you will need figure out the appropri... | 7ba6ea8b7d51b8942a0597f2f89a05ecbee9f46e | 709,610 |
def dict_to_string(d, order=[], exclude=[], entry_sep="_", kv_sep=""):
"""
Turn a dictionary into a string by concatenating all key and values
together, separated by specified delimiters.
d: a dictionary. It is expected that key and values are simple literals
e.g., strings, float, integers, no... | 55a11507dc6dacbaadcfca736839a74ecc45622a | 333,448 |
def parse_datetime_component(name, obj):
"""Parse datetime accessor arrays.
The `datetime accessors`_ of :obj:`xarray.DataArray` objects are treated in
semantique as a component of the temporal dimension. Parsing them includes
adding :attr:`value_type <semantique.processor.structures.Cube.value_type>`
and :a... | 590f23d1acbba9cb568b9ee5fb30419cceeec954 | 193,060 |
def relu(x):
""" ReLU function (maximum of input and zero). """
return (0 < x).if_else(x, 0) | 773fc17688d00537f45d586a6f8ad316b29165e2 | 475,602 |
def get_combined_keys(dicts):
"""
>>> sorted(get_combined_keys([{'foo': 'egg'}, {'bar': 'spam'}]))
['bar', 'foo']
"""
seen_keys = set()
for dct in dicts:
seen_keys.update(dct.keys())
return seen_keys | d737c034237959881ad6e46ddaf21617700fee1f | 138,325 |
import pickle
def load(infile):
"""
Load a pickle file.
"""
filename = infile.split('.')[0]+'.pickle'
with open(filename, 'rb') as f:
return pickle.load(f) | 6d7b0e60620ba40f00976c91c1b7eeffa59451d3 | 457,151 |
from typing import Sequence
def is_blank(value):
"""Returns True if a value is considered empty or blank."""
return value in (None, "") or (isinstance(value, Sequence) and len(value) == 0) | c5d7afba76a367b67a0586d5624b02de8ba9b904 | 478,851 |
import json
def writeJson(file_name, data):
"""
Writes given dict data to given file_name as json.
Args:
file_name (string): Path to write data to.
data (dict): dict to write to given file_name.
Returns:
(string): full path where json file is.
"""
with open(file_name... | e17092d15ae1988ea9b34045834b23a8bef82219 | 569,665 |
def get_seasons(df):
"""
Changes months into season
Parameters
----------
df : dataframe
the forest fire dataframe
Returns
-------
Array
Seasons the months are associated with
"""
seasons = ["NONE"] * len(df)
for x in range(0, len(df)):
m = df.loc[x... | bee62e066ee8439fb04ada471e3ebebe16d27365 | 102,015 |
def add_chars() -> bytes:
"""Returns list of all possible bytes for testing bad characters"""
# bad_chars: \x00
chars = b""
chars += b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
chars += b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
chars += b"\x20\x21\x2... | cce8008085e6480642dad23b8e3a11728912d9ae | 669,826 |
def skipdoc(func_or_class):
"""Instruct Sphinx not to generate documentation for ``func_or_class``
Parameters
----------
func_or_class : function or class
Function or class not to document
Returns
-------
object
Wrapped function or class
"""
func_or_class.plastid_sk... | cfb3b543ac104d3d803091459a59f22c19efb0fd | 269,084 |
def read_group_list_text_file(group_list_text_file):
"""Read in the group-level analysis participant-session list text file."""
with open(group_list_text_file, "r") as f:
group_list = f.readlines()
# each item here includes both participant and session, and this also will
# become the main ID ... | 02cd5b76b6e3b2a7a30a6b0e277f48f2a1f313e7 | 239,442 |
def jsModuleDeclaration(name):
"""
Generate Javascript for a module declaration.
"""
var = ''
if '.' not in name:
var = 'var '
return '%s%s = {"__name__": "%s"};' % (var, name, name) | e53119d96fe87edbc7e52766b46c9ed2a33fa4ae | 391,337 |
def _int_endf(s):
"""Convert string to int. Used for INTG records where blank entries
indicate a 0.
Parameters
----------
s : str
Integer or spaces
Returns
-------
integer
The number or 0
"""
s = s.strip()
return int(s) if s else 0 | 63150eed7d9f968d323bfc870b348191163e4401 | 235,217 |
def get_status(result):
"""
Given a CheckResult, return its status ID.
"""
return result.value["status"] | 2f105326f02e514dfb8cae7edeff66bf1e15da6d | 244,437 |
def find_containers(bag, bag_rules):
"""Find the bags that can contain a specified bag."""
allowed = []
for n, item in bag_rules.items():
if bag in item.keys():
allowed.append(n)
return allowed | 8c0d2dd33f2ea8ce8aa60c4ba6e0af005022754f | 616,531 |
import json
def get_local_facts_from_file(filename):
""" Retrieve local facts from fact file
Args:
filename (str): local facts file
Returns:
dict: the retrieved facts
"""
try:
with open(filename, 'r') as facts_file:
local_facts = json.load(facts... | b566fb622ed92f01fe04393ba49116756da84efa | 429,106 |
def pentad_to_jday(pentad, pmin=0, day=3):
"""
Returns day of year for a pentad (indexed from pmin).
Input day determines which day (1-5) in the pentad to return.
Usage: jday = pentad_to_jday(pentad, pmin)
"""
if day not in range(1, 6):
raise ValueError('Invalid day ' + str(day))
... | 6582c2710f2694a887b57c761586c5fda79601c7 | 399,050 |
def is_empty(node):
"""Checks whether the :code:`node` is empty."""
return node == [] | 08dca99334a08c979df52d48ce9ef1c767f544e6 | 50,514 |
import inspect
def get_first_nondeprecated_class(cls):
"""Get the first non-deprecated class in class hierarchy.
For internal use only, no backwards compatibility guarantees.
Args:
cls: A class which may be marked as a deprecated alias.
Returns:
First class in the given class's class hierarchy (tra... | ecff9a233e6c591fa3d7f64e4c01f519e4f7d38b | 275,805 |
def process_small_clause(graph, cycle, cut=True):
"""
Match a cycle if there is a small clause relationship: verb with outgoing edge ARG3/H to a preposition node, the
preposition node has an outgoing edge ARG1/NEQ, and
1) an outgoing edge ARG2/NEQ, or
2) an outgoing edge ARG2/EQ to a noun;
ARG2/... | 4cc714838efc47b2de8c35821763249286039299 | 26,216 |
def parent_directory(path):
"""
Get parent directory. If root, return None
"" => None
"foo/" => "/"
"foo/bar/" => "foo/"
"""
if path == '':
return None
prefix = '/'.join(path.split('/')[:-2])
if prefix != '':
prefix += '/'
return prefix | 261943945531fc348c46c49f5d3081cbd815bfdb | 21,083 |
def second(items):
"""
Gets the second item from a collection.
"""
return items[1] | fae12532263ff519f22dffe721eaebfb39186c08 | 356,953 |
def payload_string(nibble1, nibble2, nibble3, nibble4):
"""Returns the string representation of a payload."""
return'0x{:X}{:X}{:X}{:X}'.format(nibble1, nibble2, nibble3, nibble4) | aa80620ebcaec8bebb087fb953d065f9165cc2c0 | 47,804 |
def remove_comments(s):
"""
Examples
--------
>>> code = '''
... # comment 1
... # comment 2
... echo foo
... '''
>>> remove_comments(code)
'echo foo'
"""
return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#")) | 1d3e1468c06263d01dd204c5ac89235a17f50972 | 3,840 |
import grp
def getgid(group):
"""Get gid for group
"""
if type(group) is str:
gid = grp.getgrnam(group).gr_gid
return gid
elif type(group) is int:
gid = grp.getgrgid(group).gr_gid
return gid | 3ee267aecd13df48d655a566c9679aca6af1fb97 | 352,214 |
def get_task_id_from_name(task_name, project_tasks):
"""
get task_id from task_name
"""
result = None
if project_tasks is not None:
for task in project_tasks:
if task["name"] == task_name:
result = task["id"]
if result is None:
raise RuntimeError("Task... | 22a72889576dcec998f51a67b0229c0b43e05bf7 | 509,366 |
from typing import List
import shlex
def split(string: str) -> List[str]:
"""
Split string (which represents a command) into a list.
This allows us to just copy/paste command prefixes without having to define a full list.
"""
return shlex.split(string) | 360fceeba7d6280e27068f61d2420cfd9fbfbcc2 | 706,133 |
def get_txt_text_from_path(filepath : str) -> str:
"""Extract text in a txt file
Arguments:
filepath {str} -- path to the txt file
Returns:
str -- text in the txt file
"""
with open(filepath, 'r') as f:
text = f.read()
return text.strip() | f3c0318cb994144214bc5c61e4b52bc194c83ecd | 309,592 |
def Mw_Mw_Generic(MagSize, MagError):
"""
Generic 1:1 conversion
"""
return (MagSize, MagError) | 23fad6e7cd1af221be25066cf3ce3f3a644e193e | 403,970 |
def is_scalar(x):
"""
>>> is_scalar(1)
True
>>> is_scalar(1.1)
True
>>> is_scalar([1, 2, 3])
False
>>> is_scalar((1, 2, 3))
False
>>> is_scalar({'a': 1})
False
>>> is_scalar({1, 2, 3})
False
>>> is_scalar('spam')
True
"""
try:
len(x)
except... | b8ee1536df04dda1e071a6e84dce66e4c576e42e | 623,998 |
def rgb_to_hex(rgb):
"""
Translates a RGB color to its hex format.
"""
return '#%02x%02x%02x' % rgb | 48ff35a4522e51b88e97800510ecc91e7d4840fa | 136,495 |
def adamant_code(aiida_local_code_factory):
"""Get a adamant code.
"""
executable = '/home/fmoitzi/CLionProjects/mEMTO/cmake-build-release' \
'-gcc-8/kgrn/source_lsf/kgrn'
adamant_code = aiida_local_code_factory(executable=executable,
e... | 7a0069960d1c7b265695ff1bd3074ea6943c62cc | 238,025 |
def get_x_y_values(tg, num_words=50):
"""
Gets a list of most frequently occurring words, with the specific number of occurrences
:param tg: (TermGenerator) Object with the parsed sentences.
:param num_words: (int) Number of words to be processed for the top occurring terms.
:return: (List) List of ... | 9584851d7261f4c5d8d279fa721fbe281e40e5b6 | 650,188 |
import re
def increment(s):
""" look for the last sequence of number(s) in a string and increment """
lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')
m = lastNum.search(s)
if m:
next = str(int(m.group(1))+1)
start, end = m.span(1)
s = s[:max(end-len(next), start)] + next + s[en... | 918c72990f04fcc36884deeb1e1d5a846b86ea12 | 689,101 |
from typing import ChainMap
def merge_dict(dicts):
"""Merge a list of dicts into a single dict """
return dict(ChainMap(*dicts)) | fdc3d2301c787235f5c8252190b290d1a8368e2b | 403,807 |
def avg(nums):
"""Returns the average (arithmetic mean) of a list of numbers"""
return float(sum(nums)) / len(nums) | 58fee328732c51e4355c29dd0489d163fdeaa4d1 | 327,028 |
def _find_file_type(file_names, extension):
"""
Returns files that end with the given extension from a list of file names.
"""
return [f for f in file_names if f.lower().endswith(extension)] | d18c84b1d76d25dc3e71cb70c4c5717b6a1ed6de | 417,207 |
def get_assign_default_value_rule(variable_name: str, default_value_parameter_name: str):
"""
Returns a rule that sets a default value for a variable.
@param variable_name: The name of the variable whose default should be set (as a string)
@param default_value_parameter_name: The name of the parameter ... | 4423374980c32c18c8dc6f49eadcf058c49ac31b | 617,270 |
def d_opt(param,value,extra_q=0):
"""
Create string "-D param=value"
"""
sym_q=""
if extra_q==1:
sym_q="\""
return("-D "+param+"="+sym_q+value+sym_q+" ") | 04daa34d3eca92e60651e763ee08553acd9cf331 | 665,058 |
def strip_spaces(s):
""" Strip excess spaces from a string """
return u" ".join([c for c in s.split(u' ') if c]) | b3b02fb01887b48b6a94d0181cb777ccab6db1f5 | 446,200 |
def _non_executed_cells_count(cell_list):
"""The function takes a list of cells and returns the number of non-executed cells
Args:
cell_list(list): list of dictionary objects representing the notebook cells
Returns:
non_exec_cells: number of non-executed cells in the list
... | 06de43b45dd8880e4d193df6d4c8cd364f10dd29 | 445,735 |
import requests
import json
def get_invoice(amt: int, memo: str) -> str:
"""
Returns a Lightning Invoice from the Tallycoin API
"""
tallydata = {'type': 'fundraiser', 'id': 'zfxqtu', 'satoshi_amount': str(amt), 'payment_method': 'ln',
'message': memo}
response = requests.post('h... | 777d4d4fa39d91cf9ddace89716a1ae96acc5e80 | 114,069 |
def device_get_from_facts(module, device_name):
"""
Get device information from CVP facts.
Parameters
----------
module : AnsibleModule
Ansible module.
device_name : string
Hostname to search in facts.
Returns
-------
dict
Device facts if found, else None.
... | 55549b178f14f665f3c48a4e750be39ca70d61ab | 650,143 |
def city_state(city, state, population=0):
"""Return a string representing a city-state pair."""
output_string = city.title() + ", " + state.title()
if population:
output_string += ' - population ' + str(population)
return output_string | ae958598a57128cf36f63ff6bfb8181f9d07db31 | 22,028 |
import random
def generate_name(start, markov_chain, max_words=2):
"""Generate a new town name, given a start syllable and a Markov chain.
This function takes a single start syllable or a list of start syllables,
one of which is then chosen randomly, and a corresponding Markov chain to
generate a new... | dd40e0ad715bf8957d9bfcfc701997883766f7ca | 691,775 |
def extract_vulnerabilities(debian_data, base_release='jessie'):
"""
Return a sequence of mappings for each existing combination of
package and vulnerability from a mapping of Debian vulnerabilities
data.
"""
package_vulnerabilities = []
for package_name, vulnerabilities in debian_data.item... | f22cc3507388b768363d4c4f2efd8054b5331113 | 169,771 |
def response(code, description):
"""
Decorates a function with a set of possible HTTP response codes that
it can return.
Args:
code: The HTTP code (i.e 404)
description: A human readable description
"""
def response_inner(function):
if not hasattr(function, 'doc_response... | 4912d09c2e7bb30ebba7c2f6989160be4d124e8d | 117,007 |
def get_column_as_list(matrix, column_no):
"""
Retrieves a column from a matrix as a list
"""
column = []
num_rows = len(matrix)
for row in range(num_rows):
column.append(matrix[row][column_no])
return column | 0f8f234fa9c68852d1c2f88049e2d0fea0df746d | 682,637 |
def get_lemmas(synset):
""" Look up and return all lemmas of a given synset. """
lemmas = synset.lemma_names()
return lemmas | e24decdd2af6b65f5c495d9949ef8ff9aaa5c8da | 83,928 |
def module_exists(course, module_name):
"""
Tests whether a module exists for a course
Looks for an existing module of the same name.
Returns the 'items_url' of the existing module
or an empty string if it does not yet exists.
"""
for module in course.get_modules():
if module.name ==... | cab676aa703120f6234492b93e19640b23e6bd49 | 360,050 |
from datetime import datetime
def to_time(s):
""" Captures time from image name and convert to time variable """
s = s.replace('/Users/lucasosouza/Documents/CarND/P3-final/IMG/center_', '')
s = s.replace('.jpg', '')
s = datetime.strptime(s, '%Y_%m_%d_%H_%M_%S_%f')
return s | 0225aff50916537e5c68607cc37c93d20dd76e1f | 85,620 |
def _parse_endpoint_url(urlish):
"""
If given a URL, return the URL and None. If given a URL with a string and
"::" prepended to it, return the URL and the prepended string. This is
meant to give one a means to supply a region name via arguments and
variables that normally only accept URLs.
""... | bf3defcf9aeaca43d8aa8d7ba645cd0ba11b99f6 | 696,785 |
def port_in_rule(port, rule):
"""
Return True or False if port is covered by a security group rule.
:param port: port to check
:type port: int
:param rule: security group rule to check
:return: True or False if port is covered by a security group rule.
:rtype: bool
"""
try:
... | 9e3f8ac5eb8d3506b5cf8bff06ed0b59a46400d8 | 320,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.