seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def cli(ctx, tool_id, io_details=False, link_details=False):
"""Get details of a given tool.
Output:
Information about the tool's interface
"""
return ctx.gi.tools.show_tool(tool_id, io_details=io_details, link_details=link_details) | bigcode/self-oss-instruct-sc2-concepts |
def get_centroids(vertices, entities, dim=2):
"""Calculate the centroids of all the entities.
:param vertex: vertex coordinates of mesh
:type vertex: numpy.ndarray[float64 x dim]
:param entities: mesh connectivity
:type entities: numpy.ndarray[int x (dim+1)]
:param dim: dimension of mesh
:t... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
import fnmatch
def ignore_rules_for_url(spider, url):
"""
Returns a list of ignore rules from the given spider,
that are relevant to the given URL.
"""
ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {}
return itertools.chain.from_iterable(
rule_list
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_resource(admin_mc, request):
"""Remove a resource after a test finishes even if the test fails."""
client = admin_mc.client
def _cleanup(resource):
request.addfinalizer(lambda: client.delete(resource))
return _cleanup | bigcode/self-oss-instruct-sc2-concepts |
def fixture_make_queue(request, make_unique_name):
"""
Return a factory function that can be used to make a queue for testing.
:param request: The Pytest request object that contains configuration data.
:param make_unique_name: A fixture that returns a unique name.
:return: The factory function to ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def points_to_cartesian(batch: torch.Tensor) -> torch.Tensor:
"""
Transforms a batch of points in homogeneous coordinates back to cartesian
coordinates.
Args:
batch: batch of points in homogeneous coordinates. Should be of shape
BATCHSIZE x NUMPOINTS x NDIM+1
Ret... | bigcode/self-oss-instruct-sc2-concepts |
def dnsamp2(x):
"""Downsamples by a factor 2 a 2D numpy array"""
return x[::2,::2] | bigcode/self-oss-instruct-sc2-concepts |
def get_view_predicates(view):
"""Returns the given view's predicates as list with (predicate's class
name, predicate's value) pairs as items. Assumes the predicate's
value is stored an attribute ``val``.
"""
predicates = []
for predicate in getattr(view, "__predicates__", []):
if hasatt... | bigcode/self-oss-instruct-sc2-concepts |
def get_nth_line(file_name: str, line_no: int) -> str:
"""Return the given line of an input file.
:param line_no: Which line of the input file to return? Starts at 1!
:raises ValueError: line_no is too large for a small file or < 1.
"""
if line_no < 1:
raise ValueError(""""line_no" starts ... | bigcode/self-oss-instruct-sc2-concepts |
def __tuples(a):
"""map an array or list of lists to a tuple of tuples"""
return tuple(map(tuple, a)) | bigcode/self-oss-instruct-sc2-concepts |
def scale_filters(filters, multiplier, base):
"""Scale `filters` by `factor`and round to the nearest multiple of `base`.
Args:
filters: Positive integer. The original filter size.
multiplier: Positive float. The factor by which to scale the filters.
base: Positive integer. The number of filters will be... | bigcode/self-oss-instruct-sc2-concepts |
def map_values(function, dictionary):
"""
Transform each value using the given function. Return a new dict with transformed values.
:param function: keys map function
:param dictionary: dictionary to mapping
:return: dict with changed values
"""
return {key: function(value) for key, value ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def interpolate(low, high, n, method):
"""
Interpolates between two numeric values.
The *n* parameter specifies the number of values to interpoluate.
Specifically the number of classes that will result from the interpolated
values.
The *method* parameter specifies the interpolation method.... | bigcode/self-oss-instruct-sc2-concepts |
def nearest_neighbor_interpolation(points):
"""
Input: list of points (x, y).
Returns a function f(x) which returns y value of nearest neighbor for given
x. At the midpoints (when distances to 2 closest points are the same) value
of point with lower x value is returned.
"""
points.sort(key=l... | bigcode/self-oss-instruct-sc2-concepts |
def cache_get_langs(sql):
"""Get the list of languages from tooltip database."""
return [row[0] for row in sql.execute(
"SELECT DISTINCT lang FROM vars").fetchall()] | bigcode/self-oss-instruct-sc2-concepts |
def trigger_reactions(polymer: str) -> str:
"""
Triggers the polymer reactions and returns the polymer with all the
reactions applied.
The algorithm works by iterating through the polymer and comparing the
current unit against the next unit. If the next unit is the same as
the current one but d... | bigcode/self-oss-instruct-sc2-concepts |
def pep8_module_name(name):
"""Convert a module name to a PEP8 compliant module name.
* lowercase
* whitespace -> underscore
* dash -> underscore
"""
if name[0].isnumeric():
name = '_'+name
valid_module_name = name.lower().replace('-', '_').replace(' ', '_')
... | bigcode/self-oss-instruct-sc2-concepts |
def put_list_to(path_to_file: str, lines: list):
"""
Write a list to a file in lines.
:param str path_to_file: /path/to/file
:param list lines: source list
:return: str
"""
with open(path_to_file, 'w') as fp:
content = list()
for line in lines:
content.append('{}... | bigcode/self-oss-instruct-sc2-concepts |
def get_geotag(post_content):
"""Gets latitude and longitude from post's HTML content."""
post_map = post_content.find("div", {"id": "map"})
geotag = {"lat": "", "lon": ""}
if post_map is not None:
geotag["lat"] = post_map.attrs["data-latitude"]
geotag["lon"] = post_map.attrs["data-longi... | bigcode/self-oss-instruct-sc2-concepts |
def get_hosted_zone_id(session, hosted_zone):
"""Look up Hosted Zone ID by DNS Name
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hosted_zone (string) : DNS Name of the Hosted Zone to loo... | bigcode/self-oss-instruct-sc2-concepts |
def assert_variable_type(variable, expected_type, raise_exception=True):
"""Return True if a variable is of a certain type or types.
Otherwise raise a ValueError exception.
Positional arguments:
variable -- the variable to be checked
expected_type -- the expected type or types of the variable
r... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def get_all_assembled_contigs(cxn, bit_score=0, length=0):
"""Get all assembled contigs."""
sql = """
SELECT iteration, contig_id, seq, description, bit_score, len,
query_from, query_to, query_strand,
hit_from, hit_to, hit_strand
FROM aux.assemble... | bigcode/self-oss-instruct-sc2-concepts |
def convert_from_CAL_to_k(data):
"""
Transforms from CAL to k using k = (1 - CAL)
"""
return 1 - data | bigcode/self-oss-instruct-sc2-concepts |
def word_count(text):
"""
Count number word in text
Args:
text (str): string text
Returns:
(int): number of word in text
"""
if isinstance(text, str):
tokens = text.split(" ")
else:
tokens = []
return len(tokens) | bigcode/self-oss-instruct-sc2-concepts |
def cast_str_to_int_float_bool_or_str(str_, fmt='{:.3f}'):
"""
Convert string into the following data types (return the first successful): int, float, bool, or str.
:param str_: str;
:param fmt: str; formatter for float
:return: int, float, bool, or str;
"""
value = str(str_).strip()
f... | bigcode/self-oss-instruct-sc2-concepts |
def exists(env):
""" Check if `gtags` module has been loaded in the environment """
return env['GTAGS'] if 'GTAGS' in env else None | bigcode/self-oss-instruct-sc2-concepts |
def filter_matching_fields(fields, other_fields):
"""return fields which are same as in other_fields list, ignoring the case"""
other_fields_lowercase = set([f.lower() for f in other_fields])
return [f for f in fields if f.lower() in other_fields_lowercase] | bigcode/self-oss-instruct-sc2-concepts |
def get_file_attachment(res_client, incident_id, artifact_id=None, task_id=None, attachment_id=None):
"""
call the Resilient REST API to get the attachment or artifact data
:param res_client: required for communication back to resilient
:param incident_id: required
:param artifact_id: optional
:... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def literal(text: str) -> str:
"""
Quick way of 'quoting' the text
https://orgmode.org/manual/Literal-Examples.html
"""
return textwrap.indent(text, ': ', lambda line: True) | bigcode/self-oss-instruct-sc2-concepts |
def concatenate_dirs(dir1, dir2):
"""
Appends dir2 to dir1. It is possible that either/both dir1 or/and dir2 is/are None
"""
result_dir = dir1 if dir1 is not None and len(dir1) > 0 else ''
if dir2 is not None and len(dir2) > 0:
if len(result_dir) == 0:
result_dir = dir2
e... | bigcode/self-oss-instruct-sc2-concepts |
def intersection_lists(lst1, lst2):
""" Return the intersection between two lists """
return list(set(lst1) & set(lst2)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def find_mine_pythonic_alt(field: List) -> List[int]:
"""Finds mine location (pythonic alternative).
Examples:
>>> assert find_mine([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == [1, 1]
"""
return next(
[field.index(sub_field), sub_field.index(1)]
for sub_field ... | bigcode/self-oss-instruct-sc2-concepts |
def specieset(structure):
""" Returns ordered set of species.
Especially usefull with VASP since we are sure what the list of species
is always ordered the same way.
"""
tmp = [a.type for a in structure]
species = sorted(set(tmp), key=tmp.index)
return species | bigcode/self-oss-instruct-sc2-concepts |
async def get_db_name(pool):
"""Gets the name of the current database."""
return await pool.fetchval("SELECT current_database()") | bigcode/self-oss-instruct-sc2-concepts |
def extract_prime_power(a, p):
"""
Return s, t such that a = p**s * t, t % p = 0
"""
s = 0
if p > 2:
while a and a % p == 0:
s += 1
a //= p
elif p == 2:
while a and a & 1 == 0:
s += 1
a >>= 1
else:
raise ValueError("Nu... | bigcode/self-oss-instruct-sc2-concepts |
def get_K(jfdb):
"""
Infer K from jellyfish db.
"""
j = jfdb.rsplit('_', 1)[0].rsplit('-', 1)[-1]
assert j[0] == 'K'
return int(j[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def load_file_list(filename):
"""
Load a text file containing a list of filenames (or other strings) as a
Python list.
To obtain a list of DataFile objects, the result can easily be converted
as in the example:
>>> raw_biases = DataFileList(load_file_list('list_of_biases.txt'))
If the lis... | bigcode/self-oss-instruct-sc2-concepts |
def create_choice(klass, choices, subsets, kwargs):
"""Create an instance of a ``Choices`` object.
Parameters
----------
klass : type
The class to use to recreate the object.
choices : list(tuple)
A list of choices as expected by the ``__init__`` method of ``klass``.
subsets : l... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def try_gpu(x):
"""Try to put a Variable/Tensor/Module on GPU."""
if torch.cuda.is_available():
return x.cuda()
return x | bigcode/self-oss-instruct-sc2-concepts |
def methods(attrdict):
"""Return all public methods and __init__ for some class."""
return {
name: method
for name, method in attrdict.items()
if callable(method)
and (not name.startswith("_") or name == "__init__")
} | bigcode/self-oss-instruct-sc2-concepts |
import time
def chop_midnight( tsecs ):
"""
Returns the epoch time at midnight for the given day.
"""
tup = time.localtime( tsecs )
tup = ( tup[0], tup[1], tup[2], 0, 0, 0, tup[6], tup[7], tup[8] )
return int( time.mktime( tup ) + 0.5 ) | bigcode/self-oss-instruct-sc2-concepts |
def difference_with(f, xs, ys):
"""Finds the set (i.e. no duplicates) of all elements in the first list not
contained in the second list. Duplication is determined according to the
value returned by applying the supplied predicate to two list elements"""
out = []
for x in xs:
if x in out:
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def roundup(x, n=10):
"""Round up x to multiple of n."""
return int(math.ceil(x / n)) * n | bigcode/self-oss-instruct-sc2-concepts |
def site(coord, size, xperiodic):
"""
numbering the square lattice sites
Parameters
--------------
site : (x, y)
(x, y) coordinate of the site
size : (int, int) -> (nx, ny)
linear size of the square lattice
xperiodic : boolean
indicates PBC along x
"""
nx, ny... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import logging
def get_news_from_steamNetAPI(game_id):
"""
This is the function that gets the latest news of a game from the Steam API.
Params:
game_id - Integer
Returns:
List - Contains 3 dictionaries with the 'actual' news.
"""
try:
game_news_api... | bigcode/self-oss-instruct-sc2-concepts |
def compute_overlap(bound1, bound2):
"""
Get the bound of the overlapping section between two bounds
:param bound1: bound where overlap is to be checked
:param bound2: bound where overlap is to be checked
:return: bound tuple of overlap between ``bound1`` and ``bound2``
if there is no overl... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_check_digit(number):
"""
Given a number without the check-digit, calculate
the check digit and return it.
See: https://www.gs1.org/services/how-calculate-check-digit-manually
"""
# Step 2: Multiply alternate position by 3 and 1
# and get the sum
step_2 = sum(
[int(... | bigcode/self-oss-instruct-sc2-concepts |
def b64max(char_length):
""" Maximum number of raw bits that can be stored in a b64 of length x """
# Four byte increments only, discard extra length
return (char_length // 4) * (3 * 8) | bigcode/self-oss-instruct-sc2-concepts |
def get_age_df(df, age_list):
"""Gets a DataFrame and filters it for the purpose of putting specific
ages on the Concordia plots. Note the DataFrame must have a column named
'age'.
Parameters
----------
df : DataFrame
A dataframe with a column 'age'.
age_list : list
A list o... | bigcode/self-oss-instruct-sc2-concepts |
def rm_duplicates(lis):
""" Takes a list, removes duplicates and returns it sorted. """
a_set = set(lis)
return sorted(a_set) | bigcode/self-oss-instruct-sc2-concepts |
def researched_before(technology, timestamp, player):
"""Check if a technology was researched before a given time."""
for item in player['research']:
if item['technology'] == technology and item['timestamp'] < timestamp:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def average(lst):
"""Averages a list, tuple, or set of numeric values"""
return sum(lst) / len(lst) | bigcode/self-oss-instruct-sc2-concepts |
def hasHandlers(self):
"""
See if this logger has any handlers configured.
Loop through all handlers for this logger and its parents in the
logger hierarchy. Return True if a handler was found, else False.
Stop searching up the hierarchy whenever a logger with the "propagate"
attribute set to ze... | bigcode/self-oss-instruct-sc2-concepts |
def cmp_column_indices(x,y):
"""Comparision function for column indices
x and y are XLS-style column indices e.g. 'A', 'B', 'AA' etc.
Returns -1 if x is a column index less than y, 1 if it is
greater than y, and 0 if it's equal.
"""
# Do string comparision on reverse of column indices
ret... | bigcode/self-oss-instruct-sc2-concepts |
def color_rgb(red, green, blue):
""" Given three intensities red, green, blue, all from 0 to 255,
returns the corresponding CSS color string e.g. '#ff00cc' """
return f"#{red*256**2 + green*256 + blue:06x}" | bigcode/self-oss-instruct-sc2-concepts |
import builtins
def _parse_warning(warn_str):
"""Reverse-engineer a warning string
Parameters
----------
warn_str : string
Returns
-------
(str, Warning, str, int)
message, category, filename, lineno
"""
tokens = warn_str.rstrip('\n').split(" ")
# The first token is
... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def expected_failure(exptn, msg=None):
"""
Wrapper for a test function, which expects a certain Exception.
Example::
@expected_failure(ValueError, "point must be an instance of lib.Point")
def test_result_error(self):
Result([1., 1.], 1.1)
@param Excepti... | bigcode/self-oss-instruct-sc2-concepts |
def elements_to_str(l):
""" Convert each element in an iterator to a string representation
Args:
l (:obj:`list`): an iterator
Returns:
:obj:`list`: a list containing each element of the iterator converted to a string
"""
return [str(e) for e in l] | bigcode/self-oss-instruct-sc2-concepts |
def fence_native_format(source, language, css_class, options, md):
"""Format source as div."""
return '<div class="%s">%s</div>' % (css_class, source) | bigcode/self-oss-instruct-sc2-concepts |
def add_inplace(X, varX, Y, varY):
"""In-place addition with error propagation"""
# Z = X + Y
# varZ = varX + varY
X += Y
varX += varY
return X, varX | bigcode/self-oss-instruct-sc2-concepts |
from typing import get_origin
from typing import Union
from typing import get_args
def is_type_SpecificOptional(f_type) -> bool:
"""
Returns true for types such as Optional[T], but not Optional, or T.
"""
return get_origin(f_type) is not None and f_type.__origin__ == Union and get_args(f_type)[1]() is... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_filterjs(url):
"""
Get filter.js file
:param url: base url for timetabling system
:return: filter.js text
"""
url = url + 'js/filter.js'
source = requests.get(url).text
return source | bigcode/self-oss-instruct-sc2-concepts |
def parseBands(band, allBands, error):
"""Parses a string that specifies bands.
Bands are horizontal rectangles defined with respect to lines.
They correspond with regions of interest where we try to find specific
marks, such as commas and accents.
Parameters
----------
band: string or Non... | bigcode/self-oss-instruct-sc2-concepts |
def GeojsonCheck(filename):
"""
Checks if filename is of type geojson
:param str filename: filename to check
:returns: bool - True if filename ends with geojson; otherwise False
"""
if filename.endswith('.geojson'):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def volume_bars(df, volume_column, threshold):
"""
Computes volume bars (index)
:param df: pd.DataFrame()
:param volume_column: (str) name for the column with volume data
:param m: (int) threshold for volume
:return idx: returns list of indices
"""
t = df[volume_column]
ts = 0
... | bigcode/self-oss-instruct-sc2-concepts |
def multiply_by_u(x, u=(9, 4), d=5):
"""
Multiply x with u, interpreting as numbers from the field sqrt(d). Where u is a fundamental solution.
Args:
x: <tuple> (a,b) to be interpreted as (a+b*sqrt(d))
u: <tuple> (u1,u2) to be interpreted as (u1+u2*sqrt(d))
d: <int>
Returns: (x,y... | bigcode/self-oss-instruct-sc2-concepts |
def zeroth_order(t: float, q: list, k: float) -> float:
"""Simple zeroth-order rate function.
:param t: model time
:param q: Vector (list) of mass distribution through compartments (not actually used but required argument for ODE solver)
:param k: Time constant of the rate function.
:returns:... | bigcode/self-oss-instruct-sc2-concepts |
def construct_conn_msg(stream, lines=None, protocol_opts=None):
"""Return a connnection message
:param stream: stream name
:param lines: number of messages to consume
:param protocol_opts: optional arguments
"""
connection_msg = stream
if lines:
connection_msg += ' {0}'.format(lines... | bigcode/self-oss-instruct-sc2-concepts |
def MultipleReplace(Text, ReplaceDict):
"""
Perform multiple replacements in one go using the replace dictionary
in format: { 'search' : 'replace' }
"""
NewText = Text
for Search, Replace in ReplaceDict.items():
NewText = NewText.replace(Search, str(Replace))
return NewText | bigcode/self-oss-instruct-sc2-concepts |
import logging
def check_proc_type(image_proc_type):
""" check_proc_type function checks to make sure image_proc_type is a string
:param image_proc_type: user selected processing technique
:raises ValueError: if image_proc_type is not a string
:returns True: if pass test """
if isins... | bigcode/self-oss-instruct-sc2-concepts |
def gcd(n1, n2):
"""
Recursive function to return the GCD of n1 and n2
"""
if n1 == 0:
return n2
return gcd(n2 % n1, n1) | bigcode/self-oss-instruct-sc2-concepts |
def wrap_with_links(obj, links, val, root_path, many=False):
"""Adds links key to object (first argument) based on links dictionary and value"""
if many:
for item in obj:
item['links'] = {}
for key in links:
item['links'][key] = root_path + links[key].format(item[... | bigcode/self-oss-instruct-sc2-concepts |
def GetNegativeResult(line):
"""Extract the name of the negative result from line."""
line = line[len("@remove "):]
return line.strip() | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def generate_key(num_chars=32):
"""
Generate a unique key.
:param num_chars: Number of characters.
:return: Key of num_chars length
"""
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(num_chars)) | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(s):
"""check if a string is a palindrome"""
return s == s[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def best_case_name(obj):
"""Take an object and return the highest quality case name possible.
In general, this means returning the fields in an order like:
- case_name
- case_name_full
- case_name_short
Assumes that the object passed in has all of those attributes.
"""
if ... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dict(d1, d2):
"""Merge two dictionaries
The second dictionary `d2` overwrites values in `d1` if they have
common keys. This is equivilent to
return {**d1, **2}
in python3. Using this function improves python2--3
compatibility.
"""
out = d1.copy()
out.update(d2)
... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def get_docstring(target) -> str:
"""
Retrieves the documentation string from the target object and returns it
after removing insignificant whitespace
:param target:
The object for which the doc string should be retrieved
:return:
The cleaned documentation string f... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def filter_line(
line: str,
filters: typing.Optional[typing.Iterable[str]]
) -> typing.Optional[str]:
"""
Filters out line that contain substring
Args:
line: line to filter
filters: filter strings to apply
Returns: line if not filter are found in line, e... | bigcode/self-oss-instruct-sc2-concepts |
def parse_item(item):
"""
Parse a CVE item from the NVD database
"""
parsed_items = {}
cve = item.get('cve', {})
CVE_data_meta = cve.get('CVE_data_meta', {})
ID = CVE_data_meta.get('ID', '')
parsed_items['id'] = ID
affects = cve.get('affects', {})
vendor = affects.get('vendor'... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def convert_to_instruction_dict(installation_str: str) -> Dict[str, str]:
"""Convert given string to dict.
Args:
installation_str (str): The string to be converted.
Returns:
Dict[str, str]: Expected dict
"""
return {"cmd": installation_str} | bigcode/self-oss-instruct-sc2-concepts |
def fix_aspect_providers(lib_providers):
"""Change a list of providers to be returnable from an aspect.
Args:
lib_providers: A list of providers, e.g., as returned from forward_deps().
Returns:
A list of providers which is valid to return from an aspect.
"""
# The DefaultInfo provider... | bigcode/self-oss-instruct-sc2-concepts |
def pairs_to_dict(items: list) -> dict:
"""Example: ['MESSAGES', '3', 'UIDNEXT', '4'] -> {'MESSAGES': '3', 'UIDNEXT': '4'}"""
if len(items) % 2 != 0:
raise ValueError('An even-length array is expected')
return dict((items[i * 2], items[i * 2 + 1]) for i in range(len(items) // 2)) | bigcode/self-oss-instruct-sc2-concepts |
def fig(fig, include_plotlyjs='cdn', full_html:bool=False)->str:
"""Returns html for a plotly figure. By default the plotly javascript is not
included but imported from the plotly cdn, and the full html wrapper is not included.
Args:
include_plotlyjs (bool, str): how to import the necessary javascr... | bigcode/self-oss-instruct-sc2-concepts |
def _triangles(dg):
"""
Return a list of all oriented triangles in the digraph ``dg``.
EXAMPLES::
sage: from sage.combinat.cluster_algebra_quiver.mutation_type import _triangles
sage: Q = ClusterQuiver(['A',3])
sage: _triangles(Q.digraph())
[]
sage: Q.mutate([0,1])
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def wrf_times_to_datetime(wrfdata,timename='Times',format='%Y-%m-%d_%H:%M:%S'):
"""Convert WRF times to datetime format"""
timestrs = wrfdata.variables['Times'][:]
if hasattr(timestrs[0],'values'):
# xarray
return [ datetime.strptime(s.values.tostring().decode... | bigcode/self-oss-instruct-sc2-concepts |
def get_higher_closing_price(df):
"""returns the exchange with the higher closing price"""
# exchange 1 has higher closing price
if (df['close_exchange_1'] - df['close_exchange_2']) > 0:
return 1
# exchange 2 has higher closing price
elif (df['close_exchange_1'] - df['close_exchange_2']) <... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def normalize(clip, mean, std):
"""
Normalise clip by subtracting mean and dividing by standard deviation
Parameters
----------
clip : torch.tensor
video clip
mean : tuple
Tuple of mean values for each channel
std : tuple
Tuple of standard deviation va... | bigcode/self-oss-instruct-sc2-concepts |
import re
def fix_varptr_calls(vba_code):
"""
Change calls like VarPtr(foo(0)) to VarPtr(foo) so we can report on the
whole byte array.
"""
# Do we have any VarPtr() calls?
if ("VarPtr(" not in vba_code):
return vba_code
vba_code = re.sub(r"(VarPtr\(\w+)\(0\)\)", r'\1)', vba_code)... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def checksum(file, method='sha1', chunk_size=4096):
"""Calculate the checksum of a file.
"""
h = hashlib.new(method)
with open(file, 'rb') as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
h.update(chunk)
return h.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def _exist_key(key, **kwargs):
"""
check whether key is exsit in the kwargs and kwargs[key] is not None.
"""
is_exist = key in kwargs
is_not_none = kwargs[key] is not None if is_exist else None
return is_exist and is_not_none | bigcode/self-oss-instruct-sc2-concepts |
def duration_to_string(duration):
"""Format a duration in seconds as a string.
Args:
duration (float): The duration in seconds.
Return:
A more human-readable version of the string (for example, "3.5 hours" or
"93 milliseconds").
"""
if duration > 3600 * 24:
duration_str = "{0:0.1f} days".f... | bigcode/self-oss-instruct-sc2-concepts |
def cli(ctx, quota_id, deleted=False):
"""Display information on a quota
Output:
A description of quota.
For example::
{'bytes': 107374182400,
'default': [],
'description': 'just testing',
'display_amount': '100.0 GB',
'groups': [],
... | bigcode/self-oss-instruct-sc2-concepts |
def rank_results(results):
"""Ranks the results of the hyperparam search, prints the ranks and returns them.
Args:
results (list): list of model configs and their scores.
Returns:
list: the results list reordered by performance.
"""
ranking = sorted(results, key=lambda k: k["score"... | bigcode/self-oss-instruct-sc2-concepts |
def indent(unindented, n_spaces=2):
"""
Indent a multi-line string using spaces.
"""
indent = " " * n_spaces
newline = "\n" + indent
return indent + newline.join(unindented.split("\n")) | bigcode/self-oss-instruct-sc2-concepts |
def getAverageRGBOld(image):
"""
Given PIL Image, return average value of color as (r, g, b)
"""
# no. of pixels in image
npixels = image.size[0] * image.size[1]
# get colors as [(cnt1, (r1, g1, b1)), ...]
cols = image.getcolors(npixels)
# get [(c1*r1, c1*g1, c1*g2),...]
sumRGB = [(x... | bigcode/self-oss-instruct-sc2-concepts |
def match(cmd, s):
""" Check if cmd has the required parts of s and any of the optional part.
"""
parts = s.split('-')
start = parts[0]
if len(parts) > 1:
end = parts[1]
else:
end = ""
return cmd.startswith(start) and (start+end).startswith(cmd) | bigcode/self-oss-instruct-sc2-concepts |
def has_failed(node):
"""
Check whether status is "failed".
To avoid false positives check whether status is one of "pass" or "none".
:param node: XML node holding status as text.
:returns: Whether the status is reported as "failed".
"""
return (node.text.strip() not in ['pass', 'none']) | bigcode/self-oss-instruct-sc2-concepts |
def _has_active_network_in_vlan(vlan):
"""
Check if there are any other active network in the vlan
this is used because some equipments remove all the L3 config
when applying some commands, so they can only be applyed at the first time
or to remove interface vlan configuration
:param vlan: vlan... | bigcode/self-oss-instruct-sc2-concepts |
def func(x, a, b, c):
"""
Second degree polynomial function of the form
f(x) = ax^2 + bx + c
:param x: input variable
:param a: second deg coeff
:param b: first deg coeff
:param c: zeroth deg coeff
:return: f(x)
"""
return a*x**2 + b*x + c | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.