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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d896457d9fb1e783941ee1f | train | function | def subpixel_upsample(x, target_channels, upscale_ratio):
estimated_filters = target_channels * (upscale_ratio ** 2)
x = keras.layers.Conv2D(estimated_filters, 3, padding="same")(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.LeakyReLU(0.2)(x)
x = tf.nn.depth_to_space(x, block_size=ups... | def subpixel_upsample(x, target_channels, upscale_ratio):
| estimated_filters = target_channels * (upscale_ratio ** 2)
x = keras.layers.Conv2D(estimated_filters, 3, padding="same")(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.LeakyReLU(0.2)(x)
x = tf.nn.depth_to_space(x, block_size=upscale_ratio)
return x
| "):
x = keras.layers.Conv2D(filters=filters, kernel_size=3, padding=padding)(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Activation("relu")(x)
return x
def subpixel_upsample(x, target_channels, upscale_ratio):
| 64 | 64 | 97 | 14 | 49 | anish9/keras-io | examples/vision/text_image_denoiser.py | Python | subpixel_upsample | subpixel_upsample | 152 | 158 | 152 | 152 | 45624f2dc142b079a8bba980c6aad775bdde2ed0 | bigcode/the-stack | train |
0a7fcbe677c9e9867060a213 | train | function | def data_file(f):
"""Get absolute path for file inside pythondata_cpu_zynq7."""
fn = os.path.join(data_location, f)
fn = os.path.abspath(fn)
if not os.path.exists(fn):
raise IOError("File {f} doesn't exist in pythondata_cpu_zynq7".format(f))
return fn
| def data_file(f):
| """Get absolute path for file inside pythondata_cpu_zynq7."""
fn = os.path.join(data_location, f)
fn = os.path.abspath(fn)
if not os.path.exists(fn):
raise IOError("File {f} doesn't exist in pythondata_cpu_zynq7".format(f))
return fn
| import os.path
__dir__ = os.path.split(os.path.abspath(os.path.realpath(__file__)))[0]
data_location = os.path.join(__dir__, "verilog")
def data_file(f):
| 42 | 64 | 74 | 5 | 37 | DeanoC/pythondata-cpu-zynq7 | pythondata-cpu-zynq7/__init__.py | Python | data_file | data_file | 5 | 11 | 5 | 5 | ad5f737664085f1fb30aee7efbf1aca2c6b3cce3 | bigcode/the-stack | train |
0ebc269fb0a67b4416ee06ca | train | class | class ActionDQNAgent(DQNAgent):
def __init__(self, observation_space, action_space, get_duplicate_actions_fn, params):
super().__init__(observation_space, action_space, get_duplicate_actions_fn, params)
def _get_q_targets(self, batch):
with torch.no_grad():
# Compute Double-Q targe... | class ActionDQNAgent(DQNAgent):
| def __init__(self, observation_space, action_space, get_duplicate_actions_fn, params):
super().__init__(observation_space, action_space, get_duplicate_actions_fn, params)
def _get_q_targets(self, batch):
with torch.no_grad():
# Compute Double-Q targets
next_states = tor... | import torch
from ..nnutils import one_hot, MLP
from .dqn import DQNAgent
class ActionDQNAgent(DQNAgent):
| 32 | 157 | 524 | 9 | 22 | camall3n/actgen | actgen/agents/action_dqn.py | Python | ActionDQNAgent | ActionDQNAgent | 7 | 49 | 7 | 7 | 97e97003761ecd19ef6f5ef804cf038b7998a32b | bigcode/the-stack | train |
bd7c403e012c427071525149 | train | class | class Line(_BaseTraceHierarchyType):
# autocolorscale
# --------------
@property
def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.line.colorscale`. Has an effect only if in
... | class Line(_BaseTraceHierarchyType):
# autocolorscale
# --------------
@property
| def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.line.colorscale`. Has an effect only if in
`marker.line.color`is set to a numerical array. In case
`colorscale` is unspec... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
# autocolorscale
# --------------
@property
| 49 | 256 | 5,231 | 23 | 25 | piyush1301/plotly.py | plotly/graph_objs/splom/marker/__init__.py | Python | Line | Line | 7 | 574 | 7 | 11 | b2243cf02732c9cdf5235c71c83d614d346e9045 | bigcode/the-stack | train |
8e68432dda1c3d1160850a03 | train | class | class ColorBar(_BaseTraceHierarchyType):
# bgcolor
# -------
@property
def bgcolor(self):
"""
Sets the color of padded area.
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,... | class ColorBar(_BaseTraceHierarchyType):
# bgcolor
# -------
@property
| def bgcolor(self):
"""
Sets the color of padded area.
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva... | ['color'] = color if color is not None else _v
_v = arg.pop('colorscale', None)
self['colorscale'] = colorscale if colorscale is not None else _v
_v = arg.pop('colorsrc', None)
self['colorsrc'] = colorsrc if colorsrc is not None else _v
_v = arg.pop('reversescale', None)
... | 256 | 256 | 16,478 | 20 | 235 | piyush1301/plotly.py | plotly/graph_objs/splom/marker/__init__.py | Python | ColorBar | ColorBar | 581 | 2,440 | 581 | 585 | 57ecbdcf8cf29f3268afd47e7897113f27bb21ab | bigcode/the-stack | train |
118fd8f40af20e2c4f82ce57 | train | function | def get_exchange_rate(fixed_currency, variable_currency):
''' Return tuple of last trade, ask and bid prices for given currencies '''
r = yahoo_finance_query(s=variable_currency + fixed_currency + '=X', f='l1a0b0')
return tuple(map(Decimal, r.split(',')))
| def get_exchange_rate(fixed_currency, variable_currency):
| ''' Return tuple of last trade, ask and bid prices for given currencies '''
r = yahoo_finance_query(s=variable_currency + fixed_currency + '=X', f='l1a0b0')
return tuple(map(Decimal, r.split(',')))
| "
f - properties we ant to get. See
https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty
'''
return requests.get('http://download.finance.yahoo.com/d/quotes.csv', params=params).text
def get_exchange_rate(fixed_currency, variable_currency):
| 64 | 64 | 65 | 11 | 52 | bunyk/pyrrd | monitor_sources.py | Python | get_exchange_rate | get_exchange_rate | 17 | 20 | 17 | 17 | 72217a01934708754329251adb04b6aef174d4be | bigcode/the-stack | train |
3e11942def4365a38d5052b2 | train | function | def get_wikipedia_edits():
j = json.loads(requests.get(
'https://uk.wikipedia.org/w/api.php',
params={
'action': 'query',
'meta': 'siteinfo',
'siprop': 'statistics',
'continue': '',
'format': 'json',
}
).text)
return int(j['... | def get_wikipedia_edits():
| j = json.loads(requests.get(
'https://uk.wikipedia.org/w/api.php',
params={
'action': 'query',
'meta': 'siteinfo',
'siprop': 'statistics',
'continue': '',
'format': 'json',
}
).text)
return int(j['query']['statistics']['edit... | variable_currency):
''' Return tuple of last trade, ask and bid prices for given currencies '''
r = yahoo_finance_query(s=variable_currency + fixed_currency + '=X', f='l1a0b0')
return tuple(map(Decimal, r.split(',')))
def get_wikipedia_edits():
| 64 | 64 | 83 | 7 | 57 | bunyk/pyrrd | monitor_sources.py | Python | get_wikipedia_edits | get_wikipedia_edits | 22 | 33 | 22 | 22 | 82214fa153557f99c215d89e4dd13d36fb76b705 | bigcode/the-stack | train |
a46bcf5b919fd084a5799f86 | train | function | def yahoo_finance_query(**params):
''' Return the text of the request to the Yahoo finance API
s - ids of entities we wnant to receive. Every stock, index or currency has their own ID.
If you want to get values of more than one ID, separate them with ","
f - properties we ant to get. See
https://cod... | def yahoo_finance_query(**params):
| ''' Return the text of the request to the Yahoo finance API
s - ids of entities we wnant to receive. Every stock, index or currency has their own ID.
If you want to get values of more than one ID, separate them with ","
f - properties we ant to get. See
https://code.google.com/p/yahoo-finance-manage... | from decimal import Decimal
import requests
from tabulate import tabulate
import json
def yahoo_finance_query(**params):
| 26 | 64 | 115 | 8 | 17 | bunyk/pyrrd | monitor_sources.py | Python | yahoo_finance_query | yahoo_finance_query | 8 | 15 | 8 | 8 | 9e26656cf93698d96d44b38840828646c156d2e1 | bigcode/the-stack | train |
f3e282781a9f30d02495400b | train | function | def table():
print(tabulate(
(
('RUB/' + currency, ) + get_exchange_rate('RUB', currency)
for currency in ('EUR', 'USD', 'UAH')
),
headers = ('Pair', 'Trade', 'Ask', 'Bid')
))
| def table():
| print(tabulate(
(
('RUB/' + currency, ) + get_exchange_rate('RUB', currency)
for currency in ('EUR', 'USD', 'UAH')
),
headers = ('Pair', 'Trade', 'Ask', 'Bid')
))
| /w/api.php',
params={
'action': 'query',
'meta': 'siteinfo',
'siprop': 'statistics',
'continue': '',
'format': 'json',
}
).text)
return int(j['query']['statistics']['edits'])
def table():
| 63 | 64 | 62 | 3 | 60 | bunyk/pyrrd | monitor_sources.py | Python | table | table | 36 | 43 | 36 | 36 | cd47aead0879e8407dc1d1dd2e2f1a1b43f07e68 | bigcode/the-stack | train |
e41c16910e4e70edb6437f90 | train | function | def solution(xs):
if len(xs) == 1: return str(xs[0])
ans = 1
smallestAbsMin = 100001
zeroCount = 0
oddNegatives = False
# Every negative number needs a pair
# We remove the negative number with a smaller magnitude
for n in xs:
if n==0:
zeroCount+=1
conti... | def solution(xs):
| if len(xs) == 1: return str(xs[0])
ans = 1
smallestAbsMin = 100001
zeroCount = 0
oddNegatives = False
# Every negative number needs a pair
# We remove the negative number with a smaller magnitude
for n in xs:
if n==0:
zeroCount+=1
continue
if n<0... | def solution(xs):
| 4 | 64 | 194 | 4 | 0 | Aarif123456/foobar | 2/a/soution.py | Python | solution | solution | 1 | 22 | 1 | 1 | 65445a05c0d1b25eeb75cb5252464047aaa9d7f4 | bigcode/the-stack | train |
0b7db8aa0af216fbcea9ffda | train | class | class sTest(unittest.TestCase):
def test_function(self):
test_cases = \
[
([2, 0, 2, 2, 0],"8"),\
([-2, -3, 4, -5],"60"),\
([2, -3, 4, -5],"120"),\
([0,0,0],"0"),\
([0,0,-1],"0"),\
([-1],"-1"),\
... | class sTest(unittest.TestCase):
| def test_function(self):
test_cases = \
[
([2, 0, 2, 2, 0],"8"),\
([-2, -3, 4, -5],"60"),\
([2, -3, 4, -5],"120"),\
([0,0,0],"0"),\
([0,0,-1],"0"),\
([-1],"-1"),\
([-12, -12, 2, 0, 0, 0,0,0... | len(xs) or (zeroCount+1 == len(xs) and ans==bne): return "0"
if oddNegatives: ans/=bne
return str(int(ans))
# Your code here
###############################################
# Code below is not submitted
import unittest
class sTest(unittest.TestCase):
| 65 | 65 | 219 | 7 | 57 | Aarif123456/foobar | 2/a/soution.py | Python | sTest | sTest | 29 | 47 | 29 | 30 | 5dd85900518981ada57524055d3e5bd75a8c2ed4 | bigcode/the-stack | train |
d1abb2794c2f93fb4b8e513c | train | function | def get_pose_net(cfg, is_train, **kwargs):
model = PoseHighResolutionNet(cfg, **kwargs)
if is_train and cfg['MODEL']['INIT_WEIGHTS']:
model.init_weights(cfg['MODEL']['PRETRAINED'])
return model
| def get_pose_net(cfg, is_train, **kwargs):
| model = PoseHighResolutionNet(cfg, **kwargs)
if is_train and cfg['MODEL']['INIT_WEIGHTS']:
model.init_weights(cfg['MODEL']['PRETRAINED'])
return model
| _init_state_dict[name] = m
self.load_state_dict(need_init_state_dict, strict=False)
elif pretrained:
logger.error('=> please download pre-trained models first!')
raise ValueError('{} is not exist!'.format(pretrained))
def get_pose_net(cfg, is_train, **kwargs):
| 64 | 64 | 53 | 12 | 52 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | get_pose_net | get_pose_net | 528 | 534 | 528 | 528 | 836ceecba4aaaa889fdd393fa91ba31f0b62ae60 | bigcode/the-stack | train |
81c015e85b75b208a39b2c48 | train | class | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv2 =... | class Bottleneck(nn.Module):
| expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(planes, planes, ke... | self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residu... | 96 | 96 | 322 | 6 | 89 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | Bottleneck | Bottleneck | 60 | 98 | 60 | 60 | b5a8cd8afd945feb167929855ba2a93b498338f3 | bigcode/the-stack | train |
97af57a85166cd11f429b51d | train | class | class HighResolutionModule(nn.Module):
def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
num_channels, fuse_method, multi_scale_output=True):
super(HighResolutionModule, self).__init__()
self._check_branches(
num_branches, blocks, num_blocks, num_incha... | class HighResolutionModule(nn.Module):
| def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
num_channels, fuse_method, multi_scale_output=True):
super(HighResolutionModule, self).__init__()
self._check_branches(
num_branches, blocks, num_blocks, num_inchannels, num_channels)
self.num_... | d(planes, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
... | 256 | 256 | 1,228 | 7 | 248 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | HighResolutionModule | HighResolutionModule | 101 | 265 | 101 | 101 | 1254a516a878a638108b699587995810714dc548 | bigcode/the-stack | train |
62378b53addfdb7017373e64 | train | class | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)... | class BasicBlock(nn.Module):
| expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3... | = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
| 66 | 66 | 223 | 6 | 60 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | BasicBlock | BasicBlock | 28 | 57 | 28 | 28 | c84736063ac41072dc468e0f7d94092a40b3931d | bigcode/the-stack | train |
da0b4670c270b11f65f9a995 | train | function | def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| def conv3x3(in_planes, out_planes, stride=1):
| """3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
| from __future__ import division
from __future__ import print_function
import os
import logging
import torch
import torch.nn as nn
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
| 64 | 64 | 53 | 15 | 49 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | conv3x3 | conv3x3 | 22 | 25 | 22 | 22 | 95abd420f09085ca977ad9440a37fe26f7f768c8 | bigcode/the-stack | train |
2f355b8e99d70ff004a145e0 | train | class | class PoseHighResolutionNet(nn.Module):
def __init__(self, cfg, **kwargs):
self.inplanes = 64
extra = cfg['MODEL']['EXTRA']
super(PoseHighResolutionNet, self).__init__()
# stem net
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
... | class PoseHighResolutionNet(nn.Module):
| def __init__(self, cfg, **kwargs):
self.inplanes = 64
extra = cfg['MODEL']['EXTRA']
super(PoseHighResolutionNet, self).__init__()
# stem net
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
bias=False)
self.bn1 = nn.Bat... | 2d(num_outchannels_conv3x3),
nn.ReLU(True)
)
)
fuse_layer.append(nn.Sequential(*conv3x3s))
fuse_layers.append(nn.ModuleList(fuse_layer))
return nn.ModuleList(fuse_layers)
def get... | 256 | 256 | 2,098 | 8 | 248 | simonwey/DecoupleNet | lib/models/pose_hrnet_multi_task_lambda.py | Python | PoseHighResolutionNet | PoseHighResolutionNet | 274 | 525 | 274 | 275 | 5aea969cd909d2a5314621986b64303107c19ecf | bigcode/the-stack | train |
9015f45a114474d00589ec5e | train | function | def check_version(actual_version):
if type(actual_version) != "string" or len(actual_version) < 5:
return # Unexpected format
# Please use length 3 tuples, because bazel versions has 3 members;
# to avoid surprising behaviors (for example (2,0) >/= (2, 0, 0))
min_bazel = (4, 0, 0) # Change TH... | def check_version(actual_version):
| if type(actual_version) != "string" or len(actual_version) < 5:
return # Unexpected format
# Please use length 3 tuples, because bazel versions has 3 members;
# to avoid surprising behaviors (for example (2,0) >/= (2, 0, 0))
min_bazel = (4, 0, 0) # Change THIS LINE when changing bazel min ver... | "0.29.1" or "0.29 foobar"
Returns:
The version as a int list such as [2, 0], [0, 29, 1], or [0, 29]
"""
return [int(_parse_version_chunk(x)) for x in bazel_version.split(".")]
def check_version(actual_version):
| 76 | 77 | 259 | 6 | 70 | aveltras/rules_haskell | haskell/private/versions.bzl | Python | check_version | check_version | 41 | 60 | 41 | 41 | 52655680a24471358814f3c35e28274408bc8d14 | bigcode/the-stack | train |
d511fa35aeb7b8c9e03cb6be | train | function | def _parse_version_chunk(version_chunk):
"""
Args:
version_chunk: a chunk of a semantic version, possibly with trailing
content at the end; such as "29", "2", or "3 foobar".
We handle trailing content because
native.bazel_version can: try prin... | def _parse_version_chunk(version_chunk):
| """
Args:
version_chunk: a chunk of a semantic version, possibly with trailing
content at the end; such as "29", "2", or "3 foobar".
We handle trailing content because
native.bazel_version can: try printing actual_version
... | bazel_skylib//lib:versions.bzl", "versions")
# But we don't want to use them, as skylib is not yet loaded when code
# in this file executes (and there's no way to execute it later; see first
# paragraph above).
def _parse_version_chunk(version_chunk):
| 64 | 64 | 152 | 8 | 56 | aveltras/rules_haskell | haskell/private/versions.bzl | Python | _parse_version_chunk | _parse_version_chunk | 13 | 29 | 13 | 13 | a460edc5d08baaefb1dcf642978ddf59647c2c40 | bigcode/the-stack | train |
f35b931dbc3f3a92d9b65879 | train | function | def _parse_bazel_version(bazel_version):
"""
Args:
bazel_version: a string that starts with a semantic version
like "2.0" or "0.29.1" or "0.29 foobar"
Returns:
The version as a int list such as [2, 0], [0, 29, 1], or [0, 29]
"""
return [int(_parse_version_chunk(x)) f... | def _parse_bazel_version(bazel_version):
| """
Args:
bazel_version: a string that starts with a semantic version
like "2.0" or "0.29.1" or "0.29 foobar"
Returns:
The version as a int list such as [2, 0], [0, 29, 1], or [0, 29]
"""
return [int(_parse_version_chunk(x)) for x in bazel_version.split(".")]
| with trailing content removed, such as "29", "2", or "3"
"""
for i in range(len(version_chunk)):
c = version_chunk[i]
if not c.isdigit():
return version_chunk[:i]
return version_chunk
def _parse_bazel_version(bazel_version):
| 64 | 64 | 107 | 10 | 53 | aveltras/rules_haskell | haskell/private/versions.bzl | Python | _parse_bazel_version | _parse_bazel_version | 31 | 39 | 31 | 31 | a94fdba7a63204777c1096be352d974db8a91455 | bigcode/the-stack | train |
3f983cccd16c216ea9ba0ce8 | train | function | def find_loop_size(subject, key, init=1):
loop_size = 0
val = init
while val != key:
val = transform(subject=subject, init=val)
loop_size += 1
return loop_size
| def find_loop_size(subject, key, init=1):
| loop_size = 0
val = init
while val != key:
val = transform(subject=subject, init=val)
loop_size += 1
return loop_size
| import sys
def transform(subject, loop_size=1, init=1, mod=20201227):
value = init
for i in range(loop_size):
value = (value * subject) % mod
return value
def find_loop_size(subject, key, init=1):
| 62 | 64 | 54 | 12 | 49 | andrewblim/advent-of-code-2020 | py/advent_of_code_2020/day25.py | Python | find_loop_size | find_loop_size | 11 | 17 | 11 | 11 | a0fee6f9fe309e84a8c8586bb8eae89a29127b61 | bigcode/the-stack | train |
bebce627ccb0953aaeaeeb0b | train | function | def transform(subject, loop_size=1, init=1, mod=20201227):
value = init
for i in range(loop_size):
value = (value * subject) % mod
return value
| def transform(subject, loop_size=1, init=1, mod=20201227):
| value = init
for i in range(loop_size):
value = (value * subject) % mod
return value
| import sys
def transform(subject, loop_size=1, init=1, mod=20201227):
| 22 | 64 | 47 | 19 | 2 | andrewblim/advent-of-code-2020 | py/advent_of_code_2020/day25.py | Python | transform | transform | 4 | 8 | 4 | 4 | 40be1f9af5f3f51fd98ff6243f507d8c516de033 | bigcode/the-stack | train |
aa0e14401cde70251a08f28c | train | function | def find_encryption_key(key1, key2, subject):
loop_size1 = find_loop_size(subject, key1)
loop_size2 = find_loop_size(subject, key2)
encryption1 = transform(key2, loop_size1)
encryption2 = transform(key1, loop_size2)
if encryption1 != encryption2:
raise RuntimeError(f"unequal encryption keys ... | def find_encryption_key(key1, key2, subject):
| loop_size1 = find_loop_size(subject, key1)
loop_size2 = find_loop_size(subject, key2)
encryption1 = transform(key2, loop_size1)
encryption2 = transform(key1, loop_size2)
if encryption1 != encryption2:
raise RuntimeError(f"unequal encryption keys {encryption1} {encryption2}")
return encry... | _size(subject, key, init=1):
loop_size = 0
val = init
while val != key:
val = transform(subject=subject, init=val)
loop_size += 1
return loop_size
def find_encryption_key(key1, key2, subject):
| 64 | 64 | 96 | 13 | 50 | andrewblim/advent-of-code-2020 | py/advent_of_code_2020/day25.py | Python | find_encryption_key | find_encryption_key | 20 | 27 | 20 | 20 | 878bd2c3efa94222ae1dd80a31659bea259aaa9e | bigcode/the-stack | train |
1324ffd56db20542e1c9f82f | train | function | @app.middleware("http")
async def add_correlation_header(request: Request, call_next):
correlation_id = str(uuid.uuid4())
response = await call_next(request)
response.headers["X-Correlation-Id"] = correlation_id
return response
| @app.middleware("http")
async def add_correlation_header(request: Request, call_next):
| correlation_id = str(uuid.uuid4())
response = await call_next(request)
response.headers["X-Correlation-Id"] = correlation_id
return response
| http://localhost:*', 'https://app.dev.blockmedisolutions.com'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)]
app = FastAPI(middleware=middleware)
@app.middleware("http")
async def add_correlation_header(request: Request, call_next):
| 64 | 64 | 54 | 19 | 45 | monoper/BlockchainDB | example/app/main.py | Python | add_correlation_header | add_correlation_header | 28 | 33 | 28 | 29 | f34901133129215cbc13ff6c7d3d94c581ecddd0 | bigcode/the-stack | train |
e2ed8953211b4a8a26bd25e7 | train | function | @app.get('/api/health', status_code=status.HTTP_200_OK)
def health():
"""Health check endpoint for use by ECS"""
return True
| @app.get('/api/health', status_code=status.HTTP_200_OK)
def health():
| """Health check endpoint for use by ECS"""
return True
| _next(request)
response.headers["X-Correlation-Id"] = correlation_id
return response
app.include_router(auth_api)
app.include_router(client_api)
app.include_router(provider_api)
app.include_router(blockchain_api)
@app.get('/api/health', status_code=status.HTTP_200_OK)
def health():
| 64 | 64 | 32 | 18 | 46 | monoper/BlockchainDB | example/app/main.py | Python | health | health | 40 | 43 | 40 | 41 | be5c6bb4f169eef7fd598cd79b39ac81201338f9 | bigcode/the-stack | train |
3f236de64adcdfb8e5edad57 | train | function | @comment.route('/api/v1/courses/<course_id>/comments', methods=['POST'])
@jwt_required
def add_new_comment(course_id):
"""adds comment to course."""
data = request.get_json()
if data:
if not course_controller.query_course(course_id):
return jsonify({
'message': 'Cour... | @comment.route('/api/v1/courses/<course_id>/comments', methods=['POST'])
@jwt_required
def add_new_comment(course_id):
| """adds comment to course."""
data = request.get_json()
if data:
if not course_controller.query_course(course_id):
return jsonify({
'message': 'Course does not exist in database'
}), 404
comment_controller.add_new_comment(data, course_id)
... | controller import CommentController
from ..courses.controller import CourseController
comment = Blueprint('comment', __name__)
comment_controller = CommentController()
course_controller = CourseController()
@comment.route('/api/v1/courses/<course_id>/comments', methods=['POST'])
@jwt_required
def add_new_comment(cours... | 64 | 64 | 122 | 30 | 34 | BuildForSDG/Team-273-Backend | src/comments/view.py | Python | add_new_comment | add_new_comment | 11 | 25 | 11 | 13 | 3fa308f717e5b2e4291403ca05f163fcd6869189 | bigcode/the-stack | train |
a8aa98db46d327294c65f71e | train | function | @comment.route('/api/v1/courses/<course_id>/comments', methods=['GET'])
def fetch_comment(course_id):
"""gets comment to course."""
if not course_controller.query_course(course_id):
return jsonify({
'message': 'Course does not exist in database'
}), 400
else:
comm... | @comment.route('/api/v1/courses/<course_id>/comments', methods=['GET'])
def fetch_comment(course_id):
| """gets comment to course."""
if not course_controller.query_course(course_id):
return jsonify({
'message': 'Course does not exist in database'
}), 400
else:
comments = comment_controller.fetch_comments(course_id)
return jsonify({"comments": comments}), 20... | _new_comment(data, course_id)
return jsonify({"message": "comment added successfully"}), 200
else:
return jsonify({"message": "No data"}), 400
@comment.route('/api/v1/courses/<course_id>/comments', methods=['GET'])
def fetch_comment(course_id):
| 64 | 64 | 87 | 25 | 38 | BuildForSDG/Team-273-Backend | src/comments/view.py | Python | fetch_comment | fetch_comment | 29 | 38 | 29 | 30 | 87f08661c6d23903bf01cc9e58373000b9fb7069 | bigcode/the-stack | train |
29c84c312e6affebad6e3959 | train | class | class TypeWithDefault(type):
def __init__(cls, name, bases, dct):
super(TypeWithDefault, cls).__init__(name, bases, dct)
cls._default = None
def __call__(cls):
if cls._default is None:
cls._default = type.__call__(cls)
return copy.copy(cls._default)
def set_defa... | class TypeWithDefault(type):
| def __init__(cls, name, bases, dct):
super(TypeWithDefault, cls).__init__(name, bases, dct)
cls._default = None
def __call__(cls):
if cls._default is None:
cls._default = type.__call__(cls)
return copy.copy(cls._default)
def set_default(cls, default):
cl... | @renci.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import copy
import logging
import multiprocessing
import sys
import urllib3
import six
from six.moves import http_client as httplib
class TypeWithDefault(type):
| 64 | 64 | 95 | 6 | 57 | atlanticwave-sdx/sdx-controller-client | swagger_client/configuration.py | Python | TypeWithDefault | TypeWithDefault | 25 | 36 | 25 | 25 | 1a93fb8d1c9116f1d902e5db717c8d6ea6f93373 | bigcode/the-stack | train |
35e28607910126240dcf6feb | train | class | class Configuration(six.with_metaclass(TypeWithDefault, object)):
"""NOTE: This class is auto generated by the swagger code generator program.
Ref: https://github.com/swagger-api/swagger-codegen
Do not edit the class manually.
"""
def __init__(self):
"""Constructor"""
# Default Bas... | class Configuration(six.with_metaclass(TypeWithDefault, object)):
| """NOTE: This class is auto generated by the swagger code generator program.
Ref: https://github.com/swagger-api/swagger-codegen
Do not edit the class manually.
"""
def __init__(self):
"""Constructor"""
# Default Base url
#self.host = "https://virtserver.swaggerhub.com/SDX-... | # coding: utf-8
"""
SDX-Controller
You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: yxin@renci.org
Generated by: https://github.com/swagger-api/swagger-code... | 245 | 256 | 1,625 | 13 | 232 | atlanticwave-sdx/sdx-controller-client | swagger_client/configuration.py | Python | Configuration | Configuration | 39 | 264 | 39 | 39 | 3b4f14cad7339c0ae6fa587fba9cc385f545ebb6 | bigcode/the-stack | train |
c614d8177b8e9a32b85215a7 | train | function | def list_rules():
return protocol_policies
| def list_rules():
| return protocol_policies
| OS-FEDERATION/identity_providers/{idp_id}/'
'protocols/{protocol_id}'),
'method': 'DELETE'}],
deprecated_rule=deprecated_delete_protocol,
deprecated_reason=DEPRECATED_REASON,
deprecated_since=versionutils.deprecated.STEIN)
]
def list_rules():
| 64 | 64 | 10 | 4 | 60 | ferag/keystone | keystone/common/policies/protocol.py | Python | list_rules | list_rules | 106 | 107 | 106 | 106 | 138be2aa48c7619f176a6899952046e263c54fd8 | bigcode/the-stack | train |
a5eccbd535675e93e7f71fad | train | class | class Garage(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, id: int=None, name: str=None, address: str=None, date_created: datetime=None, max_capacity: int=None): # noqa: E501
"""Garage - a model defi... | class Garage(Model):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, id: int=None, name: str=None, address: str=None, date_created: datetime=None, max_capacity: int=None): # noqa: E501
"""Garage - a model defined in Swagger
... | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Garage(Model):
| 61 | 256 | 1,063 | 4 | 56 | espretto/demo-garage | swagger_server/models/garage.py | Python | Garage | Garage | 12 | 176 | 12 | 12 | 0c842853204c297a3286596736ec725af5695606 | bigcode/the-stack | train |
9ac90c6d873d2451ad17e826 | train | class | class binanceusdm(binance):
def describe(self):
return self.deep_extend(super(binanceusdm, self).describe(), {
'id': 'binanceusdm',
'name': 'Binance USDⓈ-M',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/117738721-668c8d80-b205-11eb... | class binanceusdm(binance):
| def describe(self):
return self.deep_extend(super(binanceusdm, self).describe(), {
'id': 'binanceusdm',
'name': 'Binance USDⓈ-M',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/117738721-668c8d80-b205-11eb-8c49-3fad84c4a07f.jpg',
... | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.binance import binance
from ccxt.base.errors import BadRequest
class binanceusdm(binance):
| 79 | 256 | 2,527 | 8 | 70 | guyo13/ccxt | python/ccxt/binanceusdm.py | Python | binanceusdm | binanceusdm | 10 | 248 | 10 | 11 | 0975e43b97e4812f84803e1249dd9f731a3d178e | bigcode/the-stack | train |
be0f42b7d4c8adbc941f8f8f | train | class | class LabelThings:
LABEL_THING_SFN = "SFN"
LABEL_THING_WRISTBANDGW = "WRISTBAND-GW"
| class LabelThings:
| LABEL_THING_SFN = "SFN"
LABEL_THING_WRISTBANDGW = "WRISTBAND-GW"
| class LabelThings:
| 4 | 64 | 33 | 4 | 0 | MONICA-Project/HLDFAD_SourceCode | monica/general_types/label_ogc.py | Python | LabelThings | LabelThings | 1 | 3 | 1 | 1 | c3e0316da19fb760cf3ee6e303d7339174cb7efa | bigcode/the-stack | train |
d23a563c381d22ff15d5c65f | train | class | class LabelObservationType:
LABEL_OBSTYPE_LOCALIZATION = "Localization"
LABEL_OBSTYPE_CROWDDENSITY = "CrowdDensityLocal"
| class LabelObservationType:
| LABEL_OBSTYPE_LOCALIZATION = "Localization"
LABEL_OBSTYPE_CROWDDENSITY = "CrowdDensityLocal"
| = "SFN"
LABEL_THING_WRISTBANDGW = "WRISTBAND-GW"
class LabelOGCDatastreams:
LABEL_DATASTREAM_LOCALIZATION = "Localization"
LABEL_DATASTREAM_CROWDDENSITYLOCAL = "CDL-Estimation"
class LabelObservationType:
| 64 | 64 | 33 | 5 | 59 | MONICA-Project/HLDFAD_SourceCode | monica/general_types/label_ogc.py | Python | LabelObservationType | LabelObservationType | 11 | 13 | 11 | 11 | 2931e6134f52204e70e1bb137edae570f8277dd9 | bigcode/the-stack | train |
95eb982479970b5d58994862 | train | class | class LabelOGCDatastreams:
LABEL_DATASTREAM_LOCALIZATION = "Localization"
LABEL_DATASTREAM_CROWDDENSITYLOCAL = "CDL-Estimation"
| class LabelOGCDatastreams:
| LABEL_DATASTREAM_LOCALIZATION = "Localization"
LABEL_DATASTREAM_CROWDDENSITYLOCAL = "CDL-Estimation"
| class LabelThings:
LABEL_THING_SFN = "SFN"
LABEL_THING_WRISTBANDGW = "WRISTBAND-GW"
class LabelOGCDatastreams:
| 41 | 64 | 36 | 8 | 33 | MONICA-Project/HLDFAD_SourceCode | monica/general_types/label_ogc.py | Python | LabelOGCDatastreams | LabelOGCDatastreams | 6 | 8 | 6 | 6 | 9dfebfb9b2f552e3eaf076e1daa445eef54e6fc5 | bigcode/the-stack | train |
ce7df7d211ee7a5912242403 | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'List.slug'
db.add_column('server_list', 'slug',
self.gf('django.db.models.fields.SlugField')(default=datetime.datetime(2013, 2, 11, 0, 0), unique=True, max_length=300),
keep_defaul... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding field 'List.slug'
db.add_column('server_list', 'slug',
self.gf('django.db.models.fields.SlugField')(default=datetime.datetime(2013, 2, 11, 0, 0), unique=True, max_length=300),
keep_default=False)
def backwards(self, ... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 37 | 256 | 1,793 | 6 | 30 | jvashishtha/listypedia | server/migrations/0004_auto__add_field_list_slug.py | Python | Migration | Migration | 8 | 113 | 8 | 9 | 9e6d39f037e1f629796d136a11d863e20a3f7302 | bigcode/the-stack | train |
cdd0b569fe3fc2e2dc71b73c | train | function | def positive_sum(arr):
soma = 0
# pega somente os números positivos da lista
for positivo in arr:
if positivo > 0:
#print(f'{positivo}', end=' ')
soma = soma + positivo
#print(soma)
return soma
| def positive_sum(arr):
| soma = 0
# pega somente os números positivos da lista
for positivo in arr:
if positivo > 0:
#print(f'{positivo}', end=' ')
soma = soma + positivo
#print(soma)
return soma
| ,7,12]
Saída: 1 + 7 + 12 = 20
Entrada: [-1, -1, -9, 1]
Saída: 1
Entrada: []
Saída: 0
"""
# função soma número positivo de uma lista
def positive_sum(arr):
| 64 | 64 | 61 | 5 | 58 | giselemanuel/programa-Ifood-backend | qualified/sem5_qualified_5.py | Python | positive_sum | positive_sum | 22 | 30 | 22 | 22 | 26b5b930a0b0d65444b33ea2c7b0e73c0d06fa42 | bigcode/the-stack | train |
ee8afe4c5b18754af09aecc8 | train | function | def periods_constructor(duration,
year_start=YEAR_START_CALIBRATION,
year_end=YEAR_END_CALIBRATION,
stride=1):
"""
Construction of individual calibration periods
Input:
duration: the required duration in calender years, int
y... | def periods_constructor(duration,
year_start=YEAR_START_CALIBRATION,
year_end=YEAR_END_CALIBRATION,
stride=1):
| """
Construction of individual calibration periods
Input:
duration: the required duration in calender years, int
year_start: the first year considered, int
year_end: the last year considered, int
stride: default=1
Output:
the list of considered calender years
"""
duratio... | _epoch_end(self, epoch, log={}):
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
# Preparation of the periods
def periods_constructor(duration,
year_start=YEAR_START_CALIBRATION,
year_end=YEAR_END_CALIBRATION,
stride=1):
| 64 | 64 | 156 | 33 | 30 | hydrogo/KALIv2 | code/ann_script.py | Python | periods_constructor | periods_constructor | 253 | 280 | 253 | 256 | f40f2a3cb04a2ab932d8003df8db836941215cdf | bigcode/the-stack | train |
b9f94fd586729a1ebc5afc62 | train | function | def nse(y_true, y_pred):
return 1 - np.nansum((y_true-y_pred)**2)/np.nansum((y_true-np.nanmean(y_true))**2)
| def nse(y_true, y_pred):
| return 1 - np.nansum((y_true-y_pred)**2)/np.nansum((y_true-np.nanmean(y_true))**2)
| _std
batch_y_val -= self.y_mean
batch_y_val /= self.y_std
return batch_x_val
def on_epoch_end(self):
pass # to nothing as it is only a single epoch
###############################################################################
# HELPERS
# NSE
def nse(y_true, y_pred):... | 64 | 64 | 43 | 9 | 54 | hydrogo/KALIv2 | code/ann_script.py | Python | nse | nse | 242 | 243 | 242 | 242 | b36ff00202b4b1a496fd89fdb0c192bfd3a9ea77 | bigcode/the-stack | train |
24c8ca334be4bb8be0517794 | train | class | class Generator_validation(keras.utils.Sequence):
# Class is a dataset wrapper for better training performance
def __init__(self,
data_instance,
year_start,
year_end,
norms,
history=720,
batch_size=256):
... | class Generator_validation(keras.utils.Sequence):
# Class is a dataset wrapper for better training performance
| def __init__(self,
data_instance,
year_start,
year_end,
norms,
history=720,
batch_size=256):
self.data_instance = data_instance
self.year_start, self.year_end = year_start, year_end
... | -= self.X_mean
batch_x_test /= self.X_std
batch_y_train -= self.y_mean
batch_y_train /= self.y_std
batch_y_test -= self.y_mean
batch_y_test /= self.y_std
if self.mode == "train":
return batch_x_train, batch_y_train
elif self.mode == "test":... | 138 | 138 | 461 | 20 | 117 | hydrogo/KALIv2 | code/ann_script.py | Python | Generator_validation | Generator_validation | 185 | 237 | 185 | 186 | 8aff058bc6a649f635237da5dd3d5641b1d10dac | bigcode/the-stack | train |
0149574e724abc01fe9bd7d1 | train | function | def single_experiment(basin_id,
year_start,
year_end,
model_name="GRU",
hidden_state=20,
history=720,
epochs=300,
patience=5,
batch_size=256,
... | def single_experiment(basin_id,
year_start,
year_end,
model_name="GRU",
hidden_state=20,
history=720,
epochs=300,
patience=5,
batch_size=256,
... | results_folder = f'../results/{basin_id}/{model_name}'
if not os.path.exists(results_folder):
os.makedirs(results_folder)
# read data for a particular basin
data = pd.read_pickle(os.path.join(path_forcing, f'{basin_id}.pkl'))
# initialize model
model = constructor(model_name=mo... | log={}):
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
# Preparation of the periods
def periods_constructor(duration,
year_start=YEAR_START_CALIBRATION,
year_end=YEAR_END_CALIBRATION,
stride=1):
"""
Construction of... | 256 | 256 | 1,112 | 66 | 189 | hydrogo/KALIv2 | code/ann_script.py | Python | single_experiment | single_experiment | 284 | 413 | 284 | 295 | 42161547fcd20d617d379f1fbc3d3094c2103bdc | bigcode/the-stack | train |
7904fae5cfcae5d2d1167bc2 | train | function | def constructor(model_name="GRU",
hidden_state=20,
history=720,
hindcast=1,
input_vars=3,
loss=LOSS,
optimizer=keras.optimizers.Adam()):
# model instance initialization
model = keras.models.Sequential()
... | def constructor(model_name="GRU",
hidden_state=20,
history=720,
hindcast=1,
input_vars=3,
loss=LOSS,
optimizer=keras.optimizers.Adam()):
# model instance initialization
| model = keras.models.Sequential()
# add a core layer
if model_name == "GRU":
model.add(keras.layers.GRU(hidden_state, return_sequences=False, input_shape=(history, input_vars)))
elif model_name == "LSTM":
model.add(keras.layers.LSTM(hidden_state, return_sequences=False, input_shape=... | ()
###############################################################################
# Constructor for model definition
def constructor(model_name="GRU",
hidden_state=20,
history=720,
hindcast=1,
input_vars=3,
loss=LOSS,
... | 64 | 64 | 175 | 55 | 8 | hydrogo/KALIv2 | code/ann_script.py | Python | constructor | constructor | 72 | 95 | 72 | 80 | 6a26806a4c699308dabf141f770219d8c10b902d | bigcode/the-stack | train |
c1a4a088f4dfa926c66b8f17 | train | function | def seed_everything(seed=42):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
| def seed_everything(seed=42):
| random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
| 14]
###############################################################################
# GPU environment preparation
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
##############################################... | 64 | 64 | 33 | 8 | 55 | hydrogo/KALIv2 | code/ann_script.py | Python | seed_everything | seed_everything | 63 | 66 | 63 | 63 | ecbf8cb73295d02ac55e514acd789c8614f05ca2 | bigcode/the-stack | train |
d0405d8e241d2e554ce37c18 | train | class | class Generator_calibration(keras.utils.Sequence):
# Class is a dataset wrapper for better training performance
def __init__(self,
data_instance,
year_start,
year_end,
history=720,
batch_size=256,
validat... | class Generator_calibration(keras.utils.Sequence):
# Class is a dataset wrapper for better training performance
| def __init__(self,
data_instance,
year_start,
year_end,
history=720,
batch_size=256,
validation_split=0.25,
mode="train"):
self.data_instance = data_instance
self.ye... | HASHSEED'] = str(seed)
np.random.seed(seed)
seed_everything()
###############################################################################
# Constructor for model definition
def constructor(model_name="GRU",
hidden_state=20,
history=720,
hindcast=1,
... | 230 | 230 | 769 | 21 | 208 | hydrogo/KALIv2 | code/ann_script.py | Python | Generator_calibration | Generator_calibration | 99 | 181 | 99 | 100 | 3edaa94e15e2679a22533bcfa35b79b3c4577260 | bigcode/the-stack | train |
5e665b217175cfbdbbccc860 | train | class | class MemoryCallback(keras.callbacks.Callback):
def on_epoch_end(self, epoch, log={}):
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
| class MemoryCallback(keras.callbacks.Callback):
| def on_epoch_end(self, epoch, log={}):
print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
| ###
# HELPERS
# NSE
def nse(y_true, y_pred):
return 1 - np.nansum((y_true-y_pred)**2)/np.nansum((y_true-np.nanmean(y_true))**2)
# Memory leakage detection
class MemoryCallback(keras.callbacks.Callback):
| 64 | 64 | 36 | 8 | 55 | hydrogo/KALIv2 | code/ann_script.py | Python | MemoryCallback | MemoryCallback | 247 | 249 | 247 | 247 | a85680289e1938e37cdba9ae1b86c605db6a4407 | bigcode/the-stack | train |
10246759624fff72566e9ce8 | train | class | class BlankResult(AutomatedRunResult):
def _make_summary(self):
s = self._air_ratio()
return s
| class BlankResult(AutomatedRunResult):
| def _make_summary(self):
s = self._air_ratio()
return s
| _make_summary(self):
s = self._air_ratio()
return s
class UnknownResult(AutomatedRunResult):
def _make_summary(self):
lines = ["AGE= {}".format(self.isotope_group.age)]
return "\n".join(lines)
class BlankResult(AutomatedRunResult):
| 64 | 64 | 28 | 9 | 55 | ASUPychron/pychron | pychron/experiment/automated_run/result.py | Python | BlankResult | BlankResult | 187 | 190 | 187 | 187 | 8093ff99c111ac304cf41866344084c54b9c3ad2 | bigcode/the-stack | train |
aafee474310582d4f28b0866 | train | class | class AutomatedRunResult(HasTraits):
runid = Str
analysis_timestamp = None
isotope_group = Instance(IsotopeGroup)
summary = Property
tripped_conditional = Instance(AutomatedRunConditional)
centering_results = None
def _get_summary(self):
lines = ["RunID= {}".format(self.runid)]
... | class AutomatedRunResult(HasTraits):
| runid = Str
analysis_timestamp = None
isotope_group = Instance(IsotopeGroup)
summary = Property
tripped_conditional = Instance(AutomatedRunConditional)
centering_results = None
def _get_summary(self):
lines = ["RunID= {}".format(self.runid)]
at = self.analysis_timestamp
... | # ===============================================================================
# Copyright 2016 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | 247 | 256 | 1,062 | 8 | 238 | ASUPychron/pychron | pychron/experiment/automated_run/result.py | Python | AutomatedRunResult | AutomatedRunResult | 30 | 172 | 30 | 30 | aa2c52b056510b3e9c343490a60eb9a849c2810f | bigcode/the-stack | train |
27a94c0938cf788f01792b57 | train | class | class UnknownResult(AutomatedRunResult):
def _make_summary(self):
lines = ["AGE= {}".format(self.isotope_group.age)]
return "\n".join(lines)
| class UnknownResult(AutomatedRunResult):
| def _make_summary(self):
lines = ["AGE= {}".format(self.isotope_group.age)]
return "\n".join(lines)
| 30 - len(h)))
def _make_lines(self, lines):
return "{}\n".format("\n".join(lines))
class AirResult(AutomatedRunResult):
def _make_summary(self):
s = self._air_ratio()
return s
class UnknownResult(AutomatedRunResult):
| 64 | 64 | 38 | 9 | 54 | ASUPychron/pychron | pychron/experiment/automated_run/result.py | Python | UnknownResult | UnknownResult | 181 | 184 | 181 | 181 | 32232445669a4306bccbd05df37f3eb887d36e51 | bigcode/the-stack | train |
5b73522f78e1ef2da9c13134 | train | class | class AirResult(AutomatedRunResult):
def _make_summary(self):
s = self._air_ratio()
return s
| class AirResult(AutomatedRunResult):
| def _make_summary(self):
s = self._air_ratio()
return s
| (lines)
return ret
def _make_header(self, h):
return "============================= {} {}".format(h, "=" * (30 - len(h)))
def _make_lines(self, lines):
return "{}\n".format("\n".join(lines))
class AirResult(AutomatedRunResult):
| 64 | 64 | 28 | 9 | 55 | ASUPychron/pychron | pychron/experiment/automated_run/result.py | Python | AirResult | AirResult | 175 | 178 | 175 | 175 | 90088f9323a7df620c8225824e34754ce9c710e0 | bigcode/the-stack | train |
0d89f23f191328a92c7b294e | train | class | class GenThread(object):
"""Base gen-thread class, holds thread ID, reference to scheduler.
Passes on API calls to back-end scheduler"""
sharedThreadObjects = {}
def __init__(self, gen_id, interface):
self.genThreadID = gen_id
self.interface = interface
self.sequences = list()
... | class GenThread(object):
| """Base gen-thread class, holds thread ID, reference to scheduler.
Passes on API calls to back-end scheduler"""
sharedThreadObjects = {}
def __init__(self, gen_id, interface):
self.genThreadID = gen_id
self.interface = interface
self.sequences = list()
self.setupModifie... | init_pc)
# Setup memory region for boot instructions
def setupBootRegion(self):
raise NotImplementedError
# Setup essentials like key register fields, etc
def setupEssentials(self):
raise NotImplementedError
# Return initial main test PC for the generator thread
def getInitia... | 256 | 256 | 5,216 | 5 | 251 | Wlgen/force-riscv | py/base/GenThread.py | Python | GenThread | GenThread | 82 | 703 | 82 | 82 | 2816d399bd9fab53a94e3645ff1ddbd86a3ec36b | bigcode/the-stack | train |
625190c4f849d84b6f743b91 | train | class | class GenThreadEndSequence(Sequence):
def __init__(self, gen_thread, name):
super().__init__(gen_thread, name)
def generate(self, **kargs):
# generate end of test sequence
self.genSequence("EndOfTest")
# generate BNT code
self.genSequence("BranchNotTaken")
# load... | class GenThreadEndSequence(Sequence):
| def __init__(self, gen_thread, name):
super().__init__(gen_thread, name)
def generate(self, **kargs):
# generate end of test sequence
self.genSequence("EndOfTest")
# generate BNT code
self.genSequence("BranchNotTaken")
# loading registers after booting
se... | raise NotImplementedError
# Set default StateTransitionHandlers to process StateElements of each type
def setDefaultStateTransitionHandlers(self):
raise NotImplementedError
# GenThreadEndSequence class
# Generate common sequences at the end of every test thread.
class GenThreadEndSequence(Sequence... | 64 | 64 | 102 | 8 | 56 | Wlgen/force-riscv | py/base/GenThread.py | Python | GenThreadEndSequence | GenThreadEndSequence | 67 | 79 | 67 | 67 | 4f70c1fc66ab6d0a80a9889f7dfcb0607a992485 | bigcode/the-stack | train |
fd38599fc3dbecf73ecbc080 | train | class | class GenThreadSetupSequence(Sequence):
def __init__(self, gen_thread, name):
super().__init__(gen_thread, name)
def generate(self, **kargs):
self.setPEstate("BootPC", self.getBootPC())
self.setupBootRegion()
self.setupEssentials()
self.setDefaultStateTransitionHandlers(... | class GenThreadSetupSequence(Sequence):
| def __init__(self, gen_thread, name):
super().__init__(gen_thread, name)
def generate(self, **kargs):
self.setPEstate("BootPC", self.getBootPC())
self.setupBootRegion()
self.setupEssentials()
self.setDefaultStateTransitionHandlers()
init_pc = self.getInitialPC()
... | RandomUtils
from base.ItemMap import ItemMap
from base.Macro import Macro
from base.Sequence import Sequence
from base.TestException import *
from base.ThreadRequest import ThreadRequestContextManager
# GenThreadSetupSequence class
# Generate common sequence at the beginning of each test thread.
class GenThreadSe... | 69 | 69 | 230 | 8 | 61 | Wlgen/force-riscv | py/base/GenThread.py | Python | GenThreadSetupSequence | GenThreadSetupSequence | 31 | 62 | 31 | 31 | ce5bf114dd285418efaca3712ab28034a7b1870a | bigcode/the-stack | train |
9df8eba1cbd78e38cbd122de | train | class | class Point(BaseRxVRM):
"""Point receiver"""
times = properties.Array('Observation times', dtype=float)
fieldType = properties.StringChoice(
'Field type', choices=["h", "b", "dhdt", "dbdt"]
)
fieldComp = properties.StringChoice(
'Component of response', choices=["x", "y", "z"]
)... | class Point(BaseRxVRM):
| """Point receiver"""
times = properties.Array('Observation times', dtype=float)
fieldType = properties.StringChoice(
'Field type', choices=["h", "b", "dhdt", "dbdt"]
)
fieldComp = properties.StringChoice(
'Component of response', choices=["x", "y", "z"]
)
# def __init__(sel... | M(Survey.BaseRx, properties.HasProperties):
"""Base VRM receiver class"""
def __init__(self, locs, **kwargs):
super(BaseRxVRM, self).__init__(
locs, 'None', storeProjections=False, **kwargs
)
#########################################
# POINT RECEIVER CLASS FOR VRM
###############... | 81 | 81 | 273 | 7 | 74 | kimjaed/simpeg | SimPEG/VRM/RxVRM.py | Python | Point | Point | 23 | 59 | 23 | 23 | f59c6d9283db4670f67a0ea560597fdc1503df84 | bigcode/the-stack | train |
606fea836bffe60498982e23 | train | class | class BaseRxVRM(Survey.BaseRx, properties.HasProperties):
"""Base VRM receiver class"""
def __init__(self, locs, **kwargs):
super(BaseRxVRM, self).__init__(
locs, 'None', storeProjections=False, **kwargs
)
| class BaseRxVRM(Survey.BaseRx, properties.HasProperties):
| """Base VRM receiver class"""
def __init__(self, locs, **kwargs):
super(BaseRxVRM, self).__init__(
locs, 'None', storeProjections=False, **kwargs
)
| from SimPEG import Survey
import properties
#########################################
# BASE RECEIVER CLASS FOR VRM
#########################################
class BaseRxVRM(Survey.BaseRx, properties.HasProperties):
| 38 | 64 | 63 | 14 | 24 | kimjaed/simpeg | SimPEG/VRM/RxVRM.py | Python | BaseRxVRM | BaseRxVRM | 9 | 16 | 9 | 9 | c17bef556d6fccf1d0b595bc04517cf2bb76f7b0 | bigcode/the-stack | train |
298e40620e7832038ac3a6b1 | train | class | class SquareLoop(BaseRxVRM):
"""Square loop receiver
Measurements with this type of receiver are the field, integrated over the
area of the loop, then multiplied by the number of coils, then normalized
by the dipole moment. As a result, the units for fields predicted with this
type of receiver are ... | class SquareLoop(BaseRxVRM):
| """Square loop receiver
Measurements with this type of receiver are the field, integrated over the
area of the loop, then multiplied by the number of coils, then normalized
by the dipole moment. As a result, the units for fields predicted with this
type of receiver are the same as 'h', 'b', 'dhdt' ... | (Point, self).__init__(locs, **kwargs)
@property
def nTimes(self):
"""Number of measurements times."""
if self.times is not None:
return len(self.times)
@property
def nLocs(self):
"""Number of locations."""
return self.locs.shape[0]
@property
def nD... | 118 | 118 | 394 | 8 | 110 | kimjaed/simpeg | SimPEG/VRM/RxVRM.py | Python | SquareLoop | SquareLoop | 62 | 105 | 62 | 62 | 28eeeb00354f3c00faac4803ad20029a8cd352b2 | bigcode/the-stack | train |
cf94a2df6f0295c360c77952 | train | function | def lambda_handler(event, context):
# TODO implement
device_apn_token = event['queryStringParameters']['device_apn_token']
device_registration_token = event['queryStringParameters']['device_registration_token']
connection = psycopg2.connect(user = "<HANSEL_CONFIG_DB_USER>",
... | def lambda_handler(event, context):
# TODO implement
| device_apn_token = event['queryStringParameters']['device_apn_token']
device_registration_token = event['queryStringParameters']['device_registration_token']
connection = psycopg2.connect(user = "<HANSEL_CONFIG_DB_USER>",
password = "<HANSEL_CONFIG_DB_PASSWORD>",
... | import json
import psycopg2
def lambda_handler(event, context):
# TODO implement
| 21 | 64 | 178 | 12 | 8 | gethansel/hansel | backend/lambdas/reportDiagnosis/lambda_function.py | Python | lambda_handler | lambda_handler | 4 | 23 | 4 | 5 | efbe75be10e9974ed4a33624e4133c3243004d6c | bigcode/the-stack | train |
61362c8540680a1d27cc248c | train | function | def pascal_triangle_3(n):
return [comb(a, b, exact=True) for a in range(n) for b in range(a+1)]
| def pascal_triangle_3(n):
| return [comb(a, b, exact=True) for a in range(n) for b in range(a+1)]
| 2(n):
start = [1]
for i in range(1, n+1):
start.append(start[i - 1] * (n - i + 1) // i)
return start
# Alternative Solution
from scipy.special import comb
def pascal_triangle_3(n):
| 64 | 64 | 33 | 8 | 55 | maxcohen31/A-bored-math-student | Codewars/Pascal_triangle - (6 kyu).py | Python | pascal_triangle_3 | pascal_triangle_3 | 22 | 23 | 22 | 22 | 5ce468efd59907eb6b21da56b92864a78d2a1041 | bigcode/the-stack | train |
63a7b5a2162d789ff862a535 | train | function | def pascal_triangle_2(n):
start = [1]
for i in range(1, n+1):
start.append(start[i - 1] * (n - i + 1) // i)
return start
| def pascal_triangle_2(n):
| start = [1]
for i in range(1, n+1):
start.append(start[i - 1] * (n - i + 1) // i)
return start
| column in range(1, row-1):
end.append(start[-1][column] + start[-1][column-1])
end.append(1)
start.append(end)
return functools.reduce(operator.iconcat, start, [])
# Alternative Solution
def pascal_triangle_2(n):
| 64 | 64 | 51 | 8 | 55 | maxcohen31/A-bored-math-student | Codewars/Pascal_triangle - (6 kyu).py | Python | pascal_triangle_2 | pascal_triangle_2 | 14 | 18 | 14 | 14 | 7151a5011a3b0f52d9f87767d97aad38bf7e6f2a | bigcode/the-stack | train |
20e2d06e8094797d0997b707 | train | function | def pascals_triangle(n):
start = [[1]]
for row in range(2, n+1):
end = [1]
for column in range(1, row-1):
end.append(start[-1][column] + start[-1][column-1])
end.append(1)
start.append(end)
return functools.reduce(operator.iconcat, start, [])
| def pascals_triangle(n):
| start = [[1]]
for row in range(2, n+1):
end = [1]
for column in range(1, row-1):
end.append(start[-1][column] + start[-1][column-1])
end.append(1)
start.append(end)
return functools.reduce(operator.iconcat, start, [])
| import functools
import operator
def pascals_triangle(n):
| 13 | 64 | 84 | 7 | 5 | maxcohen31/A-bored-math-student | Codewars/Pascal_triangle - (6 kyu).py | Python | pascals_triangle | pascals_triangle | 3 | 11 | 3 | 3 | 1be6f0520f0d66529f6ae5cadf7f86dd99942535 | bigcode/the-stack | train |
5c97164caefbbde477bd2ea4 | train | class | class AdminRegisterForm(UserCreationForm):
用户名 = forms.CharField(max_length=200,
error_messages={
'max_length': '长度不超过20',
'required': '用户名不能为空'
})
class Meta(UserCreationForm.Meta):
mode... | class AdminRegisterForm(UserCreationForm):
| 用户名 = forms.CharField(max_length=200,
error_messages={
'max_length': '长度不超过20',
'required': '用户名不能为空'
})
class Meta(UserCreationForm.Meta):
model = Admin
fields = ['name', 'gender... | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm, modelformset_factory
from .models import Admin, User
class AdminRegisterForm(UserCreationForm):
| 44 | 64 | 78 | 8 | 35 | NotEnterprising/DATABASE_supermarket | admin/forms.py | Python | AdminRegisterForm | AdminRegisterForm | 8 | 21 | 8 | 8 | eb20b5844792056ed93c7a1b76b19459b2f51723 | bigcode/the-stack | train |
b7f6288bbc9bc81be92e87ae | train | class | class TestReportCategoryTreeView(ClientMixin, RalphTestCase):
def setUp(self):
self.client = self.login_as_user()
self._create_models()
self._create_assets()
def _create_models(self):
self.keyboard_model = DataCenterAssetModelFactory(
category=CategoryFactory(name="... | class TestReportCategoryTreeView(ClientMixin, RalphTestCase):
| def setUp(self):
self.client = self.login_as_user()
self._create_models()
self._create_assets()
def _create_models(self):
self.keyboard_model = DataCenterAssetModelFactory(
category=CategoryFactory(name="Keyboard"),
type=ObjectModelType.data_center,
... | # -*- coding: utf-8 -*-
import factory
from django.core.exceptions import ValidationError
from ralph.assets.models.choices import ObjectModelType
from ralph.assets.tests.factories import (
CategoryFactory,
DataCenterAssetModelFactory,
ManufacturerFactory
)
from ralph.back_office.models import BackOfficeAss... | 204 | 256 | 1,023 | 13 | 190 | angry-tony/cmdb-ralph | src/ralph/reports/tests.py | Python | TestReportCategoryTreeView | TestReportCategoryTreeView | 30 | 147 | 30 | 31 | df6570842d3c3617f93aae5d2bd4d315981b9a9f | bigcode/the-stack | train |
8e042aa44ecffb481b394120 | train | class | class TestReportAssetAndLicence(RalphTestCase):
def setUp(self):
self.model = DataCenterAssetModelFactory(
category=CategoryFactory(name="Keyboard"),
type=ObjectModelType.data_center,
name='Keyboard1',
manufacturer=ManufacturerFactory(name='M1')
)
... | class TestReportAssetAndLicence(RalphTestCase):
| def setUp(self):
self.model = DataCenterAssetModelFactory(
category=CategoryFactory(name="Keyboard"),
type=ObjectModelType.data_center,
name='Keyboard1',
manufacturer=ManufacturerFactory(name='M1')
)
self.dc_1 = DataCenterAssetFactory(
... | ModelStatusReport)
item = self._get_item(report, 'Keyboard')['children'][0]['children']
self.assertEqual(item[0]['count'], 6)
item = self._get_item(report, 'Mouse')['children'][0]['children']
self.assertEqual(item[0]['count'], 2)
item = self._get_item(report, 'Pendrive')['childr... | 235 | 235 | 785 | 11 | 224 | angry-tony/cmdb-ralph | src/ralph/reports/tests.py | Python | TestReportAssetAndLicence | TestReportAssetAndLicence | 150 | 238 | 150 | 150 | 31fe214618bd83927b6ddf989f81cc28a3bb4fb5 | bigcode/the-stack | train |
30145ec9369d914c1abf7141 | train | class | class TestReportLanguage(RalphTestCase):
def test_clean_metod(self):
ReportLanguage.objects.create(name='pl', default=True)
lang_2 = ReportLanguage.objects.create(name='en', default=False)
with self.assertRaisesRegex(
ValidationError,
(
'Only one lan... | class TestReportLanguage(RalphTestCase):
| def test_clean_metod(self):
ReportLanguage.objects.create(name='pl', default=True)
lang_2 = ReportLanguage.objects.create(name='en', default=False)
with self.assertRaisesRegex(
ValidationError,
(
'Only one language can be default.'
)
... | _1.id), self.dc_1.asset.barcode,
'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None',
'', '', '', ''
]
]
self.assertEqual(report_result, result)
class TestReportLanguage(RalphTestCase):
| 64 | 64 | 85 | 9 | 55 | angry-tony/cmdb-ralph | src/ralph/reports/tests.py | Python | TestReportLanguage | TestReportLanguage | 241 | 254 | 241 | 242 | 0dbe01217857686694b6e0ae21110d6fa938576e | bigcode/the-stack | train |
c336ce0f862982ad0a26e21c | train | function | def main():
"""
Creates an iGibson environment from a config file with a turtlebot in Rs (not interactive).
It steps the environment 100 times with random actions sampled from the action space,
using the Gym interface, resetting it 10 times.
"""
logging.info("*" * 80 + "\nDescription:" + main.__... | def main():
| """
Creates an iGibson environment from a config file with a turtlebot in Rs (not interactive).
It steps the environment 100 times with random actions sampled from the action space,
using the Gym interface, resetting it 10 times.
"""
logging.info("*" * 80 + "\nDescription:" + main.__doc__ + "*" ... | import logging
import os
from sys import platform
import yaml
import igibson
from igibson.envs.igibson_env import iGibsonEnv
from igibson.render.profiler import Profiler
from igibson.utils.assets_utils import download_assets, download_demo_data
def main():
| 66 | 86 | 289 | 3 | 62 | mamadbiabon/iGibson | igibson/examples/environments/env_nonint_example.py | Python | main | main | 13 | 39 | 13 | 13 | 36802e093ec305328e1054585aad46910db17730 | bigcode/the-stack | train |
e699642162a7e460b58f42fb | train | class | class Migration(migrations.Migration):
dependencies = [
('dvaapp', '0007_auto_20180120_2359'),
]
operations = [
migrations.RemoveField(
model_name='deletedvideo',
name='description',
),
migrations.RemoveField(
model_name='deletedvideo',
... | class Migration(migrations.Migration):
| dependencies = [
('dvaapp', '0007_auto_20180120_2359'),
]
operations = [
migrations.RemoveField(
model_name='deletedvideo',
name='description',
),
migrations.RemoveField(
model_name='deletedvideo',
name='name',
),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-01-29 07:19
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
| 57 | 69 | 230 | 7 | 49 | batermj/DeepVideoAnalytics | server/dvaapp/migrations/0008_auto_20180129_0719.py | Python | Migration | Migration | 9 | 51 | 9 | 10 | c542849ef0f6ddb8b24d7965bf169d7c4847f772 | bigcode/the-stack | train |
5b7d4ded1ecb6824c674de75 | train | function | async def test_assume_device_unavailable(hass: HomeAssistant, fritz: Mock):
"""Test assume device as unavailable."""
device = FritzDeviceSwitchMock()
device.voltage = 0
device.energy = 0
device.power = 0
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTI... | async def test_assume_device_unavailable(hass: HomeAssistant, fritz: Mock):
| """Test assume device as unavailable."""
device = FritzDeviceSwitchMock()
device.voltage = 0
device.energy = 0
device.power = 0
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
state = hass.states.get(ENTITY_ID)
asser... | async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
assert fritz().update_devices.call_count == 2
assert fritz().login.call_count == 2
async def test_assume_device_unavailable(hass: HomeAssistant, fritz: Mock):
| 64 | 64 | 112 | 19 | 44 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_assume_device_unavailable | test_assume_device_unavailable | 137 | 149 | 137 | 137 | f7aac20c02e594bfb3a965e6afa94866a33d2970 | bigcode/the-stack | train |
06206903a04c047f01cc2941 | train | function | async def test_turn_on(hass: HomeAssistant, fritz: Mock):
"""Test turn device on."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_TUR... | async def test_turn_on(hass: HomeAssistant, fritz: Mock):
| """Test turn device on."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, True
)
assert d... | _FAKE_NAME} Total Energy"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == ENERGY_KILO_WATT_HOUR
assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.TOTAL_INCREASING
async def test_turn_on(hass: HomeAssistant, fritz: Mock):
| 64 | 64 | 104 | 16 | 47 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_turn_on | test_turn_on | 76 | 86 | 76 | 76 | e67842d77f212493a85e0dc379305425a44e2483 | bigcode/the-stack | train |
95d007cd8306760e889217b1 | train | function | async def test_setup(hass: HomeAssistant, fritz: Mock):
"""Test setup of platform."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
state = hass.states.get(ENTITY_ID)
assert state
assert st... | async def test_setup(hass: HomeAssistant, fritz: Mock):
| """Test setup of platform."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
state = hass.states.get(ENTITY_ID)
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_F... | ICES,
ENERGY_KILO_WATT_HOUR,
POWER_WATT,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_UNAVAILABLE,
TEMP_CELSIUS,
)
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util
from . import FritzDeviceSwitchMock, setup_config_entry
from .const import CONF_FAKE_... | 122 | 123 | 410 | 15 | 107 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_setup | test_setup | 38 | 73 | 38 | 38 | 311d20c9c485cbc64b25cc50c76639f2fa0c24ac | bigcode/the-stack | train |
92dcfd520860bf0e364b8d60 | train | function | async def test_update_error(hass: HomeAssistant, fritz: Mock):
"""Test update with error."""
device = FritzDeviceSwitchMock()
fritz().update_devices.side_effect = HTTPError("Boom")
assert not await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
... | async def test_update_error(hass: HomeAssistant, fritz: Mock):
| """Test update with error."""
device = FritzDeviceSwitchMock()
fritz().update_devices.side_effect = HTTPError("Boom")
assert not await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert fritz().update_devices.call_count == 1
assert fr... | =200)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
assert fritz().update_devices.call_count == 2
assert fritz().login.call_count == 1
async def test_update_error(hass: HomeAssistant, fritz: Mock):
| 64 | 64 | 162 | 16 | 47 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_update_error | test_update_error | 119 | 134 | 119 | 119 | a900b48f454a85166fca20808f73f0cb31a1514e | bigcode/the-stack | train |
c51bf4231062de543cadbe45 | train | function | async def test_turn_off(hass: HomeAssistant, fritz: Mock):
"""Test turn device off."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_T... | async def test_turn_off(hass: HomeAssistant, fritz: Mock):
| """Test turn device off."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, True
)
assert... | device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, True
)
assert device.set_switch_state_on.call_count == 1
async def test_turn_off(hass: HomeAssistant, fritz: Mock):
| 64 | 64 | 104 | 16 | 47 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_turn_off | test_turn_off | 89 | 99 | 89 | 89 | 2e71b87424340b37628c6f8393d6fea9d558ad95 | bigcode/the-stack | train |
9ccadadaf5163c64b9e09405 | train | function | async def test_update(hass: HomeAssistant, fritz: Mock):
"""Test update without error."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert fritz().update_devices.call_count == 1
assert fritz... | async def test_update(hass: HomeAssistant, fritz: Mock):
| """Test update without error."""
device = FritzDeviceSwitchMock()
assert await setup_config_entry(
hass, MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz
)
assert fritz().update_devices.call_count == 1
assert fritz().login.call_count == 1
next_update = dt_util.utcno... | , device, fritz
)
assert await hass.services.async_call(
DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, True
)
assert device.set_switch_state_off.call_count == 1
async def test_update(hass: HomeAssistant, fritz: Mock):
| 64 | 64 | 146 | 15 | 48 | andersop91/core | tests/components/fritzbox/test_switch.py | Python | test_update | test_update | 102 | 116 | 102 | 102 | 90b5dd63343c4878f5e5ccda51d2003c1b03413e | bigcode/the-stack | train |
b73574e801e068d227957dda | train | class | class IsHotel(BasePermission):
def has_permission(self, request, view):
return request.user.is_hotelier | class IsHotel(BasePermission):
| def has_permission(self, request, view):
return request.user.is_hotelier | from rest_framework.permissions import BasePermission
class IsHotel(BasePermission):
| 15 | 64 | 25 | 7 | 7 | rossi1/RES | real_estate_api/hotel/permission.py | Python | IsHotel | IsHotel | 3 | 6 | 3 | 4 | 9c654689dd7151c8ea5444d6367917da46d7df77 | bigcode/the-stack | train |
db0cd23de70fcf8f8ceb71a5 | train | class | class ExpandedSiameseMerge(Layer):
def __init__(self, name, inputs, targets, tower_setup, merge_type):
super(ExpandedSiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
size = smart_shape(curr)[0]
def Expand(idx):
anchor = curr[idx, :]
anchor_class = targets[idx]
... | class ExpandedSiameseMerge(Layer):
| def __init__(self, name, inputs, targets, tower_setup, merge_type):
super(ExpandedSiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
size = smart_shape(curr)[0]
def Expand(idx):
anchor = curr[idx, :]
anchor_class = targets[idx]
classes,classes_ids = tf.uniqu... | import tensorflow as tf
import numpy
from datasets.Util.Util import smart_shape
from .NetworkLayers import Layer
from .Util_Network import prepare_input
class SiameseMerge(Layer):
def __init__(self, name, inputs, tower_setup, merge_type):
super(SiameseMerge, self).__init__()
curr, n_features_inp = prepare_... | 247 | 256 | 909 | 9 | 238 | GeniusGaryant/PReMVOS | code/ReID_net/network/NetworkSiameseLayers.py | Python | ExpandedSiameseMerge | ExpandedSiameseMerge | 32 | 118 | 32 | 32 | 8c684e5b999bcd4e21033b33fea2d855533b1c14 | bigcode/the-stack | train |
cbb79d861056e0f4546bfbad | train | class | class SiameseMerge(Layer):
def __init__(self, name, inputs, tower_setup, merge_type):
super(SiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
if merge_type == "concat":
out = tf.reshape(curr, [-1, n_features_inp * 2])
elif merge_type == "add":
part1 = curr[::2, :]... | class SiameseMerge(Layer):
| def __init__(self, name, inputs, tower_setup, merge_type):
super(SiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
if merge_type == "concat":
out = tf.reshape(curr, [-1, n_features_inp * 2])
elif merge_type == "add":
part1 = curr[::2, :]
part2 = curr[1::2, :... | import tensorflow as tf
import numpy
from datasets.Util.Util import smart_shape
from .NetworkLayers import Layer
from .Util_Network import prepare_input
class SiameseMerge(Layer):
| 39 | 64 | 206 | 7 | 31 | GeniusGaryant/PReMVOS | code/ReID_net/network/NetworkSiameseLayers.py | Python | SiameseMerge | SiameseMerge | 9 | 29 | 9 | 9 | 76aab39e49cf7e22267dca24f0e21d8180f0695d | bigcode/the-stack | train |
895d8f8e4ea7ee93c9d76269 | train | class | class CompleteSiameseMerge(Layer):
def __init__(self, name, inputs, targets, tower_setup, merge_type):
super(CompleteSiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
batch_size = smart_shape(curr)[0]
curr1 = curr[:,tf.newaxis,:]
curr2 = curr[tf.newaxis,:,:]
if merg... | class CompleteSiameseMerge(Layer):
| def __init__(self, name, inputs, targets, tower_setup, merge_type):
super(CompleteSiameseMerge, self).__init__()
curr, n_features_inp = prepare_input(inputs)
batch_size = smart_shape(curr)[0]
curr1 = curr[:,tf.newaxis,:]
curr2 = curr[tf.newaxis,:,:]
if merge_type == "concat":
# curr1_b... | 2, :]
expanded = part1 - part2
elif merge_type == "abs_subtract":
part1 = expanded[::2, :]
part2 = expanded[1::2, :]
expanded = tf.abs(part1 - part2)
else:
expanded = expanded
new_targets = tf.reshape(new_targets, [-1])
debug = 0
if debug:
# Print - debug exampl... | 173 | 173 | 579 | 9 | 163 | GeniusGaryant/PReMVOS | code/ReID_net/network/NetworkSiameseLayers.py | Python | CompleteSiameseMerge | CompleteSiameseMerge | 121 | 176 | 121 | 121 | fb0a5072cdeb36fc8808c0db48bace2d8c9bfd65 | bigcode/the-stack | train |
ba5fcdd5232d6762f1b3df61 | train | class | class StreamMe(Plugin):
_url_re = re.compile(r'^https?://(?:www\.)?stream\.me/(\w+).*$')
_streams_schema = validate.Schema(validate.all(
validate.transform(parse_json),
validate.any(
validate.all({
'_embedded': {
'streams': [{
... | class StreamMe(Plugin):
| _url_re = re.compile(r'^https?://(?:www\.)?stream\.me/(\w+).*$')
_streams_schema = validate.Schema(validate.all(
validate.transform(parse_json),
validate.any(
validate.all({
'_embedded': {
'streams': [{
'manifest': validate... | import logging
import re
from streamlink.exceptions import PluginError
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.plugin.api.utils import parse_json
from streamlink.stream import HLSStream
log = logging.getLogger(__name__)
class StreamMe(Plugin):
| 62 | 211 | 705 | 6 | 56 | sn4kebite/streamlink | src/streamlink/plugins/streamme.py | Python | StreamMe | StreamMe | 13 | 120 | 13 | 13 | 1173150c363605d5ce84ac5950ce54c6987fabdd | bigcode/the-stack | train |
12804e67a37d70770a43ee50 | train | class | class Query:
def __init__(self, endpoint, params, user=None, rcfile=None, times=1):
self.endpoint = endpoint
self.params = params
self.api = T.TwitterAPI(*keys.keys(user, rcfile))
self.times = times
self.stop, self.cursor, self.response = self.get_first()
def get_first()... | class Query:
| def __init__(self, endpoint, params, user=None, rcfile=None, times=1):
self.endpoint = endpoint
self.params = params
self.api = T.TwitterAPI(*keys.keys(user, rcfile))
self.times = times
self.stop, self.cursor, self.response = self.get_first()
def get_first():
r =... | #!/usr/bin/python3
# standard modules
import sys
import os
import time
# logging
import logging as L
L.basicConfig(
format='%(levelname)s: %(message)s')
# TODO
if os.environ.get('DEBUG', False):
L.getLogger().setLevel(L.INFO)
# TwitterAPI
sys.path.insert(0, '../TwitterAPI')
import TwitterAPI as T
# my modul... | 105 | 151 | 505 | 3 | 102 | shuravban/tvit | tvit/query.py | Python | Query | Query | 25 | 89 | 25 | 25 | c936e1376d19c760f5943e2e1818dad7be7d61a9 | bigcode/the-stack | train |
f44f3aa6895f743594ab2b6b | train | class | class Ahp:
@property
def goal(self):
return self._goal
@property
def criteria_table(self):
return tuple(self._criteria)
@property
def criteria_hash(self):
return dict(self._criteriaHash)
@property
def criteria_descriptions(self):
"""
:return: S... | class Ahp:
@property
| def goal(self):
return self._goal
@property
def criteria_table(self):
return tuple(self._criteria)
@property
def criteria_hash(self):
return dict(self._criteriaHash)
@property
def criteria_descriptions(self):
"""
:return: Sorted list of criteria des... | # coding: UTF-8
"""
Definition of class Ahp
"""
import sys
from yeahp.criterion import Criterion
from yeahp.alternative import Alternative
from yeahp.judgement import Judgement
class Ahp:
@property
| 52 | 256 | 1,356 | 8 | 43 | flaudanum/Yet-another-AHP | yeahp-backend/yeahp/ahp.py | Python | Ahp | Ahp | 13 | 203 | 13 | 15 | 64dcdf75927599dbb4e61f2ad83fa52011b955f2 | bigcode/the-stack | train |
01336362c872bcb33a47aab7 | train | class | class XanitizerXMLParser(object):
def __init__(self, filename, test):
self.items = []
if filename is None:
return
root = self.parse_xml(filename)
if root is not None:
self.items = self.get_findings(root, test)
def parse_xml(self, filename):
tr... | class XanitizerXMLParser(object):
| def __init__(self, filename, test):
self.items = []
if filename is None:
return
root = self.parse_xml(filename)
if root is not None:
self.items = self.get_findings(root, test)
def parse_xml(self, filename):
try:
tree = ET.parse(file... | __author__ = 'jankuehl'
import re
from defusedxml import ElementTree as ET
from dojo.models import Finding
class XanitizerXMLParser(object):
| 37 | 256 | 1,374 | 8 | 28 | everable/django-DefectDojo | dojo/tools/xanitizer/parser.py | Python | XanitizerXMLParser | XanitizerXMLParser | 8 | 185 | 8 | 9 | 8dddb9a94c836ac3de5805a23f1209fd95688b8e | bigcode/the-stack | train |
1f765870919dfb1c9b5982b8 | train | class | class ELBResponse(BaseResponse):
@property
def elb_backend(self):
return elb_backends[self.region]
def create_load_balancer(self):
load_balancer_name = self._get_param("LoadBalancerName")
availability_zones = self._get_multi_param("AvailabilityZones.member")
ports = self._ge... | class ELBResponse(BaseResponse):
@property
| def elb_backend(self):
return elb_backends[self.region]
def create_load_balancer(self):
load_balancer_name = self._get_param("LoadBalancerName")
availability_zones = self._get_multi_param("AvailabilityZones.member")
ports = self._get_list_prefix("Listeners.member")
schem... | from __future__ import unicode_literals
from boto.ec2.elb.attributes import (
ConnectionSettingAttribute,
ConnectionDrainingAttribute,
AccessLogAttribute,
CrossZoneLoadBalancingAttribute,
)
from boto.ec2.elb.policies import AppCookieStickinessPolicy, OtherPolicy
from moto.core.responses import BaseResp... | 103 | 256 | 3,049 | 11 | 91 | jonnangle/moto-1 | moto/elb/responses.py | Python | ELBResponse | ELBResponse | 15 | 370 | 15 | 16 | 48fb60da96ab453c3d334bfd277e143ca5d094d1 | bigcode/the-stack | train |
d58e0baf6fcb9009e518e126 | train | class | @module
class GeneratorOptions:
@generator
def generator_a(mod):
hw.ConstantOp.create(types.i32, 1)
@generator
def generator_b(mod):
hw.ConstantOp.create(types.i32, 2)
| @module
class GeneratorOptions:
@generator
| def generator_a(mod):
hw.ConstantOp.create(types.i32, 1)
@generator
def generator_b(mod):
hw.ConstantOp.create(types.i32, 2)
| # RUN: %PYTHON% %s | FileCheck %s
from pycde import System, module, generator, types
from circt.dialects import hw
@module
class GeneratorOptions:
@generator
| 48 | 64 | 51 | 11 | 36 | Mechachleopteryx/circt | frontends/PyCDE/test/generator_options.py | Python | GeneratorOptions | GeneratorOptions | 8 | 17 | 8 | 11 | 5d8dd9cdb3727eaed034c0113ea901973855b3af | bigcode/the-stack | train |
32bfe521b4ca85506b306ea6 | train | function | def expand_options(parentheses_line: str) -> list:
"""
Convert 'test (a|b)' -> ['test a', 'test b']
Args:
parentheses_line: Input line to expand
Returns:
List of expanded possibilities
"""
# 'a(this|that)b' -> [['a', 'this', 'b'], ['a', 'that', 'b']]
options = expand_parenthe... | def expand_options(parentheses_line: str) -> list:
| """
Convert 'test (a|b)' -> ['test a', 'test b']
Args:
parentheses_line: Input line to expand
Returns:
List of expanded possibilities
"""
# 'a(this|that)b' -> [['a', 'this', 'b'], ['a', 'that', 'b']]
options = expand_parentheses(re.split(r'([(|)])', parentheses_line))
ret... | ?
Will it pour?
Args:
sent (list<str>): List of tokens in sentence
Returns:
list<list<str>>: Multiple possible sentences from original
"""
return SentenceTreeParser(sent).expand_parentheses()
def expand_options(parentheses_line: str) -> list:
| 64 | 64 | 123 | 12 | 52 | bartdw/lingua-franca | lingua_franca/format.py | Python | expand_options | expand_options | 513 | 523 | 513 | 513 | f33233730ed2757f155a843a28be7c05e3db5bb5 | bigcode/the-stack | train |
4ceff295bbf32fba7cde2ffb | train | function | @localized_function()
def pronounce_number(number, lang='', places=2, short_scale=True,
scientific=False, ordinals=False):
"""
Convert a number to it's spoken equivalent
For example, '5' would be 'five'
Args:
number: the number to pronounce
short_scale (bool) : use... | @localized_function()
def pronounce_number(number, lang='', places=2, short_scale=True,
scientific=False, ordinals=False):
| """
Convert a number to it's spoken equivalent
For example, '5' would be 'five'
Args:
number: the number to pronounce
short_scale (bool) : use short (True) or long scale (False)
https://en.wikipedia.org/wiki/Names_of_large_numbers
scientific (bool) : convert and pro... | 12-hour format
use_ampm (bool): include the am/pm for 12-hour format
Returns:
(str): The formatted time string
"""
@localized_function()
def pronounce_number(number, lang='', places=2, short_scale=True,
scientific=False, ordinals=False):
| 63 | 64 | 136 | 27 | 36 | bartdw/lingua-franca | lingua_franca/format.py | Python | pronounce_number | pronounce_number | 282 | 298 | 282 | 284 | 8b18379eda769da55498f06c04ce745d91ec42db | bigcode/the-stack | train |
bb7c88b452bf3bbec8267a12 | train | function | def join_list(items, connector, sep=None, lang=''):
""" Join a list into a phrase using the given connector word
Examples:
join_list([1,2,3], "and") -> "1, 2 and 3"
join_list([1,2,3], "and", ";") -> "1; 2 and 3"
Args:
items(array): items to be joined
connector(str): conne... | def join_list(items, connector, sep=None, lang=''):
| """ Join a list into a phrase using the given connector word
Examples:
join_list([1,2,3], "and") -> "1, 2 and 3"
join_list([1,2,3], "and", ";") -> "1; 2 and 3"
Args:
items(array): items to be joined
connector(str): connecting word (resource name), like "and" or "or"
... | 10 and (hours > 0 or days > 0):
out += "0"
out += str(minutes)+":"
if seconds < 10:
out += "0"
out += str(seconds)
return out
def join_list(items, connector, sep=None, lang=''):
| 64 | 64 | 215 | 13 | 50 | bartdw/lingua-franca | lingua_franca/format.py | Python | join_list | join_list | 464 | 490 | 464 | 464 | 4980653142523a97a76596087f9d20715148db52 | bigcode/the-stack | train |
7919ac00bab4c78113dd4685 | train | class | class DateTimeFormat:
def __init__(self, config_path):
self.lang_config = {}
self.config_path = config_path
def cache(self, lang):
if lang not in self.lang_config:
try:
# Attempt to load the language-specific formatting data
with open(self.con... | class DateTimeFormat:
| def __init__(self, config_path):
self.lang_config = {}
self.config_path = config_path
def cache(self, lang):
if lang not in self.lang_config:
try:
# Attempt to load the language-specific formatting data
with open(self.config_path + '/' + lang ... | lang (str): Language code, e.g. "en-us"
Returns:
str: translated version of resource name
"""
from lingua_franca.internal import resolve_resource_file
if not lang:
if lang is None:
warn(NoneLangWarning)
lang = get_default_loc()
lang_code = lang if is_sup... | 255 | 256 | 1,802 | 5 | 250 | bartdw/lingua-franca | lingua_franca/format.py | Python | DateTimeFormat | DateTimeFormat | 84 | 238 | 84 | 84 | 1c1c27fba948da6916e0cf76138a2200c3104b95 | bigcode/the-stack | train |
59ce6474971770b65d9f477f | train | function | @localized_function()
def nice_time(dt, lang='', speech=True, use_24hour=False,
use_ampm=False):
"""
Format a time to a comfortable human format
For example, generate 'five thirty' for speech or '5:30' for
text display.
Args:
dt (datetime): date to format (assumes already in ... | @localized_function()
def nice_time(dt, lang='', speech=True, use_24hour=False,
use_ampm=False):
| """
Format a time to a comfortable human format
For example, generate 'five thirty' for speech or '5:30' for
text display.
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (str): code for the language to use
speech (bool): format for speech (defa... | denominators (iter of ints): denominators to use, default [1 .. 20]
Returns:
(str): The formatted string.
"""
return str(number)
@localized_function()
def nice_time(dt, lang='', speech=True, use_24hour=False,
use_ampm=False):
| 64 | 64 | 163 | 26 | 38 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_time | nice_time | 262 | 279 | 262 | 264 | 20e77ca10f0b1715a9d601943b4c9c4fe01b39b9 | bigcode/the-stack | train |
c2bab66de1153d7d9736b8c0 | train | function | def expand_parentheses(sent):
"""
['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']]
For example:
Will it (rain|pour) (today|tomorrow|)?
---->
Will it rain today?
Will it rain tomorrow?
Will it rain?
Will it pour today?
Will it pour tomorrow?
Will it pour?
Args:
... | def expand_parentheses(sent):
| """
['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']]
For example:
Will it (rain|pour) (today|tomorrow|)?
---->
Will it rain today?
Will it rain tomorrow?
Will it rain?
Will it pour today?
Will it pour tomorrow?
Will it pour?
Args:
sent (list<str>): List o... | [0])
if not sep:
sep = ", "
else:
sep += " "
return (sep.join(str(item) for item in items[:-1]) +
" " + _translate_word(connector, lang) +
" " + items[-1])
def expand_parentheses(sent):
| 64 | 64 | 139 | 6 | 58 | bartdw/lingua-franca | lingua_franca/format.py | Python | expand_parentheses | expand_parentheses | 493 | 510 | 493 | 493 | e71ed009bb5f6023edd869bca2318273a0507a90 | bigcode/the-stack | train |
9ffd1329f14c9852f8bb48ee | train | function | def nice_date(dt, lang='', now=None):
"""
Format a datetime to a pronounceable date
For example, generates 'tuesday, june the fifth, 2018'
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use Mycroft default language if not
... | def nice_date(dt, lang='', now=None):
| """
Format a datetime to a pronounceable date
For example, generates 'tuesday, june the fifth, 2018'
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use Mycroft default language if not
provided
now (datetime... | .wikipedia.org/wiki/Names_of_large_numbers
scientific (bool) : convert and pronounce in scientific notation
ordinals (bool): pronounce in ordinal form "first" instead of "one"
Returns:
(str): The pronounced number
"""
def nice_date(dt, lang='', now=None):
| 63 | 64 | 195 | 10 | 53 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_date | nice_date | 301 | 320 | 301 | 301 | e798b32f5869fba720f169d87c8b2c0d11b95dd2 | bigcode/the-stack | train |
4da369cdcbb59407423e5de7 | train | function | def nice_year(dt, lang='', bc=False):
"""
Format a datetime to a pronounceable year
For example, generate 'nineteen-hundred and eighty-four' for year 1984
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use... | def nice_year(dt, lang='', bc=False):
| """
Format a datetime to a pronounceable year
For example, generate 'nineteen-hundred and eighty-four' for year 1984
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use Mycroft default language if
... | (str): The formatted date time string
"""
full_code = get_full_lang_code(lang)
date_time_format.cache(full_code)
return date_time_format.date_time_format(dt, full_code, now, use_24hour,
use_ampm)
def nice_year(dt, lang='', bc=False):
| 64 | 64 | 155 | 10 | 54 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_year | nice_year | 352 | 371 | 352 | 352 | e56608260d2d9d8c085c771ca65191bc422b8c79 | bigcode/the-stack | train |
341392eaf426c8c63d879f67 | train | function | @localized_function(run_own_code_on=[UnsupportedLanguageError])
def nice_number(number, lang='', speech=True, denominators=None):
"""Format a float to human readable functions
This function formats a float to human understandable functions. Like
4.5 becomes 4 and a half for speech and 4 1/2 for text
Ar... | @localized_function(run_own_code_on=[UnsupportedLanguageError])
def nice_number(number, lang='', speech=True, denominators=None):
| """Format a float to human readable functions
This function formats a float to human understandable functions. Like
4.5 becomes 4 and a half for speech and 4 1/2 for text
Args:
number (int or float): the float to format
lang (str): code for the language to use
speech (bool): for... | ousand=formatted_thousand,
bc=formatted_bc)).strip()
date_time_format = DateTimeFormat(os.path.join(os.path.dirname(__file__),
'res/text'))
@localized_function(run_own_code_on=[UnsupportedLanguageError])
def nice_number(number, lang='', speech=T... | 63 | 64 | 154 | 27 | 36 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_number | nice_number | 245 | 259 | 245 | 246 | cdebc47e5a34527b4170a1925f36a8566e8e1f66 | bigcode/the-stack | train |
886d2f7d5a495db87d3d02d1 | train | function | def nice_date_time(dt, lang='', now=None, use_24hour=False,
use_ampm=False):
"""
Format a datetime to a pronounceable date and time
For example, generate 'tuesday, june the fifth, 2018 at five thirty'
Args:
dt (datetime): date to format (assumes already in lo... | def nice_date_time(dt, lang='', now=None, use_24hour=False,
use_ampm=False):
| """
Format a datetime to a pronounceable date and time
For example, generate 'tuesday, june the fifth, 2018 at five thirty'
Args:
dt (datetime): date to format (assumes already in local timezone)
lang (string): the language to use, use Mycroft default language if
... | the same day, 'today' is returned.
Returns:
(str): The formatted date string
"""
full_code = get_full_lang_code(lang)
date_time_format.cache(full_code)
return date_time_format.date_format(dt, full_code, now)
def nice_date_time(dt, lang='', now=None, use_24hour=False,
use... | 79 | 79 | 265 | 23 | 56 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_date_time | nice_date_time | 323 | 349 | 323 | 324 | 634b5255964f88b8e05c181dc12007036b9e3381 | bigcode/the-stack | train |
3ecd23fe4e0bf5d4cd04c1c1 | train | function | @localized_function()
def nice_response(text, lang=''):
"""
In some languages, sanitizes certain numeric input for TTS
Most of the time, this function will be called by any formatters
which might need it. It's exposed here just in case you've got a clever
use.
As of July 2020, this function sa... | @localized_function()
def nice_response(text, lang=''):
| """
In some languages, sanitizes certain numeric input for TTS
Most of the time, this function will be called by any formatters
which might need it. It's exposed here just in case you've got a clever
use.
As of July 2020, this function sanitizes some dates and "x ^ y"-formatted
exponents i... | 'b'], ['a', 'that', 'b']]
options = expand_parentheses(re.split(r'([(|)])', parentheses_line))
return [re.sub(r'\s+', ' ', ' '.join(i)).strip() for i in options]
@localized_function()
def nice_response(text, lang=''):
| 64 | 64 | 156 | 12 | 52 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_response | nice_response | 526 | 545 | 526 | 527 | b9ed193be3905a40ae3b6dfce578587ff1b4608c | bigcode/the-stack | train |
941aa0fd095d9df0f79c91bd | train | function | @localized_function(run_own_code_on=[FunctionNotLocalizedError])
def nice_duration(duration, lang='', speech=True):
""" Convert duration in seconds to a nice spoken timespan
Examples:
duration = 60 -> "1:00" or "one minute"
duration = 163 -> "2:43" or "two minutes forty three seconds"
Ar... | @localized_function(run_own_code_on=[FunctionNotLocalizedError])
def nice_duration(duration, lang='', speech=True):
| """ Convert duration in seconds to a nice spoken timespan
Examples:
duration = 60 -> "1:00" or "one minute"
duration = 163 -> "2:43" or "two minutes forty three seconds"
Args:
duration: time, in seconds
lang (str, optional): a BCP-47 language code, None for default
... | (lang)
date_time_format.cache(full_code)
return date_time_format.date_time_format(dt, full_code, now, use_24hour,
use_ampm)
def nice_year(dt, lang='', bc=False):
"""
Format a datetime to a pronounceable year
For example, generate 'nineteen-hun... | 214 | 214 | 714 | 24 | 190 | bartdw/lingua-franca | lingua_franca/format.py | Python | nice_duration | nice_duration | 374 | 461 | 374 | 375 | 0b084e8af0daed28c636d65677c508b5aa922b5a | bigcode/the-stack | train |
e0de26beb621d09c02765ea7 | train | function | def _translate_word(name, lang=''):
""" Helper to get word translations
Args:
name (str): Word name. Returned as the default value if not translated
lang (str): Language code, e.g. "en-us"
Returns:
str: translated version of resource name
"""
from lingua_franca.internal imp... | def _translate_word(name, lang=''):
| """ Helper to get word translations
Args:
name (str): Word name. Returned as the default value if not translated
lang (str): Language code, e.g. "en-us"
Returns:
str: translated version of resource name
"""
from lingua_franca.internal import resolve_resource_file
if not... | , InvalidLangWarning, \
FunctionNotLocalizedError
_REGISTERED_FUNCTIONS = ("nice_number",
"nice_time",
"pronounce_number",
"nice_response",
"nice_duration")
populate_localized_function_dict("format", langs=get_act... | 65 | 65 | 217 | 9 | 56 | bartdw/lingua-franca | lingua_franca/format.py | Python | _translate_word | _translate_word | 44 | 75 | 44 | 44 | 78e3562a95d610d75101adbd04e4012b74c1c590 | bigcode/the-stack | train |
82c6c98fdea48ef3c6a74fc1 | train | class | class CustomAttributeData: pass | class CustomAttributeData: | pass | class CustomAttributeData: | 6 | 64 | 6 | 6 | 0 | 56kyle/bloons_auto | btd6_memory_info/generated/System/Reflection/CustomAttributeData/custom_attribute_data.py | Python | CustomAttributeData | CustomAttributeData | 1 | 1 | 1 | 1 | 22d62b9bb66ad4b7ab918b30ec07c2be404f55b6 | bigcode/the-stack | train |
7ed40d21cb2b581c843d8608 | train | function | def u2i(uint32):
"""
Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
...
"""
mask = (2 ** 32) - 1
if uint32 & (1 << 31):
v = uint32 | ~mask
else:
v = uint32 & mask
r... | def u2i(uint32):
| """
Converts a 32 bit unsigned number to signed.
uint32:= an unsigned 32 bit number
...
print(u2i(4294967272))
-24
print(u2i(37))
37
...
"""
mask = (2 ** 32) - 1
if uint32 & (1 << 31):
v = uint32 | ~mask
else:
v = uint32 & mask
return v
| pio error.
errnum:= <0, the error number
...
print(pigpio.error_text(-5))
level not 0-1
...
"""
return _errors.get(errnum) or "unknown error ({})".format(errnum)
def u2i(uint32):
| 64 | 64 | 112 | 7 | 57 | nowls/apigpio | apigpio/apigpio.py | Python | u2i | u2i | 294 | 312 | 294 | 294 | c0182936fd151b239b05bec47e2840276326e24b | bigcode/the-stack | train |
0b9db98f6d3e05677228c3df | train | class | class _callback_handler(object):
"""
A class to handle callbacks.
Each instance of this class open it's own connection to gpiod, which is
only used to listen for notifications.
"""
def __init__(self, pi):
self._loop = pi._loop
self.pi = pi
self.handle = None
self... | class _callback_handler(object):
| """
A class to handle callbacks.
Each instance of this class open it's own connection to gpiod, which is
only used to listen for notifications.
"""
def __init__(self, pi):
self._loop = pi._loop
self.pi = pi
self.handle = None
self.monitor = 0
self.callbac... | a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is True.
"""
v = u2i(uint32)
if v < 0:
if exceptions:
raise ApigpioError(error_text(v))
return v
class _callback_ADT:
"""An A... | 256 | 256 | 924 | 6 | 249 | nowls/apigpio | apigpio/apigpio.py | Python | _callback_handler | _callback_handler | 355 | 463 | 355 | 355 | fa4ead89e0d13b4cbc8f9c0b971a72e5eb9ce5b3 | bigcode/the-stack | train |
1ae88e68988d681ff99b50d5 | train | class | class _callback_ADT:
"""An ADT class to hold callback information."""
def __init__(self, gpio, edge, func):
"""
Initialises a callback ADT.
gpio:= Broadcom gpio number.
edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
func:= a user function taking three arguments (gpio... | class _callback_ADT:
| """An ADT class to hold callback information."""
def __init__(self, gpio, edge, func):
"""
Initialises a callback ADT.
gpio:= Broadcom gpio number.
edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
func:= a user function taking three arguments (gpio, level, tick).
... | it indicates an error. On error a pigpio
exception will be raised if exceptions is True.
"""
v = u2i(uint32)
if v < 0:
if exceptions:
raise ApigpioError(error_text(v))
return v
class _callback_ADT:
| 64 | 64 | 175 | 6 | 57 | nowls/apigpio | apigpio/apigpio.py | Python | _callback_ADT | _callback_ADT | 328 | 352 | 328 | 328 | 659da0f50b687f6cca724b6d33a632249e6b7a44 | bigcode/the-stack | train |
950dadb55dd9786845f63b75 | train | class | class Pulse:
"""
A class to store pulse information.
"""
def __init__(self, gpio_on, gpio_off, delay):
"""
Initialises a pulse.
gpio_on:= the GPIO to switch on at the start of the pulse.
gpio_off:= the GPIO to switch off at the start of the pulse.
delay:= the delay in mic... | class Pulse:
| """
A class to store pulse information.
"""
def __init__(self, gpio_on, gpio_off, delay):
"""
Initialises a pulse.
gpio_on:= the GPIO to switch on at the start of the pulse.
gpio_off:= the GPIO to switch off at the start of the pulse.
delay:= the delay in microseconds bef... | PI_BAD_SER_INVERT: "bit bang serial invert not 0 or 1"
}
class ApigpioError(Exception):
"""pigpio module exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Pulse:
| 64 | 64 | 109 | 3 | 61 | nowls/apigpio | apigpio/apigpio.py | Python | Pulse | Pulse | 263 | 279 | 263 | 263 | cb1f610d4ed691ad3a2f9e977f7cda90f2de3fe5 | bigcode/the-stack | train |
f3e36640c2248848037a0477 | train | class | class Pi(object):
async def _pigpio_aio_command(self, cmd, p1, p2,):
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
... | class Pi(object):
| async def _pigpio_aio_command(self, cmd, p1, p2,):
"""
Runs a pigpio socket command.
sl:= command socket and lock.
cmd:= the command to be executed.
p1:= command parameter 1 (if applicable).
p2:= command parameter 2 (if applicable).
"""
async with ... | , data)
response = await self._loop.sock_recv(self.s, 16)
_, res = struct.unpack('12sI', response)
return res
class Callback:
"""A class to provide gpio level change callbacks."""
def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None):
"""
Initialise a callb... | 256 | 256 | 12,904 | 5 | 250 | nowls/apigpio | apigpio/apigpio.py | Python | Pi | Pi | 498 | 2,003 | 498 | 499 | 75cb1335bce550e71d42b5e49b0065d558bee243 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.