uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0300cd7ff4afca2481edc9e | train | function | def count_viewable(row, col, m, flipped_m):
"""Before coming in, should pad with a border of 2
This allows np.diagonal() to work.
m = np.pad(m, pad_width=2, mode='constant', constant_values=0)
row, col = row+2, col+2
"""
val = m[row, col]
n_rows, n_cols = m.shape
up = m[:row, col][... | def count_viewable(row, col, m, flipped_m):
| """Before coming in, should pad with a border of 2
This allows np.diagonal() to work.
m = np.pad(m, pad_width=2, mode='constant', constant_values=0)
row, col = row+2, col+2
"""
val = m[row, col]
n_rows, n_cols = m.shape
up = m[:row, col][::-1]
down = m[row + 1 :, col]
left ... | == 0) and (viewable == 0):
arrive_rows.append(i)
arrive_cols.append(j)
# Will this chair vacate?
if (val == 1) and (viewable >= 5):
leave_rows.append(i)
leave_cols.append(j)
return (arrive_rows, arrive_... | 90 | 90 | 303 | 13 | 77 | UpwardTrajectory/advent-of-code | 2020/day11/day11.py | Python | count_viewable | count_viewable | 78 | 106 | 78 | 78 | c25d8b6ebb6adcac8f88c6c88230fb6a93536fad | bigcode/the-stack | train |
313ffbb78fe79702fe8fc1d9 | train | function | def map_area(data):
return np.array(
[[np.nan if c == "." else 0 for c in row] for row in data.split("\n")]
)
| def map_area(data):
| return np.array(
[[np.nan if c == "." else 0 for c in row] for row in data.split("\n")]
)
| import numpy as np
from chairs import sample, sample2, waiting_area
def map_area(data):
| 21 | 64 | 36 | 5 | 15 | UpwardTrajectory/advent-of-code | 2020/day11/day11.py | Python | map_area | map_area | 5 | 8 | 5 | 5 | 268b61823a014a3aaf2247221a48ee05c6b8df1e | bigcode/the-stack | train |
fe41c4defb1230de3e456d2c | train | function | def show_room(m):
"""NOT USED: Helper function to visualize using original characters"""
view_map = {np.nan: ".", 0: "L", 1: "#"}
z = np.vectorize(view_map.get)(m)
z = np.vectorize({"None": ".", "L": "L", "#": "#"}.get)(z)
z_printout = "\n".join("".join(row) for row in z)
return z_printout
| def show_room(m):
| """NOT USED: Helper function to visualize using original characters"""
view_map = {np.nan: ".", 0: "L", 1: "#"}
z = np.vectorize(view_map.get)(m)
z = np.vectorize({"None": ".", "L": "L", "#": "#"}.get)(z)
z_printout = "\n".join("".join(row) for row in z)
return z_printout
| occur, exit the cycle & return the total
number of seated visitors.
"""
m, still_in_flux = map_area(data), True
while still_in_flux:
m, still_in_flux = cycle_once(m, func)
return int(np.nansum(m))
def show_room(m):
| 64 | 64 | 99 | 5 | 59 | UpwardTrajectory/advent-of-code | 2020/day11/day11.py | Python | show_room | show_room | 144 | 150 | 144 | 144 | 037404b2e2f15d9f8e214481973d9d2556f28a19 | bigcode/the-stack | train |
477aff336717be8645be9c23 | train | function | def IsToeplitzMatrix(matrix):
if len(matrix) == 0:
return True
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
# Simply check if previous top left element is the same or not
if i-1 >= 0 and j-1 >= 0 and matrix[i-1][j-1] != ma... | def IsToeplitzMatrix(matrix):
| if len(matrix) == 0:
return True
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
# Simply check if previous top left element is the same or not
if i-1 >= 0 and j-1 >= 0 and matrix[i-1][j-1] != matrix[i][j]:
re... | :
# The diagonal "[1, 2]" has different elements.
#
# Constraints:
# m == matrix.length
# n == matrix[i].length
# 1 <= m, n <= 20
# 0 <= matrix[i][j] <= 99
def IsToeplitzMatrix(matrix):
| 64 | 64 | 103 | 8 | 55 | hanaa-abdelgawad/leetcode | python/easy/toeplitz.py | Python | IsToeplitzMatrix | IsToeplitzMatrix | 32 | 45 | 32 | 32 | 374c2a3278f4b08d5793b8bcca33361c19342d7f | bigcode/the-stack | train |
c9ea10bbd6287624bd703781 | train | class | class ProbeUtil(object):
def __init__(self, cookies=None, cookie_filename='cookie.txt'):
self.opener = None
self.cookie_filename = cookie_filename
self.cookies = cookies
if not self.cookies:
self.default_init()
self.opener = urllib2.build_opener(
... | class ProbeUtil(object):
| def __init__(self, cookies=None, cookie_filename='cookie.txt'):
self.opener = None
self.cookie_filename = cookie_filename
self.cookies = cookies
if not self.cookies:
self.default_init()
self.opener = urllib2.build_opener(
urllib2.HTTPCookieProcessor(co... | import urllib2
import urllib
import cookielib
class ProbeUtil(object):
| 18 | 70 | 234 | 6 | 11 | jasonljc/enterprise-price-monitor | django_monitor/price_monitor/spider/enterprise/enterprise/probe/util.py | Python | ProbeUtil | ProbeUtil | 5 | 37 | 5 | 6 | e3a456323bd67496c354113479d57104678720cb | bigcode/the-stack | train |
80359677be4993c424cc2b92 | train | function | @contextlib.contextmanager
def _handle_graph(handle):
with handle.graph.as_default():
yield
| @contextlib.contextmanager
def _handle_graph(handle):
| with handle.graph.as_default():
yield
|
from tensorflow.python.keras import backend
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_resource_variable_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
@contextlib.cont... | 64 | 64 | 22 | 12 | 51 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | _handle_graph | _handle_graph | 41 | 44 | 41 | 42 | f82beb76fa8232272593cc05df5440dcb420f3ed | bigcode/the-stack | train |
e9a0a8fb869b22dc5832634c | train | function | def _tensor_conversion(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
| def _tensor_conversion(var, dtype=None, name=None, as_ref=False):
| return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
| _op(), dtype)
if as_ref:
return self.handle
else:
return self.read_value()
# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
def _tensor_conversion(var, dtype=None, name=None, as_ref=False):
| 64 | 64 | 46 | 16 | 48 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | _tensor_conversion | _tensor_conversion | 245 | 246 | 245 | 245 | 2df4e9507639f8a9059af9f9bf57d28404d63db7 | bigcode/the-stack | train |
0ec52491f0671187622381db | train | function | @contextlib.contextmanager
def replicated_variable_for_optimizer(num_replicas):
"""Context manager for optimizer weights. Overrides K.variable."""
if num_replicas == 1:
yield
return
try:
old_v = backend.variable
def opt_variable(value, dtype=None, name=None, constraint=None):
"""Instantiat... | @contextlib.contextmanager
def replicated_variable_for_optimizer(num_replicas):
| """Context manager for optimizer weights. Overrides K.variable."""
if num_replicas == 1:
yield
return
try:
old_v = backend.variable
def opt_variable(value, dtype=None, name=None, constraint=None):
"""Instantiates a variable and returns it."""
if dtype is None:
dtype = backend... | ops.GraphKeys.TRAINABLE_VARIABLES)
l = g.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES)
for v in index.values():
if v in l:
l.remove(v)
g.add_to_collections(collections, result)
return result
return variable_scope.variable_scope(
"", custom_getter=_replicated_varia... | 94 | 94 | 316 | 16 | 78 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | replicated_variable_for_optimizer | replicated_variable_for_optimizer | 301 | 346 | 301 | 302 | 92b49afa01c2895cec0ea7edca929baa8ac38172 | bigcode/the-stack | train |
ab85e55418299e5e620184b1 | train | function | def replicated_fetch_function(var):
# pylint: disable=protected-access
return ([var._dense_var_to_tensor()], lambda v: v[0])
| def replicated_fetch_function(var):
# pylint: disable=protected-access
| return ([var._dense_var_to_tensor()], lambda v: v[0])
| as tensors.
def _tensor_conversion(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
def replicated_fetch_function(var):
# pylint: disable=protected-access
| 64 | 64 | 32 | 15 | 48 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | replicated_fetch_function | replicated_fetch_function | 249 | 251 | 249 | 250 | 9e8f66b98c42a40b874ba80eabc3f7c872b58937 | bigcode/the-stack | train |
635e5310586edc923c89a24d | train | function | def _enclosing_tpu_context():
# pylint: disable=protected-access
context = ops.get_default_graph()._get_control_flow_context()
# pylint: enable=protected-access
while context is not None and not isinstance(
context, control_flow_ops.XLAControlFlowContext):
context = context.outer_context
return cont... | def _enclosing_tpu_context():
# pylint: disable=protected-access
| context = ops.get_default_graph()._get_control_flow_context()
# pylint: enable=protected-access
while context is not None and not isinstance(
context, control_flow_ops.XLAControlFlowContext):
context = context.outer_context
return context
| from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
@contextlib.contextmanager
def _handle_graph(handle):
with handle.graph.as_default():
yield
def _enclosing_tpu_context():
# pylint: disable=protected-access
| 64 | 64 | 73 | 17 | 46 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | _enclosing_tpu_context | _enclosing_tpu_context | 47 | 54 | 47 | 48 | df4018e724dc7240c2efe51ef3b5a47cb0cabfcb | bigcode/the-stack | train |
67f12ef435eba89017f65d25 | train | function | def replicated_scope(num_replicas):
"""Variable scope for constructing replicated variables."""
def _replicated_variable_getter(getter, name, *args, **kwargs):
"""Getter that constructs replicated variables."""
collections = kwargs.pop("collections", None)
if collections is None:
collections = [o... | def replicated_scope(num_replicas):
| """Variable scope for constructing replicated variables."""
def _replicated_variable_getter(getter, name, *args, **kwargs):
"""Getter that constructs replicated variables."""
collections = kwargs.pop("collections", None)
if collections is None:
collections = [ops.GraphKeys.GLOBAL_VARIABLES]
k... | ) # pylint: disable=protected-access
def replicated_fetch_function(var):
# pylint: disable=protected-access
return ([var._dense_var_to_tensor()], lambda v: v[0])
# pylint: enable=protected-access
ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion)
ops.register_dense_tensor_like_ty... | 101 | 101 | 338 | 8 | 93 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | replicated_scope | replicated_scope | 261 | 298 | 261 | 261 | aeb50db66c03acb19a6ed5bbce958ffec11fd351 | bigcode/the-stack | train |
3e188f1197f8b72cc76d1d4e | train | class | class ReplicatedVariable(object):
"""A replicated variable for use on TPUs.
When accessed inside a tpu.replicate() context, this variable acts as if it
is a single variable whose handle is a replicated input to the computation.
Outside a tpu.replicate() context currently this object has pretty murky
semanti... | class ReplicatedVariable(object):
| """A replicated variable for use on TPUs.
When accessed inside a tpu.replicate() context, this variable acts as if it
is a single variable whose handle is a replicated input to the computation.
Outside a tpu.replicate() context currently this object has pretty murky
semantics, especially with respect to thi... | ==============================================================================
"""Distributed variable implementation for TPUs.
N.B. This is an experimental feature that should only be used for Keras support.
It is unsupported and will be removed in favor of Distribution Strategy soon.
"""
from __future__ import ab... | 256 | 256 | 1,264 | 6 | 249 | PaulWang1905/tensorflow | tensorflow/contrib/tpu/python/tpu/keras_tpu_variables.py | Python | ReplicatedVariable | ReplicatedVariable | 57 | 240 | 57 | 57 | 66a7f96dcb0640b1f6f7a1169fd8c7b8bfb2c645 | bigcode/the-stack | train |
1c7281c241ed86190efc92a8 | train | function | def main(number, inputExcel, NDVI, Surf_albedo, Surface_temp, water_mask,
proyDEM_fileName, QC_Map, year, DOY, hour, minutes, pixel_spacing,
UTM_Zone, Cold_Pixel_Constant, Hot_Pixel_Constant):
'''
Additional input now from excel sheet:
1. output_folder
2. Image_Type (1,2,3: LS, ... | def main(number, inputExcel, NDVI, Surf_albedo, Surface_temp, water_mask,
proyDEM_fileName, QC_Map, year, DOY, hour, minutes, pixel_spacing,
UTM_Zone, Cold_Pixel_Constant, Hot_Pixel_Constant):
| '''
Additional input now from excel sheet:
1. output_folder
2. Image_Type (1,2,3: LS, VIIRS, MODIS)
3. DEM_fileName (HydroSHED etc.)
4. Temp_inst (Constant, GLDAS or CFSR)
5. Temp_24 (Constant, GLDAS or CFSR)
6. RH_inst (Constant, GLDAS or CFSR)
7. RH_24 (Constan... |
September 2017
"""
import os
import shutil
import numpy as np
from osgeo import osr
import gdal
from math import sin, cos, pi
import subprocess
from openpyxl import load_workbook
from pyproj import Proj, transform
def main(number, inputExcel, NDVI, Surf_albedo, Surface_temp, water_mask,
proyDEM_fileN... | 120 | 120 | 403 | 60 | 59 | tylere/SEBAL | EESEBAL/EESEBAL_code.py | Python | main | main | 22 | 49 | 22 | 25 | df22f0097d25ce431a4167721c359ea319d4f567 | bigcode/the-stack | train |
c627b6142eee5b7abd32525e | train | class | class InsecureHTTPAdapter(HTTPAdapter):
def cert_verify(
self,
conn, # type: ConnectionPool
url, # type: str
verify, # type: Union[bool, str]
cert, # type: Optional[Union[str, Tuple[str, str]]]
):
# type: (...) -> None
super().cert_verify(co... | class InsecureHTTPAdapter(HTTPAdapter):
| def cert_verify(
self,
conn, # type: ConnectionPool
url, # type: str
verify, # type: Union[bool, str]
cert, # type: Optional[Union[str, Tuple[str, str]]]
):
# type: (...) -> None
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
... | -Length": stats.st_size,
"Last-Modified": modified,
})
resp.raw = open(pathname, "rb")
resp.close = resp.raw.close
return resp
def close(self):
# type: () -> None
pass
class InsecureHTTPAdapter(HTTPAdapter):
| 64 | 64 | 97 | 9 | 54 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | InsecureHTTPAdapter | InsecureHTTPAdapter | 224 | 234 | 224 | 225 | 2d3c74459d6905f7413b2ccf8fbb228656b963f1 | bigcode/the-stack | train |
f1a6eb92991f4b4b40664032 | train | function | def looks_like_ci():
# type: () -> bool
"""
Return whether it looks like pip is running under CI.
"""
# We don't use the method of checking for a tty (e.g. using isatty())
# because some CI systems mimic a tty (e.g. Travis CI). Thus that
# method doesn't provide definitive informatio... | def looks_like_ci():
# type: () -> bool
| """
Return whether it looks like pip is running under CI.
"""
# We don't use the method of checking for a tty (e.g. using isatty())
# because some CI systems mimic a tty (e.g. Travis CI). Thus that
# method doesn't provide definitive information in either direction.
return any(name in... | # Jenkins
'BUILD_ID',
# AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
'CI',
# Explicit environment variable.
'PIP_IS_CI',
)
def looks_like_ci():
# type: () -> bool
| 64 | 64 | 97 | 13 | 51 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | looks_like_ci | looks_like_ci | 88 | 96 | 88 | 89 | dcea873f197b4e14fbc61b4e9b73a2ad806b34fd | bigcode/the-stack | train |
ccd76c1cf3de03c8dd540f9d | train | class | class LocalFSAdapter(BaseAdapter):
def send(
self,
request, # type: PreparedRequest
stream=False, # type: bool
timeout=None, # type: Optional[Union[float, Tuple[float, float]]]
verify=True, # type: Union[bool, str]
cert=None, # type: Optional[Union[str, ... | class LocalFSAdapter(BaseAdapter):
| def send(
self,
request, # type: PreparedRequest
stream=False, # type: bool
timeout=None, # type: Optional[Union[float, Tuple[float, float]]]
verify=True, # type: Union[bool, str]
cert=None, # type: Optional[Union[str, Tuple[str, str]]]
proxies=Non... | else None
user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
if user_data is not None:
data["user_data"] = user_data
return "{data[installer][name]}/{data[installer][version]} {json}".format(
data=data,
json=json.dumps(data, separators=(",", ":"), sort_keys=True),
... | 85 | 86 | 288 | 7 | 78 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | LocalFSAdapter | LocalFSAdapter | 182 | 221 | 182 | 183 | 662adbb634111a5898ef334556388037ba815502 | bigcode/the-stack | train |
c10eab84945dd9cb390e71ab | train | function | def user_agent():
# type: () -> str
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": __version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
... | def user_agent():
# type: () -> str
| """
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": __version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
} # type: Dict[str, Any]
... | okay if the list is not comprehensive.
# For more background, see: https://github.com/pypa/pip/issues/5499
CI_ENVIRONMENT_VARIABLES = (
# Azure Pipelines
'BUILD_BUILDID',
# Jenkins
'BUILD_ID',
# AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
'CI',
# Explicit environm... | 209 | 209 | 698 | 12 | 197 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | user_agent | user_agent | 99 | 179 | 99 | 100 | 90e534cea878e850a198ea88d87cabcdf25f6c8a | bigcode/the-stack | train |
f28f5bd6ac5cf5c8a815e719 | train | class | class PipSession(requests.Session):
timeout = None # type: Optional[int]
def __init__(
self,
*args, # type: Any
retries=0, # type: int
cache=None, # type: Optional[str]
trusted_hosts=(), # type: Sequence[str]
index_urls=None, # type: Optional[Lis... | class PipSession(requests.Session):
| timeout = None # type: Optional[int]
def __init__(
self,
*args, # type: Any
retries=0, # type: int
cache=None, # type: Optional[str]
trusted_hosts=(), # type: Sequence[str]
index_urls=None, # type: Optional[List[str]]
**kwargs, # type: Any... | ": stats.st_size,
"Last-Modified": modified,
})
resp.raw = open(pathname, "rb")
resp.close = resp.raw.close
return resp
def close(self):
# type: () -> None
pass
class InsecureHTTPAdapter(HTTPAdapter):
def cert_veri... | 256 | 256 | 1,667 | 7 | 249 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | PipSession | PipSession | 250 | 449 | 250 | 251 | b0246133c909edfb2f929a394456d40b7d69614a | bigcode/the-stack | train |
c9f391d17492119159a87e41 | train | class | class InsecureCacheControlAdapter(CacheControlAdapter):
def cert_verify(
self,
conn, # type: ConnectionPool
url, # type: str
verify, # type: Union[bool, str]
cert, # type: Optional[Union[str, Tuple[str, str]]]
):
# type: (...) -> None
super(... | class InsecureCacheControlAdapter(CacheControlAdapter):
| def cert_verify(
self,
conn, # type: ConnectionPool
url, # type: str
verify, # type: Union[bool, str]
cert, # type: Optional[Union[str, Tuple[str, str]]]
):
# type: (...) -> None
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
... | Union[bool, str]
cert, # type: Optional[Union[str, Tuple[str, str]]]
):
# type: (...) -> None
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
class InsecureCacheControlAdapter(CacheControlAdapter):
| 64 | 64 | 98 | 10 | 54 | JE-Chen/je_old_repo | TimeWrapper_JE/venv/Lib/site-packages/pip/_internal/network/session.py | Python | InsecureCacheControlAdapter | InsecureCacheControlAdapter | 237 | 247 | 237 | 238 | 7d68a17580d4e097f9b16e137875b6e594618922 | bigcode/the-stack | train |
62b7358100b0f23eb2043356 | train | function | def format_supported_platforms(extension, out, width):
text = 'supported on: {}'.format(', '.join(extension.supported_platforms))
out.write('{}\n'.format(format_body(text, width)))
| def format_supported_platforms(extension, out, width):
| text = 'supported on: {}'.format(', '.join(extension.supported_platforms))
out.write('{}\n'.format(format_body(text, width)))
| width)
def format_extension_name(extension, out):
out.write('\n{}\n'.format(extension.name))
def format_extension_summary(extension, out, width):
out.write('{}\n'.format(format_body(strip_inlined_text(get_summary(extension)), width)))
def format_supported_platforms(extension, out, width):
| 63 | 64 | 43 | 11 | 52 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_supported_platforms | format_supported_platforms | 83 | 85 | 83 | 83 | 483e1e400f54c2240f9b41db6d512cb2e00613fa | bigcode/the-stack | train |
ca21a37d04b5673fa4f38ad9 | train | function | def format_extension_parameters(extension, out, width, shift=4):
out.write('parameters:\n\n')
param_texts = []
for param in extension.parameters:
description = format_paragraph(strip_inlined_text(param.description or ''), width - shift)
param_text = '{}'.format(param.name)
if param.m... | def format_extension_parameters(extension, out, width, shift=4):
| out.write('parameters:\n\n')
param_texts = []
for param in extension.parameters:
description = format_paragraph(strip_inlined_text(param.description or ''), width - shift)
param_text = '{}'.format(param.name)
if param.mandatory:
param_text += " (MANDATORY)"
param_... | multi-paragraph description, as already
# listed above.
description = get_description(extension).split('\n\n', 1)[-1]
out.write('{}\n'.format(format_body(strip_inlined_text(description), width)))
def format_extension_parameters(extension, out, width, shift=4):
| 63 | 64 | 212 | 14 | 49 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_extension_parameters | format_extension_parameters | 95 | 113 | 95 | 95 | 145f09d408f39006f161072629ccb04e166f2968 | bigcode/the-stack | train |
fb2a04ab1b1fa2a8b3624436 | train | class | class ShowCommand(Command):
name = 'show'
description = """
Display documentation for the specified extension (workload, instrument, etc.).
"""
def initialize(self, context):
self.parser.add_argument('name', metavar='EXTENSION',
help='''The name of the ext... | class ShowCommand(Command):
| name = 'show'
description = """
Display documentation for the specified extension (workload, instrument, etc.).
"""
def initialize(self, context):
self.parser.add_argument('name', metavar='EXTENSION',
help='''The name of the extension for which information ... | Loader, settings
from wlauto.utils.doc import (get_summary, get_description, get_type_name, format_column, format_body,
format_paragraph, indent, strip_inlined_text)
from wlauto.utils.misc import get_pager
from wlauto.utils.terminalsize import get_terminal_size
class ShowCommand(Command):
... | 69 | 69 | 232 | 5 | 63 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | ShowCommand | ShowCommand | 28 | 58 | 28 | 29 | cb062561405d6a3064ed649960ac88c4baf328e0 | bigcode/the-stack | train |
27c1f836ab49c64939b66247 | train | function | def format_extension_name(extension, out):
out.write('\n{}\n'.format(extension.name))
| def format_extension_name(extension, out):
| out.write('\n{}\n'.format(extension.name))
| hasattr(extension, 'supported_platforms'):
format_supported_platforms(extension, out, width)
out.write('\n')
if extension.parameters:
format_extension_parameters(extension, out, width)
out.write('\n')
format_extension_description(extension, out, width)
def format_extension_name(... | 64 | 64 | 20 | 8 | 56 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_extension_name | format_extension_name | 75 | 76 | 75 | 75 | f420ca02c0ae632cbe373c8fca3fe8b52538c167 | bigcode/the-stack | train |
87814518d06fc2195efef4eb | train | function | def format_extension(extension, out, width):
format_extension_name(extension, out)
out.write('\n')
format_extension_summary(extension, out, width)
out.write('\n')
if hasattr(extension, 'supported_platforms'):
format_supported_platforms(extension, out, width)
out.write('\n')
if ex... | def format_extension(extension, out, width):
| format_extension_name(extension, out)
out.write('\n')
format_extension_summary(extension, out, width)
out.write('\n')
if hasattr(extension, 'supported_platforms'):
format_supported_platforms(extension, out, width)
out.write('\n')
if extension.parameters:
format_extension_... | sp = subprocess.Popen(pager, stdin=subprocess.PIPE)
sp.communicate(text)
except OSError:
self.logger.warning('Could not use PAGER "{}"'.format(pager))
sys.stdout.write(text)
else:
sys.stdout.write(text)
def format_extension(... | 64 | 64 | 97 | 9 | 55 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_extension | format_extension | 61 | 72 | 61 | 61 | d3019cd4ae089e9f2e9c12c26a7cbc4ff86421ff | bigcode/the-stack | train |
bd1fe1eac8d0d2b09f576576 | train | function | def format_extension_description(extension, out, width):
# skip the initial paragraph of multi-paragraph description, as already
# listed above.
description = get_description(extension).split('\n\n', 1)[-1]
out.write('{}\n'.format(format_body(strip_inlined_text(description), width)))
| def format_extension_description(extension, out, width):
# skip the initial paragraph of multi-paragraph description, as already
# listed above.
| description = get_description(extension).split('\n\n', 1)[-1]
out.write('{}\n'.format(format_body(strip_inlined_text(description), width)))
| ):
text = 'supported on: {}'.format(', '.join(extension.supported_platforms))
out.write('{}\n'.format(format_body(text, width)))
def format_extension_description(extension, out, width):
# skip the initial paragraph of multi-paragraph description, as already
# listed above.
| 63 | 64 | 66 | 30 | 33 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_extension_description | format_extension_description | 88 | 92 | 88 | 90 | 602bedd4c6b3065630bdf123a611f29c4343cff9 | bigcode/the-stack | train |
4a575363051c5ce836d6b6c7 | train | function | def format_extension_summary(extension, out, width):
out.write('{}\n'.format(format_body(strip_inlined_text(get_summary(extension)), width)))
| def format_extension_summary(extension, out, width):
| out.write('{}\n'.format(format_body(strip_inlined_text(get_summary(extension)), width)))
| ('\n')
if extension.parameters:
format_extension_parameters(extension, out, width)
out.write('\n')
format_extension_description(extension, out, width)
def format_extension_name(extension, out):
out.write('\n{}\n'.format(extension.name))
def format_extension_summary(extension, out, width):
| 64 | 64 | 30 | 10 | 54 | JaviMerino/workload-automation | wlauto/commands/show.py | Python | format_extension_summary | format_extension_summary | 79 | 80 | 79 | 79 | a175b7d574da9353a29a6d7bff2f84b5f8a7e5a2 | bigcode/the-stack | train |
481d93da29862cb9f69333a6 | train | function | @pytest.mark.asyncio
async def test_401_refresh_failure(aresponses, login_success_response):
"""Test that multiple 401 responses in a row raises the right exception."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dump... | @pytest.mark.asyncio
async def test_401_refresh_failure(aresponses, login_success_response):
| """Test that multiple 401 responses in a row raises the right exception."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufyl... |
import aiohttp
import pytest
from eufy_security import async_login
from eufy_security.errors import InvalidCredentialsError, RequestError
from eufy_security.types import ParamType
from .common import TEST_EMAIL, TEST_PASSWORD, load_fixture
@pytest.mark.asyncio
async def test_401_refresh_failure(aresponses, login_su... | 73 | 73 | 245 | 19 | 53 | jpty/python-eufy-security | tests/test_api.py | Python | test_401_refresh_failure | test_401_refresh_failure | 15 | 45 | 15 | 16 | 508b4a89e2f17e382df2e0f7fd29e58093523c40 | bigcode/the-stack | train |
b7d9b95f701780b10fcfcc71 | train | function | @pytest.mark.asyncio
async def test_empty_response(aresponses, login_success_response):
"""Test the odd use case that arises when a response is empty."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success... | @pytest.mark.asyncio
async def test_empty_response(aresponses, login_success_response):
| """Test the odd use case that arises when a response is empty."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
... | _response.json"),
status=200,
),
)
async with aiohttp.ClientSession() as websession:
with pytest.raises(InvalidCredentialsError):
await async_login(TEST_EMAIL, "bad_password", websession)
@pytest.mark.asyncio
async def test_empty_response(aresponses, login_success_respon... | 64 | 64 | 206 | 17 | 47 | jpty/python-eufy-security | tests/test_api.py | Python | test_empty_response | test_empty_response | 132 | 156 | 132 | 133 | 878394fb5180106af7b1d284be796bb4229c8e44 | bigcode/the-stack | train |
650163b162e78b7a7b6436c5 | train | function | @pytest.mark.asyncio
async def test_http_error(aresponses, login_success_response):
"""Test the Eufy Security web API returning a non-2xx HTTP error code."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=None, status=500),
... | @pytest.mark.asyncio
async def test_http_error(aresponses, login_success_response):
| """Test the Eufy Security web API returning a non-2xx HTTP error code."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=None, status=500),
)
async with aiohttp.ClientSession() as websession:
with pytest.rais... | )
async with aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
history = await api.async_get_history()
assert len(history) == 2
@pytest.mark.asyncio
async def test_http_error(aresponses, login_success_response):
| 64 | 64 | 110 | 17 | 46 | jpty/python-eufy-security | tests/test_api.py | Python | test_http_error | test_http_error | 246 | 258 | 246 | 247 | 23bbb8fd863a0e9abaacaf4e4c645069b114ab32 | bigcode/the-stack | train |
11a9f9c79f820c3da823938c | train | function | @pytest.mark.asyncio
async def test_401_refresh_success(aresponses, login_success_response):
"""Test that a 401 response re-authenticates successfully."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_succes... | @pytest.mark.asyncio
async def test_401_refresh_success(aresponses, login_success_response):
| """Test that a 401 response re-authenticates successfully."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
... | =load_fixture("hub_list_response.json"), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/passport/login",
"post",
aresponses.Response(text=None, status=401),
)
async with aiohttp.ClientSession() as websession:
with pytest.raises(InvalidCredential... | 108 | 108 | 363 | 19 | 89 | jpty/python-eufy-security | tests/test_api.py | Python | test_401_refresh_success | test_401_refresh_success | 48 | 94 | 48 | 49 | 20c36702c9b2ae886cd98b05e8ff749007077846 | bigcode/the-stack | train |
c77dabc57c8f246f6e60c95f | train | function | @pytest.mark.asyncio
async def test_get_history(aresponses, login_success_response):
"""Test getting the device history."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)... | @pytest.mark.asyncio
async def test_get_history(aresponses, login_success_response):
| """Test getting the device history."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_devs_l... | )
async with aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
api._token_expiration = datetime.now() - timedelta(seconds=10)
await api.async_update_device_info()
assert len(api.devices) == 2
@pytest.mark.asyncio
async def test_ge... | 79 | 79 | 266 | 17 | 61 | jpty/python-eufy-security | tests/test_api.py | Python | test_get_history | test_get_history | 210 | 243 | 210 | 211 | fafde31a4fe658c8e5cf2fc868cb1ae09dcb59bd | bigcode/the-stack | train |
3fe2b322b879b730090832a9 | train | function | @pytest.mark.asyncio
async def test_bad_email(aresponses):
"""Test authenticating with a bad email."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(
text=load_fixture("login_failure_invalid_email_response.json"), sta... | @pytest.mark.asyncio
async def test_bad_email(aresponses):
| """Test authenticating with a bad email."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(
text=load_fixture("login_failure_invalid_email_response.json"), status=200
),
)
async with aiohttp.ClientSess... | load_fixture("hub_list_response.json"), status=200),
)
async with aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
assert len(api.devices) == 2
@pytest.mark.asyncio
async def test_bad_email(aresponses):
| 64 | 64 | 115 | 13 | 50 | jpty/python-eufy-security | tests/test_api.py | Python | test_bad_email | test_bad_email | 97 | 111 | 97 | 98 | b2a8fe2cfd28ead0a57a36bd8f0dd4a9b14f57bf | bigcode/the-stack | train |
906d87ba038d286c723dda86 | train | function | @pytest.mark.asyncio
async def test_set_params_for_station(aresponses, login_success_response):
"""Test setting station params."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200)... | @pytest.mark.asyncio
async def test_set_params_for_station(aresponses, login_success_response):
| """Test setting station params."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_devs_list"... | _response.json"), status=200
),
)
async with aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
device = next(iter(api.devices.values()))
await api.async_set_params(device, {ParamType.SNOOZE_MODE: True})
@pytest.mark.asyncio
asy... | 85 | 85 | 285 | 19 | 66 | jpty/python-eufy-security | tests/test_api.py | Python | test_set_params_for_station | test_set_params_for_station | 407 | 442 | 407 | 408 | a8e8588144a0ad1ac114024e73eda93a77100b65 | bigcode/the-stack | train |
b5e2c729188957f1dd8c5c58 | train | function | @pytest.mark.asyncio
async def test_login_success(aresponses, login_success_response):
"""Test a successful login and API object creation."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), ... | @pytest.mark.asyncio
async def test_login_success(aresponses, login_success_response):
| """Test a successful login and API object creation."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v... | "/api/v1/passport/login",
"post",
aresponses.Response(text=None, status=500),
)
async with aiohttp.ClientSession() as websession:
with pytest.raises(RequestError):
await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
@pytest.mark.asyncio
async def test_login_succ... | 75 | 75 | 250 | 17 | 58 | jpty/python-eufy-security | tests/test_api.py | Python | test_login_success | test_login_success | 261 | 291 | 261 | 262 | 47d9ead90fc7545e366e46b5f01363f352e69466 | bigcode/the-stack | train |
612a3ae541e7478b6c24da00 | train | function | @pytest.mark.asyncio
async def test_bad_password(aresponses):
"""Test authenticating with a bad password."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(
text=load_fixture("login_failure_invalid_password_response.js... | @pytest.mark.asyncio
async def test_bad_password(aresponses):
| """Test authenticating with a bad password."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(
text=load_fixture("login_failure_invalid_password_response.json"),
status=200,
),
)
async with... | _invalid_email_response.json"), status=200
),
)
async with aiohttp.ClientSession() as websession:
with pytest.raises(InvalidCredentialsError):
await async_login("bad_email@host.com", TEST_PASSWORD, websession)
@pytest.mark.asyncio
async def test_bad_password(aresponses):
| 64 | 64 | 113 | 13 | 51 | jpty/python-eufy-security | tests/test_api.py | Python | test_bad_password | test_bad_password | 114 | 129 | 114 | 115 | 8afe31d6113db1931c4632606a9bf6d0c9c834d8 | bigcode/the-stack | train |
1e2dbe603f443c1bb319cf2c | train | function | @pytest.mark.asyncio
async def test_start_stream(aresponses, login_success_response):
"""Test starting the RTSP stream."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
... | @pytest.mark.asyncio
async def test_start_stream(aresponses, login_success_response):
| """Test starting the RTSP stream."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_devs_lis... | aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
assert api._email == TEST_EMAIL
assert api._password == TEST_PASSWORD
assert api._token is not None
assert api._token_expiration is not None
assert len(api.devices) == 2... | 89 | 89 | 299 | 17 | 71 | jpty/python-eufy-security | tests/test_api.py | Python | test_start_stream | test_start_stream | 294 | 330 | 294 | 295 | e1ce7cbc97d38d2e3e771d4bbdb3529bd77a10f3 | bigcode/the-stack | train |
1b1525e88fede22c440abe24 | train | function | @pytest.mark.asyncio
async def test_expired_access_token(aresponses, login_success_response):
"""Test that an expired access token refreshes automatically and correctly."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.... | @pytest.mark.asyncio
async def test_expired_access_token(aresponses, login_success_response):
| """Test that an expired access token refreshes automatically and correctly."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eu... | .Response(text=load_fixture("empty_response.json"), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_hub_list",
"post",
aresponses.Response(text=load_fixture("hub_list_response.json"), status=200),
)
async with aiohttp.ClientSession() as websessio... | 116 | 116 | 387 | 19 | 97 | jpty/python-eufy-security | tests/test_api.py | Python | test_expired_access_token | test_expired_access_token | 159 | 207 | 159 | 160 | ef485a35bee9c160dfeb0f856828ea52c4adf4e0 | bigcode/the-stack | train |
45254d2d1554908f1e0072df | train | function | @pytest.mark.asyncio
async def test_set_params_for_device(aresponses, login_success_response):
"""Test setting device params."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
... | @pytest.mark.asyncio
async def test_set_params_for_device(aresponses, login_success_response):
| """Test setting device params."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_devs_list",... | ",
aresponses.Response(text=load_fixture("stop_stream_response.json"), status=200),
)
async with aiohttp.ClientSession() as websession:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
device = next(iter(api.devices.values()))
await api.async_stop_stream(device)
@p... | 84 | 84 | 283 | 19 | 65 | jpty/python-eufy-security | tests/test_api.py | Python | test_set_params_for_device | test_set_params_for_device | 369 | 404 | 369 | 370 | 4d45b948d8da1a35b67cd07deccd661f96ce0491 | bigcode/the-stack | train |
70b1b0362d12e5eb7822e1e5 | train | function | @pytest.mark.asyncio
async def test_stop_stream(aresponses, login_success_response):
"""Test stopping the RTSP stream."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
... | @pytest.mark.asyncio
async def test_stop_stream(aresponses, login_success_response):
| """Test stopping the RTSP stream."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
aresponses.add(
"security-app.eufylife.com",
"/v1/app/get_devs_lis... | session:
api = await async_login(TEST_EMAIL, TEST_PASSWORD, websession)
device = next(iter(api.devices.values()))
stream_url = await api.async_start_stream(device)
assert stream_url == "rtmp://p2p-vir-6.eufylife.com/hls/123"
@pytest.mark.asyncio
async def test_stop_stream(aresponses, log... | 80 | 80 | 267 | 17 | 63 | jpty/python-eufy-security | tests/test_api.py | Python | test_stop_stream | test_stop_stream | 333 | 366 | 333 | 334 | 6147fa05719d12188a0e821971225147d9883a38 | bigcode/the-stack | train |
b7634a005cf94e40c0a0d7c0 | train | class | class DerivedTag(AnnotationSchema):
'''Basic spatial tag using DerivedSpatialPoint information'''
pt = mm.fields.Nested(DerivedSpatialPoint, required=True)
tag = mm.fields.String(required=True, description="Description of point")
| class DerivedTag(AnnotationSchema):
| '''Basic spatial tag using DerivedSpatialPoint information'''
pt = mm.fields.Nested(DerivedSpatialPoint, required=True)
tag = mm.fields.String(required=True, description="Description of point")
| AnnotationSchema
import marshmallow as mm
class DerivedSpatialPoint(BoundSpatialPoint):
dependent_chunk = NumericField(description='Chunk id for the point at the time the annotation was made',
required=True)
level = NumericField(description='Chunk level',
... | 64 | 64 | 49 | 7 | 57 | spapa013/EMAnnotationSchemas | emannotationschemas/schemas/derived_spatial_point.py | Python | DerivedTag | DerivedTag | 12 | 15 | 12 | 12 | 568c2e6796245aae7f12dd869ce865848507d4c3 | bigcode/the-stack | train |
98e4ce3c6d7a18ca24de97dc | train | class | class DerivedSpatialPoint(BoundSpatialPoint):
dependent_chunk = NumericField(description='Chunk id for the point at the time the annotation was made',
required=True)
level = NumericField(description='Chunk level',
required=False)
| class DerivedSpatialPoint(BoundSpatialPoint):
| dependent_chunk = NumericField(description='Chunk id for the point at the time the annotation was made',
required=True)
level = NumericField(description='Chunk level',
required=False)
| from emannotationschemas.schemas.base import BoundSpatialPoint, NumericField, AnnotationSchema
import marshmallow as mm
class DerivedSpatialPoint(BoundSpatialPoint):
| 32 | 64 | 48 | 9 | 22 | spapa013/EMAnnotationSchemas | emannotationschemas/schemas/derived_spatial_point.py | Python | DerivedSpatialPoint | DerivedSpatialPoint | 5 | 9 | 5 | 5 | b3245617ebadd7a665985ad0f2ff4fc8bf78ac22 | bigcode/the-stack | train |
ee1d66359ac819c056a35a0d | train | function | def read_log_file(file):
data_vals = np.loadtxt(file, delimiter=',', skiprows=1)
with open(file, 'r') as f:
line = f.readline().strip()
header = line.split(',')
data = {}
for i in range(len(header)):
data[header[i]] = data_vals[:, i]
return data
| def read_log_file(file):
| data_vals = np.loadtxt(file, delimiter=',', skiprows=1)
with open(file, 'r') as f:
line = f.readline().strip()
header = line.split(',')
data = {}
for i in range(len(header)):
data[header[i]] = data_vals[:, i]
return data
| plt.legend(ncol=1, loc='upper right')
plt.xlabel(x_label, fontsize=15)
plt.ylabel(y_label, fontsize=15)
plt.ylim(0.04, 0.3)
sns.despine()
plt.savefig(save_file)
def read_log_file(file):
| 64 | 64 | 77 | 6 | 58 | frosinastojanovska/schnetpack | experiments/loss_visualization.py | Python | read_log_file | read_log_file | 26 | 36 | 26 | 26 | 164d482ee5e00e67d0a5e6841116b2a656dbd3bc | bigcode/the-stack | train |
1420eedabe4884ca062e955a | train | function | def plot_testing_results(labels, suffix):
data = {'method': [], 'Dataset and metric': [], 'Value': []}
for label in labels:
data['method'].extend([label.split('_')[-1]] * 6)
with open(f'data/schnet_{label}/test_eval.txt', 'r') as f:
_ = f.readline()
mae, rmse = list(map(f... | def plot_testing_results(labels, suffix):
| data = {'method': [], 'Dataset and metric': [], 'Value': []}
for label in labels:
data['method'].extend([label.split('_')[-1]] * 6)
with open(f'data/schnet_{label}/test_eval.txt', 'r') as f:
_ = f.readline()
mae, rmse = list(map(float, f.readline().strip().split(',')))
... | E_energy_U0']
plot_loss(all_data, labels, f'mae_energy_{suffix}.png', x_label='Epoch number', y_label='MAE value',
title='MAE energy U0')
all_data = {}
for label in labels:
all_data[label] = read_log_file(f'data/schnet_{label}/log/log.csv')['RMSE_energy_U0']
plot_loss(all_data, la... | 130 | 130 | 434 | 8 | 122 | frosinastojanovska/schnetpack | experiments/loss_visualization.py | Python | plot_testing_results | plot_testing_results | 65 | 96 | 65 | 65 | 420a05e4a7db18f824a9bd376ef375ed023690ac | bigcode/the-stack | train |
e1a1770ceb89ff83703baca6 | train | function | def plot_train_progress(labels, suffix):
all_data = {}
for label in labels:
all_data[label] = read_log_file(f'data/schnet_{label}/log/log.csv')['Validation loss']
plot_loss(all_data, labels, f'validation_loss_{suffix}.png', x_label='Epoch number', y_label='Loss value',
title='Validatio... | def plot_train_progress(labels, suffix):
| all_data = {}
for label in labels:
all_data[label] = read_log_file(f'data/schnet_{label}/log/log.csv')['Validation loss']
plot_loss(all_data, labels, f'validation_loss_{suffix}.png', x_label='Epoch number', y_label='Loss value',
title='Validation loss')
all_data = {}
for label... | plt.savefig(save_file)
def read_log_file(file):
data_vals = np.loadtxt(file, delimiter=',', skiprows=1)
with open(file, 'r') as f:
line = f.readline().strip()
header = line.split(',')
data = {}
for i in range(len(header)):
data[header[i]] = data_vals[:, i]
return data
def pl... | 90 | 90 | 303 | 8 | 81 | frosinastojanovska/schnetpack | experiments/loss_visualization.py | Python | plot_train_progress | plot_train_progress | 39 | 62 | 39 | 39 | b89b949efa3071ddd80013e5c24304c12eafe20a | bigcode/the-stack | train |
dc3919a3aa3db3ab768994a6 | train | function | def plot_loss(data, data_labels_to_plot, save_file, x_label='', y_label='', title=''):
assert len(data_labels_to_plot) > 0
plt.clf()
plt.style.use('classic')
sns.set()
sns.set_style("ticks")
sns.set_palette("Paired")
x = np.array(range(list(data.values())[0].shape[0]))
for label in data_... | def plot_loss(data, data_labels_to_plot, save_file, x_label='', y_label='', title=''):
| assert len(data_labels_to_plot) > 0
plt.clf()
plt.style.use('classic')
sns.set()
sns.set_style("ticks")
sns.set_palette("Paired")
x = np.array(range(list(data.values())[0].shape[0]))
for label in data_labels_to_plot:
plt.plot(x, data[label], 'o-', label=label)
plt.title(title... | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def plot_loss(data, data_labels_to_plot, save_file, x_label='', y_label='', title=''):
| 44 | 64 | 173 | 22 | 21 | frosinastojanovska/schnetpack | experiments/loss_visualization.py | Python | plot_loss | plot_loss | 7 | 23 | 7 | 7 | e67996fcab05c5bcc2e37739d77254a6008a4869 | bigcode/the-stack | train |
b6a31461964efb8e7ccd5c6d | train | function | def fetch_tick_dataset(dataset_path, data_home=None, n_features=None,
verbose=True):
"""Fetch dataset from tick_datasets github repository.
Uses cache if this dataset has already been downloaded.
Parameters
----------
dataset_path : `str`
Dataset path on tick_datasets... | def fetch_tick_dataset(dataset_path, data_home=None, n_features=None,
verbose=True):
| """Fetch dataset from tick_datasets github repository.
Uses cache if this dataset has already been downloaded.
Parameters
----------
dataset_path : `str`
Dataset path on tick_datasets github repository. For example
"binary/adult/adult.trn.bz2" for adult train dataset
data_home :... | None
and not configured with TICK_DATASETS environement variable
all tick datasets are stored in '~/tick_datasets' subfolders.
verbose : `bool`, default=True
If True, download progress bar will be printed
Returns
-------
cache_path : `str`
File path of the downloaded dat... | 120 | 120 | 401 | 19 | 101 | sumau/tick | tick/dataset/download_helper.py | Python | fetch_tick_dataset | fetch_tick_dataset | 109 | 156 | 109 | 110 | 3a08b98fd5737fc78ee044a60d020a115c553f44 | bigcode/the-stack | train |
e60774ef9bb1518ba5588edc | train | function | def clear_data_home(data_home=None):
"""Delete all the content of the data home cache.
"""
data_home = get_data_home(data_home)
shutil.rmtree(data_home)
| def clear_data_home(data_home=None):
| """Delete all the content of the data home cache.
"""
data_home = get_data_home(data_home)
shutil.rmtree(data_home)
| clear_dataset(dataset_path, data_home=None):
"""Clear dataset from cache folder
"""
data_home = get_data_home(data_home)
cache_path = os.path.join(data_home, dataset_path)
if os.path.exists(cache_path):
os.remove(cache_path)
def clear_data_home(data_home=None):
| 64 | 64 | 39 | 8 | 56 | sumau/tick | tick/dataset/download_helper.py | Python | clear_data_home | clear_data_home | 234 | 238 | 234 | 234 | 2684b3c658c588b8bf2baa592a86971b28240839 | bigcode/the-stack | train |
37fabff891f0a350c2b28b8c | train | function | def download_dataset(dataset_url, dataset_path, data_home=None, verbose=True):
"""Downloads dataset from given URL and stores it locally
Parameters
----------
dataset_url : `str`
URL of the dataset, for example
"https://archive.ics.uci.edu/ml/machine-learning-databases/url/url_svmlight.... | def download_dataset(dataset_url, dataset_path, data_home=None, verbose=True):
| """Downloads dataset from given URL and stores it locally
Parameters
----------
dataset_url : `str`
URL of the dataset, for example
"https://archive.ics.uci.edu/ml/machine-learning-databases/url/url_svmlight.tar.gz"
dataset_path : `str`
Path at which the dataset will be save... | _newsgroups.py
"""
import logging
from urllib.request import urlopen
import os
import shutil
import numpy as np
from sklearn.datasets import load_svmlight_file
import math
import warnings
logger = logging.getLogger(__name__)
BASE_URL = ("https://raw.githubusercontent.com/X-DataInitiative/tick-datasets"
... | 119 | 119 | 399 | 16 | 103 | sumau/tick | tick/dataset/download_helper.py | Python | download_dataset | download_dataset | 31 | 82 | 31 | 31 | 7534180627e3e9e930307df7f5d013a326f9c3bf | bigcode/the-stack | train |
2e562236c3dc6380b92cca0a | train | function | def download_tick_dataset(dataset_path, data_home=None, verbose=True):
"""Downloads dataset from tick_datasets github repository and stores it
locally
Parameters
----------
dataset_path : `str`
Dataset path on tick_datasets github repository. For example
"binary/adult/adult.trn.bz2" ... | def download_tick_dataset(dataset_path, data_home=None, verbose=True):
| """Downloads dataset from tick_datasets github repository and stores it
locally
Parameters
----------
dataset_path : `str`
Dataset path on tick_datasets github repository. For example
"binary/adult/adult.trn.bz2" for adult train dataset
data_home : `str`, optional, default=None
... | last_progress=last_percent)
last_percent = percent
f.write(data)
n_chunks += 1
else:
if verbose:
progress_bar(1, length=file_size)
break
return cache_path
def downloa... | 64 | 64 | 199 | 14 | 49 | sumau/tick | tick/dataset/download_helper.py | Python | download_tick_dataset | download_tick_dataset | 85 | 106 | 85 | 85 | f82e8175cb7889ed37c13d8b9e9a3258b7651f9c | bigcode/the-stack | train |
6e1c82f95cfefdedda2de101 | train | function | def get_data_home(data_home=None):
"""Return the path of the tick data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'tick_datasets'
in the user home folder.
Alternatively, it can be set by the... | def get_data_home(data_home=None):
| """Return the path of the tick data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'tick_datasets'
in the user home folder.
Alternatively, it can be set by the 'TICK_DATASETS' environment
va... |
if len(dataset) == 1:
key_0 = list(dataset.keys())[0]
dataset = dataset[key_0]
else:
dataset = dataset.items()
else:
dataset = load_svmlight_file(cache_path, n_features=n_features)
return dataset
def get_data_home(data_home=None):
| 69 | 69 | 232 | 8 | 60 | sumau/tick | tick/dataset/download_helper.py | Python | get_data_home | get_data_home | 198 | 221 | 198 | 198 | a2966acfe4a1bd269046cddda6651872ff98544f | bigcode/the-stack | train |
6f4a650929bcce7b53e11455 | train | function | def progress_bar(progress, width=40, length=None, last_progress=None):
"""Print progress bar to sys.stdout
Parameters
----------
progress : `float`
Reached progress between 0 (just started) and 1 (finished)
width : `int`
Total width of the progress bar
length : `int`
Size... | def progress_bar(progress, width=40, length=None, last_progress=None):
| """Print progress bar to sys.stdout
Parameters
----------
progress : `float`
Reached progress between 0 (just started) and 1 (finished)
width : `int`
Total width of the progress bar
length : `int`
Size in bytes of the downloaded file
"""
if length:
size = ... | .floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return '%s %s' % (s, size_name[i])
def progress_bar(progress, width=40, length=None, last_progress=None):
| 64 | 64 | 202 | 16 | 48 | sumau/tick | tick/dataset/download_helper.py | Python | progress_bar | progress_bar | 256 | 279 | 256 | 256 | dbdcff16bd1272a17b67ef47d64751ccb4646902 | bigcode/the-stack | train |
a9ab43c8370c571da6f931b8 | train | function | def load_dataset(dataset_path, data_home=None, n_features=None):
"""Load dataset from given path
Parameters
----------
dataset_path : `str`
Dataset relative path
data_home : `str`, optional, default=None
Specify a download and cache folder for the datasets. If None
and not co... | def load_dataset(dataset_path, data_home=None, n_features=None):
| """Load dataset from given path
Parameters
----------
dataset_path : `str`
Dataset relative path
data_home : `str`, optional, default=None
Specify a download and cache folder for the datasets. If None
and not configured with TICK_DATASETS environement variable
all tic... | ,
n_features=n_features)
except Exception as e:
print(80 * '_')
print('Cache loading failed')
print(80 * '_')
print(e)
if dataset is None:
download_tick_dataset(dataset_path, data_home=data_home,
... | 98 | 98 | 328 | 14 | 83 | sumau/tick | tick/dataset/download_helper.py | Python | load_dataset | load_dataset | 159 | 195 | 159 | 159 | 87fae206bd579dafd5c973464a2d232831961394 | bigcode/the-stack | train |
b474dd4f95d5a300ed745aab | train | function | def clear_dataset(dataset_path, data_home=None):
"""Clear dataset from cache folder
"""
data_home = get_data_home(data_home)
cache_path = os.path.join(data_home, dataset_path)
if os.path.exists(cache_path):
os.remove(cache_path)
| def clear_dataset(dataset_path, data_home=None):
| """Clear dataset from cache folder
"""
data_home = get_data_home(data_home)
cache_path = os.path.join(data_home, dataset_path)
if os.path.exists(cache_path):
os.remove(cache_path)
| ' to the default location {}'
.format(_TICK_HOME_ENV, _TICK_DEFAULT_HOME))
data_home = os.path.expanduser(data_home)
if not os.path.exists(data_home):
os.makedirs(data_home)
return data_home
def clear_dataset(dataset_path, data_home=None):
| 64 | 64 | 57 | 10 | 53 | sumau/tick | tick/dataset/download_helper.py | Python | clear_dataset | clear_dataset | 224 | 231 | 224 | 224 | 2f1c197030ea7f5437eeffdf42fbed77bcf15ca9 | bigcode/the-stack | train |
d34c49ee9d346176e6a6f6fd | train | function | def convert_size(size_bytes):
"""Convert raw bytes into human readable size
References
----------
http://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
"""
if size_bytes == 0:
return '0B'
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"... | def convert_size(size_bytes):
| """Convert raw bytes into human readable size
References
----------
http://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
"""
if size_bytes == 0:
return '0B'
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.... | _home, dataset_path)
if os.path.exists(cache_path):
os.remove(cache_path)
def clear_data_home(data_home=None):
"""Delete all the content of the data home cache.
"""
data_home = get_data_home(data_home)
shutil.rmtree(data_home)
def convert_size(size_bytes):
| 64 | 64 | 145 | 6 | 58 | sumau/tick | tick/dataset/download_helper.py | Python | convert_size | convert_size | 241 | 253 | 241 | 241 | 50b508d02efc9b88f1ef8ad43b3e8da3c00edec7 | bigcode/the-stack | train |
e5e8dd83828703b26da47a88 | train | class | class AnchorExplanation:
def __init__(self, exp_type: str, exp_map: dict) -> None:
"""
Class used to unpack the anchors and metadata from the explainer dictionary.
Parameters
----------
exp_type
Type of explainer: tabular, text or image.
exp_map
... | class AnchorExplanation:
| def __init__(self, exp_type: str, exp_map: dict) -> None:
"""
Class used to unpack the anchors and metadata from the explainer dictionary.
Parameters
----------
exp_type
Type of explainer: tabular, text or image.
exp_map
Dictionary with the an... | from typing import Optional, Union
import numpy as np
class AnchorExplanation:
| 16 | 256 | 911 | 4 | 11 | mauicv/alibi | alibi/explainers/anchors/anchor_explanation.py | Python | AnchorExplanation | AnchorExplanation | 6 | 134 | 6 | 7 | de5bf4094493b8b13e20ca846d052aafd7b7f495 | bigcode/the-stack | train |
a8141c639a8e6e8e33f2e684 | train | class | class SeparateRevertTask(task.Task):
def execute(self, execute_arg):
pass
def revert(self, revert_arg, result, flow_failures):
pass
| class SeparateRevertTask(task.Task):
| def execute(self, execute_arg):
pass
def revert(self, revert_arg, result, flow_failures):
pass
| pass
class DefaultProvidesTask(task.Task):
default_provides = 'def'
def execute(self):
return None
class ProgressTask(task.Task):
def execute(self, values, **kwargs):
for value in values:
self.update_progress(value)
class SeparateRevertTask(task.Task):
| 64 | 64 | 36 | 8 | 56 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | SeparateRevertTask | SeparateRevertTask | 52 | 57 | 52 | 52 | fbe37706c81ae47cc4def914648aa758e2d18a68 | bigcode/the-stack | train |
2b173ade0e6fc3a96eae6ce5 | train | class | class DefaultProvidesTask(task.Task):
default_provides = 'def'
def execute(self):
return None
| class DefaultProvidesTask(task.Task):
| default_provides = 'def'
def execute(self):
return None
| (task.Task):
def execute(self, context, spam, eggs):
pass
class KwargsTask(task.Task):
def execute(self, spam, **kwargs):
pass
class DefaultArgTask(task.Task):
def execute(self, spam, eggs=()):
pass
class DefaultProvidesTask(task.Task):
| 64 | 64 | 25 | 7 | 56 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | DefaultProvidesTask | DefaultProvidesTask | 39 | 43 | 39 | 39 | fa77cf89b2d32ac29219cb333bc9a9ea4954cca7 | bigcode/the-stack | train |
1ddcbd1f195fe0e6e1e26fcd | train | class | class MapFunctorTaskTest(test.TestCase):
def test_invalid_functor(self):
# Functor not callable
self.assertRaises(ValueError, task.MapFunctorTask, 2, requires=5)
# Functor takes no arguments
self.assertRaises(ValueError, task.MapFunctorTask, lambda: None,
... | class MapFunctorTaskTest(test.TestCase):
| def test_invalid_functor(self):
# Functor not callable
self.assertRaises(ValueError, task.MapFunctorTask, 2, requires=5)
# Functor takes no arguments
self.assertRaises(ValueError, task.MapFunctorTask, lambda: None,
requires=5)
# Functor takes too m... | Raises(TypeError, task.ReduceFunctorTask,
lambda x, y: None, requires=1)
# Too few elements in requires
self.assertRaises(ValueError, task.ReduceFunctorTask,
lambda x, y: None, requires=[1])
class MapFunctorTaskTest(test.TestCase):
| 64 | 64 | 146 | 9 | 55 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | MapFunctorTaskTest | MapFunctorTaskTest | 435 | 452 | 435 | 436 | f14c83c0071c9405fdaf97e4771c91e39cd540b6 | bigcode/the-stack | train |
a4cd49a85c5a125b4d6f6c2c | train | class | class ReduceFunctorTaskTest(test.TestCase):
def test_invalid_functor(self):
# Functor not callable
self.assertRaises(ValueError, task.ReduceFunctorTask, 2, requires=5)
# Functor takes no arguments
self.assertRaises(ValueError, task.ReduceFunctorTask, lambda: None,
... | class ReduceFunctorTaskTest(test.TestCase):
| def test_invalid_functor(self):
# Functor not callable
self.assertRaises(ValueError, task.ReduceFunctorTask, 2, requires=5)
# Functor takes no arguments
self.assertRaises(ValueError, task.ReduceFunctorTask, lambda: None,
requires=5)
# Functor takes... | def test_execute_not_callable(self):
self.assertRaises(ValueError, task.FunctorTask, 2)
def test_revert_not_callable(self):
self.assertRaises(ValueError, task.FunctorTask, lambda: None,
revert=2)
class ReduceFunctorTaskTest(test.TestCase):
| 64 | 64 | 183 | 9 | 55 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | ReduceFunctorTaskTest | ReduceFunctorTaskTest | 411 | 432 | 411 | 412 | 40baea3d1ab82e27b7a6fd84857fbd4462498c8c | bigcode/the-stack | train |
a9c49fb74b86b79d8c6099eb | train | class | class DefaultArgTask(task.Task):
def execute(self, spam, eggs=()):
pass
| class DefaultArgTask(task.Task):
| def execute(self, spam, eggs=()):
pass
| from zag import test
from zag.test import mock
from zag.types import notifier
class MyTask(task.Task):
def execute(self, context, spam, eggs):
pass
class KwargsTask(task.Task):
def execute(self, spam, **kwargs):
pass
class DefaultArgTask(task.Task):
| 64 | 64 | 20 | 7 | 56 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | DefaultArgTask | DefaultArgTask | 34 | 36 | 34 | 34 | 8a98e2b761aef84963a7612f9440657af6036ccc | bigcode/the-stack | train |
c8681f715ee8393e2819e8c2 | train | class | class ProgressTask(task.Task):
def execute(self, values, **kwargs):
for value in values:
self.update_progress(value)
| class ProgressTask(task.Task):
| def execute(self, values, **kwargs):
for value in values:
self.update_progress(value)
| def execute(self, spam, **kwargs):
pass
class DefaultArgTask(task.Task):
def execute(self, spam, eggs=()):
pass
class DefaultProvidesTask(task.Task):
default_provides = 'def'
def execute(self):
return None
class ProgressTask(task.Task):
| 64 | 64 | 28 | 6 | 57 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | ProgressTask | ProgressTask | 46 | 49 | 46 | 46 | f5ed4902e804820de7b321bbe3a3eac94cccf122 | bigcode/the-stack | train |
c00b7cc2bcfb3bc70aa697a5 | train | class | class TaskTest(test.TestCase):
def test_passed_name(self):
my_task = MyTask(name='my name')
self.assertEqual('my name', my_task.name)
def test_generated_name(self):
my_task = MyTask()
self.assertEqual('%s.%s' % (__name__, 'MyTask'),
my_task.name)
d... | class TaskTest(test.TestCase):
| def test_passed_name(self):
my_task = MyTask(name='my name')
self.assertEqual('my name', my_task.name)
def test_generated_name(self):
my_task = MyTask()
self.assertEqual('%s.%s' % (__name__, 'MyTask'),
my_task.name)
def test_task_str(self):
... |
from zag import test
from zag.test import mock
from zag.types import notifier
class MyTask(task.Task):
def execute(self, context, spam, eggs):
pass
class KwargsTask(task.Task):
def execute(self, spam, **kwargs):
pass
class DefaultArgTask(task.Task):
def execute(self, spam, eggs=()):
... | 256 | 256 | 2,763 | 7 | 248 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | TaskTest | TaskTest | 76 | 393 | 76 | 77 | fed7fe4d49b32d5fca81a8e92fd0a9e5ebfe9b28 | bigcode/the-stack | train |
cebffec8826d2387d8df5e01 | train | class | class SeparateRevertOptionalTask(task.Task):
def execute(self, execute_arg=None):
pass
def revert(self, result, flow_failures, revert_arg=None):
pass
| class SeparateRevertOptionalTask(task.Task):
| def execute(self, execute_arg=None):
pass
def revert(self, result, flow_failures, revert_arg=None):
pass
| (self, values, **kwargs):
for value in values:
self.update_progress(value)
class SeparateRevertTask(task.Task):
def execute(self, execute_arg):
pass
def revert(self, revert_arg, result, flow_failures):
pass
class SeparateRevertOptionalTask(task.Task):
| 64 | 64 | 39 | 9 | 54 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | SeparateRevertOptionalTask | SeparateRevertOptionalTask | 60 | 65 | 60 | 60 | b4c0ef260ec580e87d4f8fce23bf4b80b168e945 | bigcode/the-stack | train |
9782ffe42900597ad48991d3 | train | class | class RevertKwargsTask(task.Task):
def execute(self, execute_arg1, execute_arg2):
pass
def revert(self, execute_arg1, *args, **kwargs):
pass
| class RevertKwargsTask(task.Task):
| def execute(self, execute_arg1, execute_arg2):
pass
def revert(self, execute_arg1, *args, **kwargs):
pass
| def revert(self, revert_arg, result, flow_failures):
pass
class SeparateRevertOptionalTask(task.Task):
def execute(self, execute_arg=None):
pass
def revert(self, result, flow_failures, revert_arg=None):
pass
class RevertKwargsTask(task.Task):
| 64 | 64 | 43 | 9 | 54 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | RevertKwargsTask | RevertKwargsTask | 68 | 73 | 68 | 68 | 4ca42078450fa52d23573124db24644ca4d61471 | bigcode/the-stack | train |
fab72ea8b79cc5904ebf28f7 | train | class | class KwargsTask(task.Task):
def execute(self, spam, **kwargs):
pass
| class KwargsTask(task.Task):
| def execute(self, spam, **kwargs):
pass
| for the specific language governing permissions and limitations
# under the License.
from zag import task
from zag import test
from zag.test import mock
from zag.types import notifier
class MyTask(task.Task):
def execute(self, context, spam, eggs):
pass
class KwargsTask(task.Task):
| 64 | 64 | 20 | 7 | 56 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | KwargsTask | KwargsTask | 29 | 31 | 29 | 29 | 5f595a645eaa1b37066e913af4aed89915c5c6c7 | bigcode/the-stack | train |
be64e8a326ce387180c76258 | train | class | class FunctorTaskTest(test.TestCase):
def test_creation_with_version(self):
version = (2, 0)
f_task = task.FunctorTask(lambda: None, version=version)
self.assertEqual(version, f_task.version)
def test_execute_not_callable(self):
self.assertRaises(ValueError, task.FunctorTask, 2... | class FunctorTaskTest(test.TestCase):
| def test_creation_with_version(self):
version = (2, 0)
f_task = task.FunctorTask(lambda: None, version=version)
self.assertEqual(version, f_task.version)
def test_execute_not_callable(self):
self.assertRaises(ValueError, task.FunctorTask, 2)
def test_revert_not_callable(sel... | my_task.rebind)
expected_rebind = {'execute_arg1': 'execute_arg1'}
self.assertEqual(expected_rebind, my_task.revert_rebind)
self.assertEqual(set(['execute_arg1', 'execute_arg2']),
my_task.requires)
class FunctorTaskTest(test.TestCase):
| 64 | 64 | 108 | 9 | 55 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | FunctorTaskTest | FunctorTaskTest | 396 | 408 | 396 | 397 | 39925a85c60fdf77ad5cf1d90c6680ce5fbc68af | bigcode/the-stack | train |
cb15b7c75acf380dec6b0680 | train | class | class MyTask(task.Task):
def execute(self, context, spam, eggs):
pass
| class MyTask(task.Task):
| def execute(self, context, spam, eggs):
pass
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from zag import task
from zag import test
from zag.test import mock
from zag.types import notifier
class MyTask(task.Task):
| 64 | 64 | 20 | 6 | 57 | ToolsForHumans/taskflow | zag/tests/unit/test_task.py | Python | MyTask | MyTask | 24 | 26 | 24 | 24 | 67cfc4b2dacff7a98ef55770878e64a1328dba82 | bigcode/the-stack | train |
53f59e8ad28f6ff7fc2040ab | train | class | class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_bar04.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Wo... | class TestCompareXLSXFiles(ExcelComparisonTest):
| """
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_bar04.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet1 = w... | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
| 68 | 146 | 487 | 12 | 55 | timgates42/XlsxWriter | xlsxwriter/test/comparison/test_chart_bar04.py | Python | TestCompareXLSXFiles | TestCompareXLSXFiles | 12 | 75 | 12 | 12 | 2205fcc43f19c82220d848da51a82656c1ea444f | bigcode/the-stack | train |
5858bbfa8b684856dffaca82 | train | function | def get_type_name(type_name, sub_type=None):
""" Returns a Java type according to a spec type
"""
if type_name == "enum":
return type_name
elif type_name == "boolean":
return "Boolean"
elif type_name == "integer":
return "Long"
elif type_name == "time":
return "... | def get_type_name(type_name, sub_type=None):
| """ Returns a Java type according to a spec type
"""
if type_name == "enum":
return type_name
elif type_name == "boolean":
return "Boolean"
elif type_name == "integer":
return "Long"
elif type_name == "time":
return "Float"
elif type_name == "object":
... | ) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def get_type_name(type_name, sub_type=None):
| 64 | 64 | 126 | 11 | 53 | edwinfeener/monolithe | monolithe/generators/lang/vro/converter.py | Python | get_type_name | get_type_name | 29 | 48 | 29 | 29 | 0314ea44835c746c878f1dd39f359362e397b22e | bigcode/the-stack | train |
0cfc278a355cfb45fcf171a8 | train | function | def get_idiomatic_name(name):
"""
"""
if name == "private":
return "private_"
elif name == "public":
return "public_"
elif name == "session":
return "session_"
else:
return name | def get_idiomatic_name(name):
| """
"""
if name == "private":
return "private_"
elif name == "public":
return "public_"
elif name == "session":
return "session_"
else:
return name | "time":
return "Float"
elif type_name == "object":
return "Object"
elif type_name == "list":
return type_name
elif type_name == "float":
return "Float"
else:
return "String"
def get_idiomatic_name(name):
| 64 | 64 | 57 | 8 | 56 | edwinfeener/monolithe | monolithe/generators/lang/vro/converter.py | Python | get_idiomatic_name | get_idiomatic_name | 51 | 61 | 51 | 51 | 961320bb30bbef1ab0b15a9cfdc8ace0814c0ca9 | bigcode/the-stack | train |
b36552cf3eecb5487c772f1b | train | function | def _assert_simple_summary(testcase, expected_values, actual_summary):
"""Assert summary the specified simple values.
Args:
testcase: A TestCase instance.
expected_values: Dict of expected tags and simple values.
actual_summary: `summary_pb2.Summary`.
"""
testcase.assertAllClose(expected_values, {
... | def _assert_simple_summary(testcase, expected_values, actual_summary):
| """Assert summary the specified simple values.
Args:
testcase: A TestCase instance.
expected_values: Dict of expected tags and simple values.
actual_summary: `summary_pb2.Summary`.
"""
testcase.assertAllClose(expected_values, {
v.tag: v.simple_value
for v in actual_summary.value if (v.t... | layer_units
# Output layer weights.
testcase.assertAllEqual((prev_layer_units, output_units),
shapes[LOGITS_WEIGHTS_NAME])
testcase.assertAllEqual((output_units,),
shapes[LOGITS_BIASES_NAME])
def _assert_simple_summary(testcase, expected_values, actual_summary... | 64 | 64 | 93 | 14 | 50 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | _assert_simple_summary | _assert_simple_summary | 1,581 | 1,592 | 1,581 | 1,581 | e02af6fd7f993dec96910450cdc8536e4270b0b7 | bigcode/the-stack | train |
23a6a1e7d66eba78d733f17d | train | class | class _SummaryHook(session_run_hook.SessionRunHook):
"""Saves summaries every N steps."""
def __init__(self):
self._summaries = []
def begin(self):
self._summary_op = summary_lib.merge_all()
def before_run(self, run_context):
return session_run_hook.SessionRunArgs({'summary': self._summary_op})
... | class _SummaryHook(session_run_hook.SessionRunHook):
| """Saves summaries every N steps."""
def __init__(self):
self._summaries = []
def begin(self):
self._summary_op = summary_lib.merge_all()
def before_run(self, run_context):
return session_run_hook.SessionRunArgs({'summary': self._summary_op})
def after_run(self, run_context, run_values):
s... | , 0.39]
self.assertAllClose({
prediction_keys.PredictionKeys.PREDICTIONS: [-0.48, 0.48, 0.39],
}, next(dnn_regressor.predict(input_fn=input_fn)))
class _SummaryHook(session_run_hook.SessionRunHook):
| 63 | 64 | 128 | 11 | 52 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | _SummaryHook | _SummaryHook | 1,517 | 1,535 | 1,517 | 1,517 | d5790722b37288ecb4d35621b700ecd1f1820c6e | bigcode/the-stack | train |
9cd3e20a3b57cb4adba5ae87 | train | class | class BaseDNNRegressorTrainTest(object):
def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
d... | class BaseDNNRegressorTrainTest(object):
| def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def test_from_scratch_with_default_optimize... | Train for a few steps, then validate optimizer, summaries, and
# checkpoint.
num_steps = 5
summary_hook = _SummaryHook()
dnn_classifier.train(
input_fn=lambda: ({'age': [[10.]]}, [[1]]), steps=num_steps,
hooks=(summary_hook,))
self.assertEqual(1, opt.minimize.call_count)
summari... | 256 | 256 | 1,614 | 10 | 246 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNRegressorTrainTest | BaseDNNRegressorTrainTest | 1,794 | 1,951 | 1,794 | 1,795 | b2611c00f45fefa291064572db39fe9c00bd4b9b | bigcode/the-stack | train |
1301892b0d2faf34b7bf2a0c | train | class | class BaseDNNModelFnTest(object):
"""Tests that _dnn_model_fn passes expected logits to mock head."""
def __init__(self, dnn_model_fn):
self._dnn_model_fn = dnn_model_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCach... | class BaseDNNModelFnTest(object):
| """Tests that _dnn_model_fn passes expected logits to mock head."""
def __init__(self, dnn_model_fn):
self._dnn_model_fn = dnn_model_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self... | minimize(loss, global_step=None, var_list=None):
"""Mock of optimizer.minimize."""
trainable_vars = var_list or ops.get_collection(
ops.GraphKeys.TRAINABLE_VARIABLES)
testcase.assertItemsEqual(expected_var_names,
[var.name for var in trainable_vars])
# Verify loss.... | 256 | 256 | 2,957 | 9 | 246 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNModelFnTest | BaseDNNModelFnTest | 244 | 505 | 244 | 244 | 4cbd88556f3d4c7abb69f5b8544eb5fc4ba7460b | bigcode/the-stack | train |
2b03df40284b88b57d79f8bd | train | class | class BaseDNNClassifierEvaluateTest(object):
def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_di... | class BaseDNNClassifierEvaluateTest(object):
| def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def test_one_dim(self):
"""Asserts e... | self._dnn_classifier_fn(
hidden_units=[256, 128],
feature_columns=[city],
n_classes=4,
optimizer=gradient_descent.GradientDescentOptimizer(learning_rate=0.0),
# The 'city' variable correspond to the 'locality' variable in the
# previous model.
warm_start_from=est... | 256 | 256 | 1,715 | 9 | 247 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNClassifierEvaluateTest | BaseDNNClassifierEvaluateTest | 1,102 | 1,236 | 1,102 | 1,103 | 403e89023b5ca57f503e9cf9a24ddb5bdcfd04e7 | bigcode/the-stack | train |
d51dfa4e6a216f02fb65199c | train | class | class BaseDNNRegressorPredictTest(object):
def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
... | class BaseDNNRegressorPredictTest(object):
| def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def test_one_dim(self):
"""Asserts pred... | 0.43538380, 0.39791084],
predictions[prediction_keys.PredictionKeys.PROBABILITIES])
self.assertAllEqual(
[1], predictions[prediction_keys.PredictionKeys.CLASS_IDS])
self.assertAllEqual(
[label_output_fn(1)],
predictions[prediction_keys.PredictionKeys.CLASSES])
def test_multi_... | 207 | 207 | 691 | 10 | 197 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNRegressorPredictTest | BaseDNNRegressorPredictTest | 1,454 | 1,514 | 1,454 | 1,455 | 12b46aeb5f62c065246dcebffda71869b3a3679f | bigcode/the-stack | train |
5c234fe9ea6f05bbdef5fa34 | train | function | def mock_optimizer(testcase, hidden_units, expected_loss=None):
"""Creates a mock optimizer to test the train method.
Args:
testcase: A TestCase instance.
hidden_units: Iterable of integer sizes for the hidden layers.
expected_loss: If given, will assert the loss value.
Returns:
A mock Optimizer... | def mock_optimizer(testcase, hidden_units, expected_loss=None):
| """Creates a mock optimizer to test the train method.
Args:
testcase: A TestCase instance.
hidden_units: Iterable of integer sizes for the hidden layers.
expected_loss: If given, will assert the loss value.
Returns:
A mock Optimizer.
"""
hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN +... | , optimizer=None):
tpu_spec = _create_tpu_estimator_spec(
features, mode, logits, labels, train_op_fn, optimizer)
return tpu_spec.as_estimator_spec()
head = test.mock.NonCallableMagicMock(spec=head_lib._Head)
head.logits_dimension = logits_dimension
head._create_tpu_estimator_spec = test.mock.Mag... | 130 | 130 | 434 | 13 | 116 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | mock_optimizer | mock_optimizer | 195 | 241 | 195 | 195 | 7367ee9ea9f0243bde17822dbd96de67d83167c1 | bigcode/the-stack | train |
8b784b5ed9507d478eb6dbda | train | class | class BaseDNNClassifierPredictTest(object):
def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir... | class BaseDNNClassifierPredictTest(object):
| def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def _test_one_dim(self, label_vocabulary... | 1]), ([[1., .8], [-.8, -1.]], [.2, -.2]),
([[-1., 1., .5], [-1., 1., .5]], [.3, -.3, .0]),),
global_step, self._model_dir)
label_dimension = 3
dnn_regressor = self._dnn_regressor_fn(
hidden_units=(2, 2),
feature_columns=[feature_column.numeric_column... | 256 | 256 | 1,258 | 9 | 247 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNClassifierPredictTest | BaseDNNClassifierPredictTest | 1,340 | 1,451 | 1,340 | 1,341 | f4d845fce936ca8ebecc6044075e8a691acf4bab | bigcode/the-stack | train |
546708261d0e96f5f8a598f2 | train | function | def assert_close(expected, actual, rtol=1e-04, message='', name='assert_close'):
with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope:
expected = ops.convert_to_tensor(expected, name='expected')
actual = ops.convert_to_tensor(actual, name='actual')
rdiff = math_ops.abs((expected - ... | def assert_close(expected, actual, rtol=1e-04, message='', name='assert_close'):
| with ops.name_scope(name, 'assert_close', (expected, actual, rtol)) as scope:
expected = ops.convert_to_tensor(expected, name='expected')
actual = ops.convert_to_tensor(actual, name='actual')
rdiff = math_ops.abs((expected - actual) / expected, 'diff')
rtol = ops.convert_to_tensor(rtol, name='rtol')
... | dnn/input_from_feature_columns/input_layer/'
'occupation_embedding/embedding_weights')
CITY_EMBEDDING_NAME = ('dnn/input_from_feature_columns/input_layer/'
'city_embedding/embedding_weights')
def assert_close(expected, actual, rtol=1e-04, message='', name='assert_clos... | 64 | 64 | 181 | 22 | 42 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | assert_close | assert_close | 81 | 94 | 81 | 81 | 654f178db46197e602714661ff0cce883ea8575c | bigcode/the-stack | train |
870aa73b6463798d91b8237a | train | class | class BaseDNNLogitFnTest(object):
"""Tests correctness of logits calculated from _dnn_logit_fn_builder."""
def __init__(self, dnn_logit_fn_builder):
self._dnn_logit_fn_builder = dnn_logit_fn_builder
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
... | class BaseDNNLogitFnTest(object):
| """Tests correctness of logits calculated from _dnn_logit_fn_builder."""
def __init__(self, dnn_logit_fn_builder):
self._dnn_logit_fn_builder = dnn_logit_fn_builder
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.cle... | .loss)
elif mode == model_fn.ModeKeys.PREDICT:
sess.run(estimator_spec.predictions)
else:
self.fail('Invalid mode: {}'.format(mode))
def test_features_tensor_raises_value_error(self):
"""Tests that passing a Tensor for features raises a ValueError."""
hidden_units ... | 256 | 256 | 3,644 | 10 | 246 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNLogitFnTest | BaseDNNLogitFnTest | 508 | 804 | 508 | 508 | 59d9a5ac54f4d2831fc07b15c45c4223754d2812 | bigcode/the-stack | train |
a99a1b71b535069795386456 | train | class | class BaseDNNRegressorEvaluateTest(object):
def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
... | class BaseDNNRegressorEvaluateTest(object):
| def __init__(self, dnn_regressor_fn):
self._dnn_regressor_fn = dnn_regressor_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def test_one_dim(self):
"""Asserts eval... | 1., 1., .5]], [.3, -.3, .0]),),
global_step, self._model_dir)
n_classes = 3
dnn_classifier = self._dnn_classifier_fn(
hidden_units=(2, 2),
feature_columns=[feature_column.numeric_column('age', shape=[2])],
n_classes=n_classes,
weight_column='w',
mod... | 256 | 256 | 1,166 | 10 | 246 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNRegressorEvaluateTest | BaseDNNRegressorEvaluateTest | 1,239 | 1,337 | 1,239 | 1,240 | 248841b7bfe9fd99775e08e4a901c1a322f3dfff | bigcode/the-stack | train |
93fc1eecabf94269811b9ddb | train | class | class BaseDNNClassifierTrainTest(object):
def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
... | class BaseDNNClassifierTrainTest(object):
| def __init__(self, dnn_classifier_fn):
self._dnn_classifier_fn = dnn_classifier_fn
def setUp(self):
self._model_dir = tempfile.mkdtemp()
def tearDown(self):
if self._model_dir:
writer_cache.FileWriterCache.clear()
shutil.rmtree(self._model_dir)
def test_from_scratch_with_default_optim... | checkpoint_utils.load_variable(
model_dir, ops.GraphKeys.GLOBAL_STEP))
# Hidden layer weights.
prev_layer_units = input_units
for i in range(len(hidden_units)):
layer_units = hidden_units[i]
testcase.assertAllEqual(
(prev_layer_units, layer_units),
shapes[HIDDEN_WEIGHTS_NA... | 256 | 256 | 2,032 | 9 | 247 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNClassifierTrainTest | BaseDNNClassifierTrainTest | 1,595 | 1,791 | 1,595 | 1,596 | 7f48ec5272c19767caf6384fe67f0fa12b4d1a0c | bigcode/the-stack | train |
f9bbd2d1f4f709fc2e52c6b9 | train | class | class BaseDNNWarmStartingTest(object):
def __init__(self, _dnn_classifier_fn, _dnn_regressor_fn):
self._dnn_classifier_fn = _dnn_classifier_fn
self._dnn_regressor_fn = _dnn_regressor_fn
def setUp(self):
# Create a directory to save our old checkpoint and vocabularies to.
self._ckpt_and_vocab_dir =... | class BaseDNNWarmStartingTest(object):
| def __init__(self, _dnn_classifier_fn, _dnn_regressor_fn):
self._dnn_classifier_fn = _dnn_classifier_fn
self._dnn_regressor_fn = _dnn_regressor_fn
def setUp(self):
# Create a directory to save our old checkpoint and vocabularies to.
self._ckpt_and_vocab_dir = tempfile.mkdtemp()
# Make a dummy ... | Session, which is in turn used to
# explicitly set variable weights through a checkpoint.
training_util.create_global_step()
# Use a variable scope here with 'dnn', emulating the dnn model_fn, so
# the checkpoint naming is shared.
with variable_scope.variable_scope('dnn'):
... | 256 | 256 | 3,009 | 9 | 247 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | BaseDNNWarmStartingTest | BaseDNNWarmStartingTest | 807 | 1,099 | 807 | 808 | 3b405859b855228de7c81415ee094c8244dd6abe | bigcode/the-stack | train |
496685f322a7f1cf50bda586 | train | function | def create_checkpoint(weights_and_biases,
global_step,
model_dir,
batch_norm_vars=None):
"""Create checkpoint file with provided model weights.
Args:
weights_and_biases: Iterable of tuples of weight and bias values.
global_step: Initial glob... | def create_checkpoint(weights_and_biases,
global_step,
model_dir,
batch_norm_vars=None):
| """Create checkpoint file with provided model weights.
Args:
weights_and_biases: Iterable of tuples of weight and bias values.
global_step: Initial global step to save in checkpoint.
model_dir: Directory into which checkpoint is saved.
"""
weights, biases = zip(*weights_and_biases)
if batch_norm_... | ')
rdiff = math_ops.abs((expected - actual) / expected, 'diff')
rtol = ops.convert_to_tensor(rtol, name='rtol')
return check_ops.assert_less(
rdiff,
rtol,
data=(message, 'Condition expected =~ actual did not hold element-wise:'
'expected = ', expected, 'actual = ', actu... | 134 | 134 | 448 | 22 | 112 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | create_checkpoint | create_checkpoint | 97 | 140 | 97 | 100 | a1377256b602f536f71ab07dd2bd0ebeabd55850 | bigcode/the-stack | train |
1d2277286a460b7c9be61b87 | train | function | def _assert_checkpoint(
testcase, global_step, input_units, hidden_units, output_units, model_dir):
"""Asserts checkpoint contains expected variables with proper shapes.
Args:
testcase: A TestCase instance.
global_step: Expected global step value.
input_units: The dimension of input layer.
hidd... | def _assert_checkpoint(
testcase, global_step, input_units, hidden_units, output_units, model_dir):
| """Asserts checkpoint contains expected variables with proper shapes.
Args:
testcase: A TestCase instance.
global_step: Expected global step value.
input_units: The dimension of input layer.
hidden_units: Iterable of integer sizes for the hidden layers.
output_units: The dimension of output lay... | return session_run_hook.SessionRunArgs({'summary': self._summary_op})
def after_run(self, run_context, run_values):
s = summary_pb2.Summary()
s.ParseFromString(run_values.results['summary'])
self._summaries.append(s)
def summaries(self):
return tuple(self._summaries)
def _assert_checkpoint(
... | 92 | 92 | 309 | 23 | 69 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | _assert_checkpoint | _assert_checkpoint | 1,538 | 1,578 | 1,538 | 1,539 | 765e4c5957c86a1df71f5f706e05daf057430db1 | bigcode/the-stack | train |
dd0220d03dae07f9cbfa64ea | train | function | def mock_head(testcase, hidden_units, logits_dimension, expected_logits):
"""Returns a mock head that validates logits values and variable names."""
hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + '/part_0:0') % i
for i in range(len(hidden_units))]
hidden_biases_names = [(HIDDEN_B... | def mock_head(testcase, hidden_units, logits_dimension, expected_logits):
| """Returns a mock head that validates logits values and variable names."""
hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + '/part_0:0') % i
for i in range(len(hidden_units))]
hidden_biases_names = [(HIDDEN_BIASES_NAME_PATTERN + '/part_0:0') % i
for i in ra... | # Output layer weights.
model_weights[LOGITS_WEIGHTS_NAME] = weights[-1]
model_weights[LOGITS_BIASES_NAME] = biases[-1]
with ops.Graph().as_default():
# Create model variables.
for k, v in six.iteritems(model_weights):
variables_lib.Variable(v, name=k, dtype=dtypes.float32)
# Create non-mode... | 165 | 166 | 555 | 15 | 150 | kuo1220/verbose-barnacle | tensorflow/python/estimator/canned/dnn_testing_utils.py | Python | mock_head | mock_head | 143 | 192 | 143 | 143 | 403e866d350ba69c7d18b5807610c41395af9091 | bigcode/the-stack | train |
73b6c7bccf8507f59a32c777 | train | function | def get_log(namespace):
global disabled
if disabled:
logging.disable(logging.CRITICAL)
ret = logging.getLogger(namespace)
else:
ret = logging.getLogger(namespace)
ret.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(log_format)
... | def get_log(namespace):
| global disabled
if disabled:
logging.disable(logging.CRITICAL)
ret = logging.getLogger(namespace)
else:
ret = logging.getLogger(namespace)
ret.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(log_format)
ret.addHandler(ch)
... | import os
import logging
from logging.handlers import RotatingFileHandler
import sys
log_format = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log_level = logging.INFO
disabled = False
def get_log(namespace):
| 60 | 64 | 80 | 5 | 54 | deepdrive/deepdrive-api | deepdrive_api/logs.py | Python | get_log | get_log | 13 | 26 | 13 | 13 | 26493851f588b6fe98f4a2edcf3109971228c78a | bigcode/the-stack | train |
6fa6d9c47cd63a36606174d6 | train | class | class WikiCS(InMemoryDataset):
r"""This is the copy of the torch_geometric.datasets.WikiCS (v1.6.3)
Args:
root (string): Root directory where the dataset should be saved.
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object an... | class WikiCS(InMemoryDataset):
| r"""This is the copy of the torch_geometric.datasets.WikiCS (v1.6.3)
Args:
root (string): Root directory where the dataset should be saved.
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object and returns a transformed
... | from typing import Optional, Callable
import json
from itertools import chain
import torch
from torch_geometric.data import Data, InMemoryDataset, download_url
class WikiCS(InMemoryDataset):
| 40 | 175 | 586 | 7 | 32 | SherylHYX/pytorch_geometric_signed_directed | torch_geometric_signed_directed/data/directed/WikiCS.py | Python | WikiCS | WikiCS | 9 | 70 | 9 | 9 | 546dd47d96c7cfab3fd900b8bd6156b3c1b2ec73 | bigcode/the-stack | train |
d27edc1218551732f6a415b9 | train | function | def test_module(client, headers=None):
response = client.http_request("GET", "/api/v1/status")
headers = {} if headers is None else headers
if response.status_code == 200:
try:
resp = response.json()
except Exception:
return "Could connect to server, but got unexpecte... | def test_module(client, headers=None):
| response = client.http_request("GET", "/api/v1/status")
headers = {} if headers is None else headers
if response.status_code == 200:
try:
resp = response.json()
except Exception:
return "Could connect to server, but got unexpected response: {}".format(
... | _request(self, method, url_suffix, data=None, headers=None):
server = self.base_url + url_suffix
res = requests.request(
method,
server,
json=data,
verify=self.verify,
headers=headers,
proxies=self.proxies,
)
return ... | 69 | 69 | 233 | 8 | 60 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | test_module | test_module | 39 | 70 | 39 | 39 | f7c0545a91d619731f19e1d5699dd42219e9fddd | bigcode/the-stack | train |
3279fe1642fdd6c199f6e296 | train | function | def form_incindents(incidents):
returnableincidents = []
for item in incidents:
returnableincidents.append(create_incident_from_humioquery(item))
return returnableincidents
| def form_incindents(incidents):
| returnableincidents = []
for item in incidents:
returnableincidents.append(create_incident_from_humioquery(item))
return returnableincidents
| "value": str(incident[key])})
return {
"name": "Humio Incident {id}".format(id=incident["@id"]),
"labels": labels,
"rawJSON": json.dumps(incident),
"occurred": occurred,
}
def form_incindents(incidents):
| 64 | 64 | 45 | 9 | 55 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | form_incindents | form_incindents | 340 | 344 | 340 | 340 | 64207e5e568fe425392f049b444cb61346250bf1 | bigcode/the-stack | train |
e0727daf73f83fca291af184 | train | function | def humio_delete_job(client, args, headers):
data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/queryjobs/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("DELETE", url, data, headers)
i... | def humio_delete_job(client, args, headers):
| data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/queryjobs/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("DELETE", url, data, headers)
if response.status_code == 204:
return... | obj.job_id)": result}
return markdown, outputs, result
elif response.status_code == 404:
raise ValueError(response.text)
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_delete_job(client, args, headers):
| 64 | 64 | 145 | 11 | 53 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_delete_job | humio_delete_job | 145 | 160 | 145 | 145 | c9d4f00344010aae0746751ddd2ecca88917ae09 | bigcode/the-stack | train |
b079b107b8eb035897242791 | train | class | class Client:
def __init__(self, base_url, verify, proxies):
self.base_url = base_url
self.verify = verify
self.proxies = proxies
def http_request(self, method, url_suffix, data=None, headers=None):
server = self.base_url + url_suffix
res = requests.request(
... | class Client:
| def __init__(self, base_url, verify, proxies):
self.base_url = base_url
self.verify = verify
self.proxies = proxies
def http_request(self, method, url_suffix, data=None, headers=None):
server = self.base_url + url_suffix
res = requests.request(
method,
... | import demistomock as demisto
from CommonServerPython import *
""" IMPORTS """
# Disable insecure warnings from urllib3
# - this does not disable SSL checking, just the warnings logged from urllib3
requests.packages.urllib3.disable_warnings()
""" CLASS for Humio"""
class Client:
| 64 | 64 | 102 | 3 | 61 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | Client | Client | 20 | 36 | 20 | 20 | 6f744e3cf6d527ea612c32c51b96b8f816dccf2a | bigcode/the-stack | train |
bf4b3bd18dfb47bb4fffc71a | train | function | def humio_list_alerts(client, args, headers):
data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alerts"
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
result = response.json()... | def humio_list_alerts(client, args, headers):
| data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alerts"
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
result = response.json()
markdown = tableToMarkdown("Humio Ale... | executed. Status code " + str(response), None, None
elif response.status_code == 404:
raise ValueError(response.text)
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_list_alerts(client, args, headers):
| 64 | 64 | 145 | 12 | 52 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_list_alerts | humio_list_alerts | 163 | 174 | 163 | 163 | 6e757d9fd09f3a95eec9625c07c8858adfd8e2fb | bigcode/the-stack | train |
a0b9a84805db9ce963995ea6 | train | function | def fetch_incidents(client, headers):
incidentquery = demisto.params().get("queryParameter")
incidentrepo = demisto.params().get("queryRepository")
timestampfrom = demisto.params().get("queryStartTime")
lastrun = demisto.getLastRun()
url = "/api/v1/repositories/" + incidentrepo + "/query"
header... | def fetch_incidents(client, headers):
| incidentquery = demisto.params().get("queryParameter")
incidentrepo = demisto.params().get("queryRepository")
timestampfrom = demisto.params().get("queryStartTime")
lastrun = demisto.getLastRun()
url = "/api/v1/repositories/" + incidentrepo + "/query"
headers["Accept"] = "application/json"
... | , data, headers)
if response.status_code == 200:
if not response.text:
raise ValueError("Notifier with id " + str(args.get("id")) + " not found")
result = response.json()
markdown = tableToMarkdown("Humio Notifiers", result, removeNull=True)
outputs = {"Humio.Notifier(val... | 120 | 120 | 401 | 8 | 112 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | fetch_incidents | fetch_incidents | 273 | 321 | 273 | 273 | 374728d02728ed9634cfaae1f81b3afaebc6d652 | bigcode/the-stack | train |
bbb15df34be36017ada60a44 | train | function | def humio_delete_alert(client, args, headers):
data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alerts/" + args.get("id")
headers["Accept"] = "application/json"
response = client.http_request("DELETE", url, data, headers)
if response.status_code == 204:
re... | def humio_delete_alert(client, args, headers):
| data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alerts/" + args.get("id")
headers["Accept"] = "application/json"
response = client.http_request("DELETE", url, data, headers)
if response.status_code == 204:
return ("Command executed. Status code " + str(re... | ", result, removeNull=True)
outputs = {"Humio.Alert(val.id == obj.id)": result}
return markdown, outputs, result
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_delete_alert(client, args, headers):
| 64 | 64 | 121 | 11 | 53 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_delete_alert | humio_delete_alert | 227 | 235 | 227 | 227 | 29970673d248074b6658b88888ad214b92445ae9 | bigcode/the-stack | train |
42e3620db5a435d0016272cf | train | function | def main():
apikey = demisto.params().get("API-key")
baseserver = (
demisto.params()["url"][:-1]
if (demisto.params()["url"] and demisto.params()["url"].endswith("/"))
else demisto.params()["url"]
)
verify_certificate = not demisto.params().get("insecure", False)
proxies = ha... | def main():
| apikey = demisto.params().get("API-key")
baseserver = (
demisto.params()["url"][:-1]
if (demisto.params()["url"] and demisto.params()["url"].endswith("/"))
else demisto.params()["url"]
)
verify_certificate = not demisto.params().get("insecure", False)
proxies = handle_proxy()... | ({"type": key, "value": str(incident[key])})
return {
"name": "Humio Incident {id}".format(id=incident["@id"]),
"labels": labels,
"rawJSON": json.dumps(incident),
"occurred": occurred,
}
def form_incindents(incidents):
returnableincidents = []
for item in incidents:
... | 108 | 108 | 362 | 3 | 104 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | main | main | 347 | 385 | 347 | 347 | ea0d9923083ac0c0dcd75a9d539c8ad8bc5e7339 | bigcode/the-stack | train |
6e23cbb0d8e77964b849326f | train | function | def humio_poll(client, args, headers):
data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/queryjobs/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if respons... | def humio_poll(client, args, headers):
| data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/queryjobs/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
result = ... | Markdown("Humio Query Job", result, removeNull=True)
outputs = {"Humio.Job": result}
return markdown, outputs, result
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_poll(client, args, headers):
| 64 | 64 | 197 | 10 | 54 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_poll | humio_poll | 121 | 142 | 121 | 121 | d5ad41015ca831c655992c0043c2c91d5b352342 | bigcode/the-stack | train |
48503cef3c2ab6690f778373 | train | function | def humio_list_notifiers(client, args, headers):
data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alertnotifiers"
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
result = resp... | def humio_list_notifiers(client, args, headers):
| data: Dict[str, str] = {}
url = "/api/v1/repositories/" + args.get("repository") + "/alertnotifiers"
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
result = response.json()
markdown = tableToMarkdown("H... | , headers)
if response.status_code == 204:
return ("Command executed. Status code " + str(response), None, None)
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_list_notifiers(client, args, headers):
| 64 | 64 | 149 | 12 | 52 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_list_notifiers | humio_list_notifiers | 238 | 249 | 238 | 238 | 19482881c59a1ece9e23ba285b74e79355260ed9 | bigcode/the-stack | train |
30c73f2e1ede9c4c04e3b64a | train | function | def humio_get_notifier_by_id(client, args, headers):
data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/alertnotifiers/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, head... | def humio_get_notifier_by_id(client, args, headers):
| data: Dict[str, str] = {}
url = (
"/api/v1/repositories/"
+ args.get("repository")
+ "/alertnotifiers/"
+ args.get("id")
)
headers["Accept"] = "application/json"
response = client.http_request("GET", url, data, headers)
if response.status_code == 200:
if n... | Null=True)
outputs = {"Humio.Notifier(val.id == obj.id)": result}
return markdown, outputs, result
else:
raise ValueError("Error:" + " response from server was: " + str(response.text))
def humio_get_notifier_by_id(client, args, headers):
| 64 | 64 | 191 | 14 | 50 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_get_notifier_by_id | humio_get_notifier_by_id | 252 | 270 | 252 | 252 | d67d66d23802f3037e90775017249b9b64509ea4 | bigcode/the-stack | train |
be4086beb998916b62ea3d84 | train | function | def humio_query(client, args, headers):
data = {}
data["queryString"] = args.get("queryString")
try:
data["start"] = int(args.get("start"))
except ValueError:
data["start"] = args.get("start")
try:
data["end"] = int(args.get("end"))
except ValueError:
data["end"] ... | def humio_query(client, args, headers):
| data = {}
data["queryString"] = args.get("queryString")
try:
data["start"] = int(args.get("start"))
except ValueError:
data["start"] = args.get("start")
try:
data["end"] = int(args.get("end"))
except ValueError:
data["end"] = args.get("end")
data["isLive"] = a... | ": "now",
"isLive": "false",
"timeZoneOffsetMinutes": 0,
}
humio_query(client, args, headers)
return "ok"
else:
return "ok"
else:
return "Bad status from server: ({}) {}".format(
... | 83 | 83 | 279 | 10 | 73 | diCagri/content | Packs/Humio/Integrations/Humio/Humio.py | Python | humio_query | humio_query | 73 | 97 | 73 | 73 | 30edb6857142ced956bf8e07fc705635aac8bc58 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.