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
940412099de2fe6ee3b3e85b
train
function
@pytest.mark.parametrize( ('genesis_slot', 'genesis_epoch', 'slots_per_epoch', 'min_attestation_inclusion_delay'), [ (8, 2, 4, 2), ] ) @pytest.mark.parametrize( ( 'attestation_slot,' 'state_slot,' 'is_valid,' ), [ # in bounds at lower end (8, 2 + 8...
@pytest.mark.parametrize( ('genesis_slot', 'genesis_epoch', 'slots_per_epoch', 'min_attestation_inclusion_delay'), [ (8, 2, 4, 2), ] ) @pytest.mark.parametrize( ( 'attestation_slot,' 'state_slot,' 'is_valid,' ), [ # in bounds at lower end (8, 2 + 8...
attestation_data = AttestationData(**sample_attestation_data_params).copy( slot=attestation_slot, ) if is_valid: validate_attestation_slot( attestation_data, state_slot, slots_per_epoch, min_attestation_inclusion_delay, genesis_slo...
@pytest.mark.parametrize( ('genesis_slot', 'genesis_epoch', 'slots_per_epoch', 'min_attestation_inclusion_delay'), [ (8, 2, 4, 2), ] ) @pytest.mark.parametrize( ( 'attestation_slot,' 'state_slot,' 'is_valid,' ), [ # in bounds at lower end (8, 2 + 8...
243
105
353
243
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_slot
test_validate_attestation_slot
33
86
33
65
2bc06473f9e3e24cef34cb8d374dac3f9a956b87
bigcode/the-stack
train
e02e6c6f4410f92fef843634
train
function
@pytest.mark.parametrize( ( 'attestation_crosslink_data_root,' 'is_valid,' ), [ (ZERO_HASH32, True), (b'\x22' * 32, False), (b'\x11' * 32, False), ] ) def test_validate_attestation_crosslink_data_root(sample_attestation_data_params, ...
@pytest.mark.parametrize( ( 'attestation_crosslink_data_root,' 'is_valid,' ), [ (ZERO_HASH32, True), (b'\x22' * 32, False), (b'\x11' * 32, False), ] ) def test_validate_attestation_crosslink_data_root(sample_attestation_data_params, ...
attestation_data = AttestationData(**sample_attestation_data_params).copy( crosslink_data_root=attestation_crosslink_data_root, ) if is_valid: validate_attestation_crosslink_data_root( attestation_data, ) else: with pytest.raises(ValidationError): ...
@pytest.mark.parametrize( ( 'attestation_crosslink_data_root,' 'is_valid,' ), [ (ZERO_HASH32, True), (b'\x22' * 32, False), (b'\x11' * 32, False), ] ) def test_validate_attestation_crosslink_data_root(sample_attestation_data_params, ...
90
64
170
90
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_crosslink_data_root
test_validate_attestation_crosslink_data_root
241
267
241
254
5527b6779c5404370918c927519fd1ef91919121
bigcode/the-stack
train
ba192adaf1ecdceae0e17966
train
function
@pytest.mark.parametrize( ( 'attestation_latest_crosslink,' 'attestation_crosslink_data_root,' 'state_latest_crosslink,' 'is_valid,' ), [ ( CrosslinkRecord(0, b'\x11' * 32), b'\x33' * 32, CrosslinkRecord(0, b'\x22' * 32), ...
@pytest.mark.parametrize( ( 'attestation_latest_crosslink,' 'attestation_crosslink_data_root,' 'state_latest_crosslink,' 'is_valid,' ), [ ( CrosslinkRecord(0, b'\x11' * 32), b'\x33' * 32, CrosslinkRecord(0, b'\x22' * 32), ...
sample_attestation_data_params['latest_crosslink'] = attestation_latest_crosslink sample_attestation_data_params['crosslink_data_root'] = attestation_crosslink_data_root attestation_data = AttestationData(**sample_attestation_data_params).copy( latest_crosslink=attestation_latest_crosslink, ...
@pytest.mark.parametrize( ( 'attestation_latest_crosslink,' 'attestation_crosslink_data_root,' 'state_latest_crosslink,' 'is_valid,' ), [ ( CrosslinkRecord(0, b'\x11' * 32), b'\x33' * 32, CrosslinkRecord(0, b'\x22' * 32), ...
335
148
494
335
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_latest_crosslink
test_validate_attestation_latest_crosslink
173
238
173
218
b560100e3ae5d45d4028943d5f32a991ddc35544
bigcode/the-stack
train
57dc8efe0b8427720cfb3d90
train
function
@settings(max_examples=1) @given(random=st.randoms()) @pytest.mark.parametrize( ( 'num_validators,' 'slots_per_epoch,' 'target_committee_size,' 'shard_count,' 'is_valid,' 'genesis_slot' ), [ (10, 2, 2, 2, True, 0), (40, 4, 3, 5, True, 0), ...
@settings(max_examples=1) @given(random=st.randoms()) @pytest.mark.parametrize( ( 'num_validators,' 'slots_per_epoch,' 'target_committee_size,' 'shard_count,' 'is_valid,' 'genesis_slot' ), [ (10, 2, 2, 2, True, 0), (40, 4, 3, 5, True, 0), ...
state = genesis_state # choose committee slot = 0 crosslink_committee = get_crosslink_committees_at_slot( state=state, slot=slot, committee_config=committee_config, )[0] committee, shard = crosslink_committee committee_size = len(committee) assert committee_size ...
@settings(max_examples=1) @given(random=st.randoms()) @pytest.mark.parametrize( ( 'num_validators,' 'slots_per_epoch,' 'target_committee_size,' 'shard_count,' 'is_valid,' 'genesis_slot' ), [ (10, 2, 2, 2, True, 0), (40, 4, 3, 5, True, 0), ...
190
142
475
190
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_aggregate_signature
test_validate_attestation_aggregate_signature
270
347
270
296
c2cd8bee3e554763d72e264fe138beda845ff7e6
bigcode/the-stack
train
47ffc437e49aff1ef7b9050f
train
function
@pytest.mark.parametrize( ( 'attestation_slot,' 'attestation_justified_epoch,' 'current_epoch,' 'previous_justified_epoch,' 'justified_epoch,' 'slots_per_epoch,' 'is_valid,' ), [ # slot_to_epoch(attestation_data.slot + 1, slots_per_epoch) >= cu...
@pytest.mark.parametrize( ( 'attestation_slot,' 'attestation_justified_epoch,' 'current_epoch,' 'previous_justified_epoch,' 'justified_epoch,' 'slots_per_epoch,' 'is_valid,' ), [ # slot_to_epoch(attestation_data.slot + 1, slots_per_epoch) >= cu...
attestation_data = AttestationData(**sample_attestation_data_params).copy( slot=attestation_slot, justified_epoch=attestation_justified_epoch, ) if is_valid: validate_attestation_justified_epoch( attestation_data, current_epoch, previous_justified...
@pytest.mark.parametrize( ( 'attestation_slot,' 'attestation_justified_epoch,' 'current_epoch,' 'previous_justified_epoch,' 'justified_epoch,' 'slots_per_epoch,' 'is_valid,' ), [ # slot_to_epoch(attestation_data.slot + 1, slots_per_epoch) >= cu...
299
127
424
299
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_justified_epoch
test_validate_attestation_justified_epoch
89
138
89
116
97cc2f328081e4a04fa235367f2e0f630ac3c952
bigcode/the-stack
train
212d161efd2d4d637fcb7cdf
train
function
@pytest.mark.parametrize( ( 'attestation_justified_block_root,' 'justified_block_root,' 'is_valid,' ), [ (b'\x33' * 32, b'\x22' * 32, False), # attestation.justified_block_root != justified_block_root # noqa: E501 (b'\x33' * 32, b'\x33' * 32, True), ] ) def test_...
@pytest.mark.parametrize( ( 'attestation_justified_block_root,' 'justified_block_root,' 'is_valid,' ), [ (b'\x33' * 32, b'\x22' * 32, False), # attestation.justified_block_root != justified_block_root # noqa: E501 (b'\x33' * 32, b'\x33' * 32, True), ] ) def test_...
attestation_data = AttestationData(**sample_attestation_data_params).copy( justified_block_root=attestation_justified_block_root, ) if is_valid: validate_attestation_justified_block_root( attestation_data, justified_block_root ) else: with pytest....
@pytest.mark.parametrize( ( 'attestation_justified_block_root,' 'justified_block_root,' 'is_valid,' ), [ (b'\x33' * 32, b'\x22' * 32, False), # attestation.justified_block_root != justified_block_root # noqa: E501 (b'\x33' * 32, b'\x33' * 32, True), ] ) def test_...
134
67
226
134
0
hwwhww/trinity
tests/eth2/beacon/state_machines/forks/test_serenity_block_attestation_validation.py
Python
test_validate_attestation_justified_block_root
test_validate_attestation_justified_block_root
141
170
141
155
9c662bd269d81ec9607064b173ee121eb5cff5f2
bigcode/the-stack
train
9689def775a4e6f3415b4a6b
train
function
def satoshis(amount): # satoshi conversion must not be performed by the parser return int(COIN*Decimal(amount)) if amount not in ['!', None] else amount
def satoshis(amount): # satoshi conversion must not be performed by the parser
return int(COIN*Decimal(amount)) if amount not in ['!', None] else amount
_invoice if TYPE_CHECKING: from .network import Network from .daemon import Daemon known_commands = {} # type: Dict[str, Command] class NotSynchronizedException(Exception): pass def satoshis(amount): # satoshi conversion must not be performed by the parser
64
64
39
19
44
lucasan123/electrum-bitgesell
electrum/commands.py
Python
satoshis
satoshis
77
79
77
78
038f543eb2abe3de78176fba491e3825330fd6b5
bigcode/the-stack
train
5b80be512ccd4de91bba6278
train
class
class NotSynchronizedException(Exception): pass
class NotSynchronizedException(Exception):
pass
import ELECTRUM_VERSION from .simple_config import SimpleConfig from .lnaddr import parse_lightning_invoice if TYPE_CHECKING: from .network import Network from .daemon import Daemon known_commands = {} # type: Dict[str, Command] class NotSynchronizedException(Exception):
64
64
10
7
57
lucasan123/electrum-bitgesell
electrum/commands.py
Python
NotSynchronizedException
NotSynchronizedException
73
74
73
73
c9b3d4045134d56fd642e5a8d09d662a36699858
bigcode/the-stack
train
4ecc23de6cca39764419f24d
train
function
def set_default_subparser(self, name, args=None): """see http://stackoverflow.com/questions/5176691/argparse-how-to-specify-a-default-subcommand""" subparser_found = False for arg in sys.argv[1:]: if arg in ['-h', '--help']: # global help if no subparser break else: for x in...
def set_default_subparser(self, name, args=None):
"""see http://stackoverflow.com/questions/5176691/argparse-how-to-specify-a-default-subcommand""" subparser_found = False for arg in sys.argv[1:]: if arg in ['-h', '--help']: # global help if no subparser break else: for x in self._subparsers._actions: if not isi...
'url_rewrite': 'Parameters passed to str.replace(), in order to create the r= part of bitgesell: URIs. Example: \"(\'file:///var/www/\',\'https://electrum.org/\')\"', } } def set_default_subparser(self, name, args=None):
64
64
193
12
52
lucasan123/electrum-bitgesell
electrum/commands.py
Python
set_default_subparser
set_default_subparser
1,215
1,234
1,215
1,215
7a6f24cca983f5819e000440deb61057579fa03f
bigcode/the-stack
train
e3334153406282dc1fa90dc4
train
function
def add_wallet_option(parser): parser.add_argument("-w", "--wallet", dest="wallet_path", help="wallet path") parser.add_argument("--forgetconfig", action="store_true", dest="forget_config", default=False, help="Forget config on exit")
def add_wallet_option(parser):
parser.add_argument("-w", "--wallet", dest="wallet_path", help="wallet path") parser.add_argument("--forgetconfig", action="store_true", dest="forget_config", default=False, help="Forget config on exit")
Use Regtest") group.add_argument("--simnet", action="store_true", dest="simnet", default=False, help="Use Simnet") group.add_argument("-o", "--offline", action="store_true", dest="offline", default=False, help="Run offline") def add_wallet_option(parser):
64
64
54
6
58
lucasan123/electrum-bitgesell
electrum/commands.py
Python
add_wallet_option
add_wallet_option
1,287
1,289
1,287
1,287
67c1dfaf3906a36932220516b2ad2f7a7001b250
bigcode/the-stack
train
b46fe980849ac108fa79bacc
train
function
def get_parser(): # create main parser parser = argparse.ArgumentParser( epilog="Run 'electrum help <command>' to see the help for a command") add_global_options(parser) subparsers = parser.add_subparsers(dest='cmd', metavar='<command>') # gui parser_gui = subparsers.add_parser('gui', de...
def get_parser(): # create main parser
parser = argparse.ArgumentParser( epilog="Run 'electrum help <command>' to see the help for a command") add_global_options(parser) subparsers = parser.add_subparsers(dest='cmd', metavar='<command>') # gui parser_gui = subparsers.add_parser('gui', description="Run Electrum's Graphical User In...
.add_argument("-P", "--portable", action="store_true", dest="portable", default=False, help="Use local 'electrum_data' directory") group.add_argument("--testnet", action="store_true", dest="testnet", default=False, help="Use Testnet") group.add_argument("--regtest", action="store_true", dest="regtest", default=...
203
203
677
10
193
lucasan123/electrum-bitgesell
electrum/commands.py
Python
get_parser
get_parser
1,291
1,346
1,291
1,292
35c1af8b9e1016542533c881686678adcfbe4a7e
bigcode/the-stack
train
1971e6909fae86b6e69d7da7
train
function
def command(s): def decorator(func): global known_commands name = func.__name__ known_commands[name] = Command(func, s) @wraps(func) async def func_wrapper(*args, **kwargs): cmd_runner = args[0] # type: Commands cmd = known_commands[func.__name__] # ...
def command(s):
def decorator(func): global known_commands name = func.__name__ known_commands[name] = Command(func, s) @wraps(func) async def func_wrapper(*args, **kwargs): cmd_runner = args[0] # type: Commands cmd = known_commands[func.__name__] # type: Command ...
self.defaults = [] # sanity checks if self.requires_password: assert self.requires_wallet for varname in ('wallet_path', 'wallet'): if varname in varnames: assert varname in self.options assert not ('wallet_path' in varnames and 'walle...
87
87
292
4
82
lucasan123/electrum-bitgesell
electrum/commands.py
Python
command
command
120
150
120
120
5cb8890f6e31e55d979245d25d16578ffc6c7a34
bigcode/the-stack
train
4450b651873eb4fe47a08af7
train
function
def subparser_call(self, parser, namespace, values, option_string=None): from argparse import ArgumentError, SUPPRESS, _UNRECOGNIZED_ARGS_ATTR parser_name = values[0] arg_strings = values[1:] # set the parser name if requested if self.dest is not SUPPRESS: setattr(namespace, self.dest, parse...
def subparser_call(self, parser, namespace, values, option_string=None):
from argparse import ArgumentError, SUPPRESS, _UNRECOGNIZED_ARGS_ATTR parser_name = values[0] arg_strings = values[1:] # set the parser name if requested if self.dest is not SUPPRESS: setattr(namespace, self.dest, parser_name) # select the parser try: parser = self._name_pars...
else: args.insert(0, name) argparse.ArgumentParser.set_default_subparser = set_default_subparser # workaround https://bugs.python.org/issue23058 # see https://github.com/nickstenning/honcho/pull/121 def subparser_call(self, parser, namespace, values, option_string=None):
71
71
239
16
54
lucasan123/electrum-bitgesell
electrum/commands.py
Python
subparser_call
subparser_call
1,242
1,262
1,242
1,242
e89e6abc0a0c7b992e894b4e36d7a332308ed79e
bigcode/the-stack
train
7622cd988b94626d501898d5
train
class
class Commands: def __init__(self, *, config: 'SimpleConfig', network: 'Network' = None, daemon: 'Daemon' = None, callback=None): self.config = config self.daemon = daemon self.network = network self._callback = callback def _run(self, method, ...
class Commands:
def __init__(self, *, config: 'SimpleConfig', network: 'Network' = None, daemon: 'Daemon' = None, callback=None): self.config = config self.daemon = daemon self.network = network self._callback = callback def _run(self, method, args, password_ge...
async def func_wrapper(*args, **kwargs): cmd_runner = args[0] # type: Commands cmd = known_commands[func.__name__] # type: Command password = kwargs.get('password') daemon = cmd_runner.daemon if daemon: if 'wallet_path' in cmd.options and kw...
256
256
8,719
3
252
lucasan123/electrum-bitgesell
electrum/commands.py
Python
Commands
Commands
153
1,098
153
154
0a43a1871e3d92239e26dbf470a27737899fcc6e
bigcode/the-stack
train
8ffdd934678908560bcd6fcc
train
function
def eval_bool(x: str) -> bool: if x == 'false': return False if x == 'true': return True try: return bool(ast.literal_eval(x)) except: return bool(x)
def eval_bool(x: str) -> bool:
if x == 'false': return False if x == 'true': return True try: return bool(ast.literal_eval(x)) except: return bool(x)
_watchtower_ctn(self, channel_point, wallet: Abstract_Wallet = None): """ return the local watchtower's ctn of channel. used in regtests """ return await self.network.local_watchtower.sweepstore.get_ctn(channel_point, None) def eval_bool(x: str) -> bool:
64
64
49
10
54
lucasan123/electrum-bitgesell
electrum/commands.py
Python
eval_bool
eval_bool
1,101
1,107
1,101
1,101
090a2cb781d274b7ae21ef8eb6b218913f99b5cf
bigcode/the-stack
train
ee52314035c4390a23827151
train
function
def add_network_options(parser): parser.add_argument("-f", "--serverfingerprint", dest="serverfingerprint", default=None, help="only allow connecting to servers with a matching SSL certificate SHA256 fingerprint." + " " + ...
def add_network_options(parser):
parser.add_argument("-f", "--serverfingerprint", dest="serverfingerprint", default=None, help="only allow connecting to servers with a matching SSL certificate SHA256 fingerprint." + " " + "To calculate this yourself: ...
parser can decide what to do with them namespace, arg_strings = parser.parse_known_args(arg_strings, namespace) if arg_strings: vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) argparse._SubParsersAction.__call__ = subparse...
83
83
278
6
76
lucasan123/electrum-bitgesell
electrum/commands.py
Python
add_network_options
add_network_options
1,267
1,274
1,267
1,267
4730162a2c21a8753dd4ba5ba18deb30d8c6c6c6
bigcode/the-stack
train
6ba1c448977f5e105b719138
train
function
def add_global_options(parser): group = parser.add_argument_group('global options') group.add_argument("-v", dest="verbosity", help="Set verbosity (log levels)", default='') group.add_argument("-V", dest="verbosity_shortcuts", help="Set verbosity (shortcut-filter list)", default='') group.add_argument("...
def add_global_options(parser):
group = parser.add_argument_group('global options') group.add_argument("-v", dest="verbosity", help="Set verbosity (log levels)", default='') group.add_argument("-V", dest="verbosity_shortcuts", help="Set verbosity (shortcut-filter list)", default='') group.add_argument("-D", "--dir", dest="electrum_pat...
="store_true", dest="noonion", default=None, help="do not try to connect to onion servers") parser.add_argument("--skipmerklecheck", action="store_true", dest="skipmerklecheck", default=False, help="Tolerate invalid merkle proofs from server") def add_global_options(parser):
67
67
225
6
61
lucasan123/electrum-bitgesell
electrum/commands.py
Python
add_global_options
add_global_options
1,276
1,285
1,276
1,276
86f5e991ec08c9d8fc3823e314d4e8d9406fae17
bigcode/the-stack
train
b5fffc7fe5f1c06ea9adfeee
train
function
def json_normalize(x): # note: The return value of commands, when going through the JSON-RPC interface, # is json-encoded. The encoder used there cannot handle some types, e.g. electrum.util.Satoshis. # note: We should not simply do "json_encode(x)" here, as then later x would get doubly json-encoded....
def json_normalize(x): # note: The return value of commands, when going through the JSON-RPC interface, # is json-encoded. The encoder used there cannot handle some types, e.g. electrum.util.Satoshis. # note: We should not simply do "json_encode(x)" here, as then later x would get doubly json-encoded....
return json_decode(json_encode(x))
def json_normalize(x): # note: The return value of commands, when going through the JSON-RPC interface, # is json-encoded. The encoder used there cannot handle some types, e.g. electrum.util.Satoshis. # note: We should not simply do "json_encode(x)" here, as then later x would get doubly json-encoded....
87
64
95
87
0
lucasan123/electrum-bitgesell
electrum/commands.py
Python
json_normalize
json_normalize
82
87
82
86
c7a9a7ee9c207ebfb63bae3dcaf0ed8e481cabf7
bigcode/the-stack
train
9ff0e5003abcbcad3f939562
train
class
class Command: def __init__(self, func, s): self.name = func.__name__ self.requires_network = 'n' in s self.requires_wallet = 'w' in s self.requires_password = 'p' in s self.description = func.__doc__ self.help = self.description.split('.')[0] if self.description else...
class Command:
def __init__(self, func, s): self.name = func.__name__ self.requires_network = 'n' in s self.requires_wallet = 'w' in s self.requires_password = 'p' in s self.description = func.__doc__ self.help = self.description.split('.')[0] if self.description else None v...
# is json-encoded. The encoder used there cannot handle some types, e.g. electrum.util.Satoshis. # note: We should not simply do "json_encode(x)" here, as then later x would get doubly json-encoded. # see #5868 return json_decode(json_encode(x)) class Command:
72
72
240
3
69
lucasan123/electrum-bitgesell
electrum/commands.py
Python
Command
Command
90
117
90
90
8d3f07afdc1bd507683b5b771eddfa8113c68bbe
bigcode/the-stack
train
6640ab2d9b3667a89ccff2c7
train
class
class AuthJWT(AuthConfig): def __init__(self,req: Request = None, res: Response = None): """ Get jwt header from incoming request or get request and response object if jwt in the cookie :param req: all incoming request :param res: response from endpoint """ i...
class AuthJWT(AuthConfig):
def __init__(self,req: Request = None, res: Response = None): """ Get jwt header from incoming request or get request and response object if jwt in the cookie :param req: all incoming request :param res: response from endpoint """ if res and self.jwt_in_cooki...
import jwt, re, uuid, hmac from jwt.algorithms import requires_cryptography, has_crypto from datetime import datetime, timezone, timedelta from typing import Optional, Dict, Union, Sequence from fastapi import Request, Response, WebSocket from fastapi_jwt_auth.auth_config import AuthConfig from fastapi_jwt_auth.excepti...
123
256
7,195
6
117
alternativshik/fastapi-jwt-auth
fastapi_jwt_auth/auth_jwt.py
Python
AuthJWT
AuthJWT
18
848
18
18
2e3c342c5a5edada9dd1841210d9fc28eadb8818
bigcode/the-stack
train
69d036852ba3ecec759f9306
train
function
@solid def error_message(context): context.log.error('An error occurred.')
@solid def error_message(context):
context.log.error('An error occurred.')
# pylint: disable=no-value-for-parameter from dagster import pipeline, solid @solid def debug_message(context): context.log.debug('A debug message.') return 'foo' @solid def error_message(context):
48
64
17
8
40
atsuhiro/dagster
examples/dagster_examples/intro_tutorial/execution_context.py
Python
error_message
error_message
12
14
12
13
cdf7794e1bb22c137dffc96a219e9db905b12c47
bigcode/the-stack
train
ff8e6f2725145c5ffe543d6f
train
function
@solid def debug_message(context): context.log.debug('A debug message.') return 'foo'
@solid def debug_message(context):
context.log.debug('A debug message.') return 'foo'
# pylint: disable=no-value-for-parameter from dagster import pipeline, solid @solid def debug_message(context):
26
64
22
8
17
atsuhiro/dagster
examples/dagster_examples/intro_tutorial/execution_context.py
Python
debug_message
debug_message
6
9
6
7
e0dbdb1710df76d77f2a6de7efe3bcf5bb6bfd54
bigcode/the-stack
train
1bb0a9b8e96c4c83f1bc06b7
train
function
@pipeline def execution_context_pipeline(): debug_message() error_message()
@pipeline def execution_context_pipeline():
debug_message() error_message()
: disable=no-value-for-parameter from dagster import pipeline, solid @solid def debug_message(context): context.log.debug('A debug message.') return 'foo' @solid def error_message(context): context.log.error('An error occurred.') @pipeline def execution_context_pipeline():
63
64
16
8
55
atsuhiro/dagster
examples/dagster_examples/intro_tutorial/execution_context.py
Python
execution_context_pipeline
execution_context_pipeline
17
20
17
18
5e875fdceaa4b5fdec00afad2652caa300c1a3bf
bigcode/the-stack
train
8cb7e7e5edb76e02cbb81911
train
class
class Connectiontype(basestring): """ direct|fabric Possible values: <ul> <li> "direct" - The port is direct attached., <li> "fabric" - The port is fabric attached. </ul> """ @staticmethod def get_api_name(): return "connectiontype"
class Connectiontype(basestring):
""" direct|fabric Possible values: <ul> <li> "direct" - The port is direct attached., <li> "fabric" - The port is fabric attached. </ul> """ @staticmethod def get_api_name(): return "connectiontype"
class Connectiontype(basestring):
7
64
75
7
0
radekg/netapp-ontap-lib-get
generated-libraries/python/netapp/storage_array/connectiontype.py
Python
Connectiontype
Connectiontype
1
13
1
1
eee2a0b92ae42511a9694413358ac6830b5a2b20
bigcode/the-stack
train
a42a3f7e82291058efd6cc9c
train
function
def plot_feedback(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.quesi[sample.quesi["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.quesi[sample.quesi["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=...
def plot_feedback(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.quesi[sample.quesi["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.quesi[sample.quesi["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=False, ...
.45], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("QUESI Score") plt.tight_layout() plt.show() def plot_feedback(sample):
63
64
167
5
58
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_feedback
plot_feedback
172
184
172
172
db49b595b08c9b352c5bf81d89eab6651467507f
bigcode/the-stack
train
c7dc90796270657dc6939c97
train
function
def plot_age(sample): age = sample.pre["alter"].apply(lambda x: int(x)) age.name = "Alter" ax = age.plot.box(vert=False, figsize=(6, 2), widths=.45, color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, m...
def plot_age(sample):
age = sample.pre["alter"].apply(lambda x: int(x)) age.name = "Alter" ax = age.plot.box(vert=False, figsize=(6, 2), widths=.45, color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth...
)") ax = occupation.value_counts().sort_values().plot.barh(color="#555753", figsize=(7.7, 3.5)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Beschäftigung") plt.tight_layout() plt.show() def plot_age(sample):
63
64
126
5
58
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_age
plot_age
128
140
128
128
1f09c9fdc1b366b1af541324df6129bc91e030ae
bigcode/the-stack
train
c86f84891749c6615bbd4547
train
function
def plot_nasa_tlx(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.nasa[sample.nasa["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.nasa[sample.nasa["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=False...
def plot_nasa_tlx(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.nasa[sample.nasa["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.nasa[sample.nasa["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=False, fig...
D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("Alter, in Jahren") ax.set_yticklabels("") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_nasa_tlx(sample):
63
64
167
8
55
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_nasa_tlx
plot_nasa_tlx
143
154
143
143
dc214c4f0b12128ace119f4570c34ba8f4b5aea0
bigcode/the-stack
train
ee8500e5442fe9c408e9442d
train
function
def plot_severity(data): # absolute plt.figure() a = data.plot.barh(figsize=(7.7, 2.4), width=.95, color=("#BABDB6", "#8AE234", "#FCE94F", "#F57900", "#EF2929")) a.set_xlabel("Absolute Häufigkeit") a.set_ylabel("Website") plt.legend(bbox_to_anchor=(1...
def plot_severity(data): # absolute
plt.figure() a = data.plot.barh(figsize=(7.7, 2.4), width=.95, color=("#BABDB6", "#8AE234", "#FCE94F", "#F57900", "#EF2929")) a.set_xlabel("Absolute Häufigkeit") a.set_ylabel("Website") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., title=...
import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator def plot_severity(data): # absolute
30
76
256
10
19
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_severity
plot_severity
6
28
6
7
eda5ccea3803e18083512263151999282f4a00dd
bigcode/the-stack
train
6b70b2a61c9987e7f110744f
train
function
def plot_experience(sample): ax = sample.pre["vorkenntnisse"].replace("n. a.", "Keine Angabe").replace("spreadshirt.de", "Spreadshirt").replace("nein", "Keine").value_counts().sort_values().plot.barh(color="#555753", figsize=(6, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Vorkenntnisse") a...
def plot_experience(sample):
ax = sample.pre["vorkenntnisse"].replace("n. a.", "Keine Angabe").replace("spreadshirt.de", "Spreadshirt").replace("nein", "Keine").value_counts().sort_values().plot.barh(color="#555753", figsize=(6, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Vorkenntnisse") ax.xaxis.set_major_locator(Max...
3.5)) plt.legend(bbox_to_anchor=(1.05, 1), loc=None, borderaxespad=0., title="Schweregrad") r.set_xlabel("Relative Häufigkeit") plt.tight_layout() plt.show() def plot_experience(sample):
63
64
113
6
57
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_experience
plot_experience
83
89
83
83
3c6b2ce59f498da5b2d4e2e1b625139860cf7e7c
bigcode/the-stack
train
66901adb70655308a98ea2f5
train
function
def plot_assistance(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.assistance[sample.assistance["website"] == "spreadshirt"]["n"].values df.loc[:, "Shirtinator"] = sample.assistance[sample.assistance["website"] == "shirtinator"]["n"].values assistanc...
def plot_assistance(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.assistance[sample.assistance["website"] == "spreadshirt"]["n"].values df.loc[:, "Shirtinator"] = sample.assistance[sample.assistance["website"] == "shirtinator"]["n"].values assistance = pd.DataFrame({"Shirtinato...
h(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Bewertung") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_assistance(sample):
63
64
215
6
57
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_assistance
plot_assistance
214
226
214
214
3f8510fafc9afd9471ddc809c3317a19a7dd5be8
bigcode/the-stack
train
153f0ec8e85186847b36e5e5
train
function
def plot_quesi(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.quesi[sample.quesi["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.quesi[sample.quesi["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=Fal...
def plot_quesi(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.quesi[sample.quesi["website"] == "spreadshirt"]["score"].values df.loc[:, "Shirtinator"] = sample.quesi[sample.quesi["website"] == "shirtinator"]["score"].values ax = df.plot.box(vert=False, ...
color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("NASA-TLX Score") plt.tight_layout() plt.show() def plot_quesi(sample):
63
64
168
7
56
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_quesi
plot_quesi
157
169
157
157
e70e522d66eb0cc56194b4d283715879696d85be
bigcode/the-stack
train
a0152125331d49fca8e2d883
train
function
def plot_gender(sample): ax = sample.pre["geschlecht"].apply(lambda x: x.title()).value_counts().sort_values().plot.barh(color="#555753", figsize=(6, 2)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Geschlecht") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt....
def plot_gender(sample):
ax = sample.pre["geschlecht"].apply(lambda x: x.title()).value_counts().sort_values().plot.barh(color="#555753", figsize=(6, 2)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Geschlecht") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show()
h(color="#555753", figsize=(6, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Vorkenntnisse") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_gender(sample):
63
64
82
5
58
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_gender
plot_gender
92
98
92
92
9ca9e3793e91515e29c629d339614d00dc45938a
bigcode/the-stack
train
30c9948f845889477108e721
train
function
def plot_clicks(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.mouse[sample.mouse["website"] == "spreadshirt"]["clicks"].values df.loc[:, "Shirtinator"] = sample.mouse[sample.mouse["website"] == "shirtinator"]["clicks"].values ax = df.plot.box(vert=...
def plot_clicks(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.mouse[sample.mouse["website"] == "spreadshirt"]["clicks"].values df.loc[:, "Shirtinator"] = sample.mouse[sample.mouse["website"] == "shirtinator"]["clicks"].values ax = df.plot.box(vert=False, ...
], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("positiv : negativ") plt.tight_layout() plt.show() def plot_clicks(sample):
63
64
163
6
57
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_clicks
plot_clicks
187
199
187
187
d84a9edb7983790e0d554f9c03b486f9146153ca
bigcode/the-stack
train
e6cc94a1f4c64f6b8a79e4ad
train
function
def plot_education(sample): ax = sample.pre["bildungsabschluss"].value_counts().sort_values().plot.barh(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Höchster\nBildungsabschluss") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() ...
def plot_education(sample):
ax = sample.pre["bildungsabschluss"].value_counts().sort_values().plot.barh(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Höchster\nBildungsabschluss") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show()
_values().plot.barh(color="#555753", figsize=(6, 2)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Geschlecht") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_education(sample):
63
64
85
6
57
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_education
plot_education
101
107
101
101
92399a3b5c4b8130d1e9d43c447666fbd01deb6e
bigcode/the-stack
train
8ab5e6ce131b56ed09be4095
train
function
def plot_concordance(data): data["Sum"] = data.sum(axis=1) data = data.sort_values("Sum") data = pd.DataFrame([data["Irrelevant"], data["Irrelevant_S"], data["Kosmetisch"], data["Kosmetisch_S"], data["Gering...
def plot_concordance(data):
data["Sum"] = data.sum(axis=1) data = data.sort_values("Sum") data = pd.DataFrame([data["Irrelevant"], data["Irrelevant_S"], data["Kosmetisch"], data["Kosmetisch_S"], data["Gering"], ...
plot_problems(data): ax = data.plot.box(vert=False, figsize=(6, 2.5), widths=[.45, .45], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("Absolute Häuf...
104
105
350
7
97
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_concordance
plot_concordance
43
80
43
43
1f52bcd919be17de1ec6278491e37afc6f599189
bigcode/the-stack
train
9631cb69f3e8c47270dc81ee
train
function
def plot_occupation(sample): occupation = sample.pre["beschäftigung"].replace("MCS", "Student (Mensch-Computer-Systeme)") occupation = occupation.replace("Mensch-Computer-Systeme", "Student (Mensch-Computer-Systeme)") occupation = occupation.replace("Mensch-Computer-Systeme (Student)", "Student (Mensch-Comp...
def plot_occupation(sample):
occupation = sample.pre["beschäftigung"].replace("MCS", "Student (Mensch-Computer-Systeme)") occupation = occupation.replace("Mensch-Computer-Systeme", "Student (Mensch-Computer-Systeme)") occupation = occupation.replace("Mensch-Computer-Systeme (Student)", "Student (Mensch-Computer-Systeme)") occupatio...
value_counts().sort_values().plot.barh(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Höchster\nBildungsabschluss") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_occupation(sample):
76
77
258
6
70
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_occupation
plot_occupation
110
125
110
110
1cce81625da52318709d705c58314e4ca13215ba
bigcode/the-stack
train
fa12230dd8812d64a9c2ac8d
train
function
def plot_mistakes(sample): df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.mistakes[sample.mistakes["website"] == "spreadshirt"]["n"].values df.loc[:, "Shirtinator"] = sample.mistakes[sample.mistakes["website"] == "shirtinator"]["n"].values mistakes = pd.DataF...
def plot_mistakes(sample):
df = pd.DataFrame(columns=["Shirtinator", "Spreadshirt"]) df.loc[:, "Spreadshirt"] = sample.mistakes[sample.mistakes["website"] == "spreadshirt"]["n"].values df.loc[:, "Shirtinator"] = sample.mistakes[sample.mistakes["website"] == "shirtinator"]["n"].values mistakes = pd.DataFrame({"Shirtinator": df["Sh...
Anzahl Hilfestellungen") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., title="Website") ax.xaxis.set_major_locator(MaxNLocator(integer=True)) plt.tight_layout() plt.show() def plot_mistakes(sample):
64
65
218
7
57
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_mistakes
plot_mistakes
229
241
229
229
29a3947b5cfaf75c4f634d93d4f4bcfdc9feb331
bigcode/the-stack
train
684665763fccb69bf7b1c5f0
train
function
def plot_problems(data): ax = data.plot.box(vert=False, figsize=(6, 2.5), widths=[.45, .45], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("Absolute H...
def plot_problems(data):
ax = data.plot.box(vert=False, figsize=(6, 2.5), widths=[.45, .45], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("Absolute Häufigkeit") ax.set_yl...
9")) plt.legend(bbox_to_anchor=(1.05, 1), loc=None, borderaxespad=0., title="Schweregrad") r.set_xlabel("Relative Häufigkeit") r.set_ylabel("Website") plt.tight_layout() plt.show() def plot_problems(data):
64
64
98
6
58
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_problems
plot_problems
31
40
31
31
d2a3e644ae4a27c67be083142c002cea05f697c4
bigcode/the-stack
train
63f31688aea070d6d6939815
train
function
def plot_choice(sample): choice = sample.post.besser.value_counts() choice.index = ["Shirtinator besser", "Spreadshirt besser", "Beide gleich gut"] ax = choice.sort_values().plot.barh(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Bewertung") ax.xaxis.s...
def plot_choice(sample):
choice = sample.post.besser.value_counts() choice.index = ["Shirtinator besser", "Spreadshirt besser", "Beide gleich gut"] ax = choice.sort_values().plot.barh(color="#555753", figsize=(7.7, 2.3)) ax.set_xlabel("Absolute Häufigkeit") ax.set_ylabel("Bewertung") ax.xaxis.set_major_locator(MaxNLoca...
], color={"whiskers": "black", "boxes": "black", 'medians': '#D62728'}, medianprops={'linewidth': 2.8}) ax.set_xlabel("Absolute Häufigkiet") plt.tight_layout() plt.show() def plot_choice(sample):
63
64
102
5
58
severinsimmler/usability-survey
analysis/usability/visualization.py
Python
plot_choice
plot_choice
202
211
202
202
06059c073cc173526976c6d37cbb31c03d2eae1a
bigcode/the-stack
train
3d2ad8eab97658f27fd9ac47
train
class
class MDPSolverExperiment(Experiment): """ The MDPSolver Experiment connects an MDPSolver and Domain, and runs the MDPSolver's solve method to start solving the MDP. """ def __init__(self, agent, domain, seed=10): """ :param agent: The agent to be tested. :param domain: The ...
class MDPSolverExperiment(Experiment):
""" The MDPSolver Experiment connects an MDPSolver and Domain, and runs the MDPSolver's solve method to start solving the MDP. """ def __init__(self, agent, domain, seed=10): """ :param agent: The agent to be tested. :param domain: The domain to be tested on. """ ...
/RLPy" __credits__ = [ "Alborz Geramifard", "Robert H. Klein", "Christoph Dann", "William Dabney", "Jonathan P. How", ] __license__ = "BSD 3-Clause" class MDPSolverExperiment(Experiment):
64
64
178
8
56
kngwyu/rlpy
rlpy/experiments/mdpsolver_experiment.py
Python
MDPSolverExperiment
MDPSolverExperiment
15
40
15
15
3359a6d94d1432907dc36f5f7bad6fb9b3339ed3
bigcode/the-stack
train
72b2a2e411475174201fa35e
train
function
def blackjack(utxos, outputs, feeRate): feeRate = Decimal(feeRate) bytesAccum = utils.transactionBytes([], outputs) inAccum = 0 inputs = [] outAccum = utils.sumOrNaN(outputs) threshold = utils.dustThreshold({}, feeRate) for i in range(len(utxos)): input = utxos[i] inputByte...
def blackjack(utxos, outputs, feeRate):
feeRate = Decimal(feeRate) bytesAccum = utils.transactionBytes([], outputs) inAccum = 0 inputs = [] outAccum = utils.sumOrNaN(outputs) threshold = utils.dustThreshold({}, feeRate) for i in range(len(utxos)): input = utxos[i] inputBytes = utils.inputBytes(input) fee ...
from decimal import Decimal from . import utils # only add inputs if they don't bust the target value (aka, exact match) # worst-case: O(n) def blackjack(utxos, outputs, feeRate):
46
64
204
12
34
nextwallet-svr/CoinSelectPy
coinselectpy/blackjack.py
Python
blackjack
blackjack
7
36
7
7
b42edf7c94370237c4a31a53ab495ecae0a4be64
bigcode/the-stack
train
533d4cf35a155553cbe9bd8e
train
class
class TestSorted(Base): """ everything you wanted to test about sorting """ def test_sort_index_preserve_levels(self): result = self.frame.sort_index() assert result.index.names == self.frame.index.names def test_sorting_repr_8017(self): np.random.seed(0) data = ...
class TestSorted(Base):
""" everything you wanted to test about sorting """ def test_sort_index_preserve_levels(self): result = self.frame.sort_index() assert result.index.names == self.frame.index.names def test_sorting_repr_8017(self): np.random.seed(0) data = np.random.randn(3, 4) ...
(df.index.levels[2], idx3) tm.assert_index_equal(df.index.get_level_values(0), idx1) tm.assert_index_equal(df.index.get_level_values(1), idx2) tm.assert_index_equal(df.index.get_level_values(2), idx3) def test_repeat(self): # GH 9361 # fixed by # GH 7891 m_...
256
256
4,066
5
251
Jos33y/student-performance-knn
venv/Lib/site-packages/pandas/tests/test_multilevel.py
Python
TestSorted
TestSorted
2,026
2,473
2,026
2,026
7924535f5573fd27e056294005328ea31da9c397
bigcode/the-stack
train
cfcbec9d325f06f26353db40
train
class
class TestMultiLevel(Base): def test_append(self): a, b = self.frame[:5], self.frame[5:] result = a.append(b) tm.assert_frame_equal(result, self.frame) result = a["A"].append(b["A"]) tm.assert_series_equal(result, self.frame["A"]) def test_append_index(self):...
class TestMultiLevel(Base):
def test_append(self): a, b = self.frame[:5], self.frame[5:] result = a.append(b) tm.assert_frame_equal(result, self.frame) result = a["A"].append(b["A"]) tm.assert_series_equal(result, self.frame["A"]) def test_append_index(self): idx1 = Index([1.1, ...
", "qux"]], codes=[[0, 1, 2, 3]], names=["first"] ) # create test series object arrays = [ ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] tuples = zip(*arrays) index =...
256
256
19,900
6
250
Jos33y/student-performance-knn
venv/Lib/site-packages/pandas/tests/test_multilevel.py
Python
TestMultiLevel
TestMultiLevel
73
2,023
73
73
a0980baaf1749d1d408e848b460a1999a95371ff
bigcode/the-stack
train
80473e4971dadae3cde81924
train
class
class Base: def setup_method(self, method): index = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) self.frame = DataF...
class Base:
def setup_method(self, method): index = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) self.frame = DataFrame( ...
itertools from itertools import product import numpy as np from numpy.random import randn import pytest import pytz from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna import pandas._testing a...
126
127
425
3
123
Jos33y/student-performance-knn
venv/Lib/site-packages/pandas/tests/test_multilevel.py
Python
Base
Base
32
70
32
32
a02eee8990115888c6cea7aba1017b72b9df9957
bigcode/the-stack
train
0780c3c5e8294ec312c8dd34
train
class
class DynamoDbTableResourceSpec(DynamoDBResourceSpec): """Resource for DynamoDB Tables""" type_name = "table" schema = Schema( ScalarField("TableName", "name"), ScalarField("TableStatus"), ScalarField("CreationDateTime"), ScalarField("TableSizeBytes"), ScalarField("I...
class DynamoDbTableResourceSpec(DynamoDBResourceSpec):
"""Resource for DynamoDB Tables""" type_name = "table" schema = Schema( ScalarField("TableName", "name"), ScalarField("TableStatus"), ScalarField("CreationDateTime"), ScalarField("TableSizeBytes"), ScalarField("ItemCount"), ScalarField("TableId"), Ano...
"""Resource for IAM Policies""" from typing import Any, Type, List, Dict from botocore.client import BaseClient from altimeter.core.graph.field.scalar_field import ScalarField from altimeter.core.graph.field.dict_field import AnonymousDictField from altimeter.core.graph.schema import Schema from altimeter.aws.resourc...
98
158
527
12
85
AmOr1984v02/altimeter
altimeter/aws/resource/dynamodb/dynamodb_table.py
Python
DynamoDbTableResourceSpec
DynamoDbTableResourceSpec
13
78
13
13
e5615e567af26bc025855275ef0aabd58ec9091a
bigcode/the-stack
train
8880523395c62292354e7d13
train
function
def get_continuous_backup_table_data(client: BaseClient, table_name: str) -> Dict: """Retrieve detailed properties of DynamoDB table""" resp = client.describe_continuous_backups(TableName=table_name) backup_data = {"ContinuousBackupsDescription": resp.get("ContinuousBackupsDescription", None)} return ba...
def get_continuous_backup_table_data(client: BaseClient, table_name: str) -> Dict:
"""Retrieve detailed properties of DynamoDB table""" resp = client.describe_continuous_backups(TableName=table_name) backup_data = {"ContinuousBackupsDescription": resp.get("ContinuousBackupsDescription", None)} return backup_data
-> Dict: """Retrieve detailed properties of DynamoDB table""" table_resp = client.describe_table(TableName=table_name) table_data = table_resp.get("Table", None) return table_data def get_continuous_backup_table_data(client: BaseClient, table_name: str) -> Dict:
64
64
72
21
42
AmOr1984v02/altimeter
altimeter/aws/resource/dynamodb/dynamodb_table.py
Python
get_continuous_backup_table_data
get_continuous_backup_table_data
88
92
88
88
8f1d54b8c106eb3d2d071a341f1423ca69ff4d17
bigcode/the-stack
train
8178ed8c32068d6e42538a85
train
function
def get_table_data(client: BaseClient, table_name: str) -> Dict: """Retrieve detailed properties of DynamoDB table""" table_resp = client.describe_table(TableName=table_name) table_data = table_resp.get("Table", None) return table_data
def get_table_data(client: BaseClient, table_name: str) -> Dict:
"""Retrieve detailed properties of DynamoDB table""" table_resp = client.describe_table(TableName=table_name) table_data = table_resp.get("Table", None) return table_data
=table_name ) table_data.update(continuous_backup_data) resource_arn = table_data["TableArn"] tables[resource_arn] = table_data return ListFromAWSResult(resources=tables) def get_table_data(client: BaseClient, table_name: str) -> Dict:
64
64
57
17
47
AmOr1984v02/altimeter
altimeter/aws/resource/dynamodb/dynamodb_table.py
Python
get_table_data
get_table_data
81
85
81
81
69f6242d1574c5d46034b283aa3268a602c5cac7
bigcode/the-stack
train
ee365e246e24480f75ea3831
train
class
class EvtAnimationsLoaded(event.Event): '''Triggered when animations names have been received from the engine'''
class EvtAnimationsLoaded(event.Event):
'''Triggered when animations names have been received from the engine'''
Names', 'Triggers', 'animation_completed_filter'] import collections from . import logger from . import action from . import exceptions from . import event from ._clad import _clad_to_engine_iface, _clad_to_engine_cozmo class EvtAnimationsLoaded(event.Event):
64
64
21
8
55
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
EvtAnimationsLoaded
EvtAnimationsLoaded
35
36
35
35
6785e7ebb7c10eba8505b3758daa16b6ed758be6
bigcode/the-stack
train
89dad21dc645a2f93096d7ec
train
class
class Animation(action.Action): '''An Animation describes an actively-playing animation on a robot.''' def __init__(self, anim_name, loop_count, ignore_body_track=False, ignore_head_track=False, ignore_lift_track=False, **kw): super().__init__(**kw) #: The name of the animation...
class Animation(action.Action):
'''An Animation describes an actively-playing animation on a robot.''' def __init__(self, anim_name, loop_count, ignore_body_track=False, ignore_head_track=False, ignore_lift_track=False, **kw): super().__init__(**kw) #: The name of the animation that was dispatched sel...
import collections from . import logger from . import action from . import exceptions from . import event from ._clad import _clad_to_engine_iface, _clad_to_engine_cozmo class EvtAnimationsLoaded(event.Event): '''Triggered when animations names have been received from the engine''' class EvtAnimationComplete...
107
107
359
5
102
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
Animation
Animation
44
82
44
44
5f69cedf3258eaf9547fa0fcf4533b59f986f7b9
bigcode/the-stack
train
79b9b7155afb376ac397954e
train
class
class AnimationTrigger(action.Action): '''An AnimationTrigger represents a playing animation trigger. Asking Cozmo to play an AnimationTrigger causes him to pick one of the animations represented by the group. ''' def __init__(self, trigger, loop_count, use_lift_safe, ignore_body_track, ...
class AnimationTrigger(action.Action):
'''An AnimationTrigger represents a playing animation trigger. Asking Cozmo to play an AnimationTrigger causes him to pick one of the animations represented by the group. ''' def __init__(self, trigger, loop_count, use_lift_safe, ignore_body_track, ignore_head_track, ignore_lift_tr...
return "anim_name=%s loop_count=%s ignore_tracks=%s" % (self.anim_name, self.loop_count, str(ignore_tracks)) def _encode(self): return _clad_to_engine_iface.PlayAnimation(animationName=self.anim_name, numLoops=self.loop_count, ignoreBodyTrack=self.ignore_body_track, ignoreHeadTrack=self.ignore...
135
135
450
6
129
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
AnimationTrigger
AnimationTrigger
85
132
85
85
8edea38056894896b56077b16f68a75786b1d84e
bigcode/the-stack
train
553d60f23e475425b26b9be4
train
class
class EvtAnimationCompleted(action.EvtActionCompleted): '''Triggered when an animation completes.''' animation_name = "The name of the animation or trigger that completed"
class EvtAnimationCompleted(action.EvtActionCompleted):
'''Triggered when an animation completes.''' animation_name = "The name of the animation or trigger that completed"
. import exceptions from . import event from ._clad import _clad_to_engine_iface, _clad_to_engine_cozmo class EvtAnimationsLoaded(event.Event): '''Triggered when animations names have been received from the engine''' class EvtAnimationCompleted(action.EvtActionCompleted):
63
64
35
11
52
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
EvtAnimationCompleted
EvtAnimationCompleted
39
41
39
39
6adc5bf58a4c06e7849026deff268fa329a63a57
bigcode/the-stack
train
1b31e78042fe724737c08b5e
train
function
def animation_completed_filter(): '''Creates an :class:`cozmo.event.Filter` to wait specifically for an animation completed event.''' return event.Filter(action.EvtActionCompleted, action=lambda action: isinstance(action, Animation))
def animation_completed_filter():
'''Creates an :class:`cozmo.event.Filter` to wait specifically for an animation completed event.''' return event.Filter(action.EvtActionCompleted, action=lambda action: isinstance(action, Animation))
name, _id) in _clad_to_engine_cozmo.AnimationTrigger.__dict__.items(): if not _name.startswith('_'): trigger = _AnimTrigger(_name, _id) setattr(Triggers, _name, trigger) Triggers.trigger_list.append(trigger) def animation_completed_filter():
64
64
48
5
59
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
animation_completed_filter
animation_completed_filter
220
223
220
220
9ba81f48269db657fa0dc057af6b09f321ab24ab
bigcode/the-stack
train
dec6e7698f710583caf99060
train
class
class Triggers: """Playing an animation trigger causes the game engine play an animation of a particular type. The engine may pick one of a number of actual animations to play based on Cozmo's mood or emotion, or with random weighting. Thus playing the same trigger twice may not result in the exact sa...
class Triggers:
"""Playing an animation trigger causes the game engine play an animation of a particular type. The engine may pick one of a number of actual animations to play based on Cozmo's mood or emotion, or with random weighting. Thus playing the same trigger twice may not result in the exact same underlying an...
): if not self._loaded: logger.debug("%d animations loaded", len(self)) self._loaded = evt self.dispatch_event(EvtAnimationsLoaded) # generate names for each CLAD defined trigger _AnimTrigger = collections.namedtuple('_AnimTrigger', 'name id') class Triggers:
64
64
115
4
60
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
Triggers
Triggers
199
211
199
199
e786967b69076d357b1331f38f27091f13332f3d
bigcode/the-stack
train
094202f4b22beaf1bfe959aa
train
class
class AnimationNames(event.Dispatcher, set): '''Holds the set of animation names (strings) returned from the Engine. Animation names are dynamically retrieved from the engine when the SDK connects to it, unlike :class:`Triggers` which are defined at runtime. ''' def __init__(self, conn, **kw): ...
class AnimationNames(event.Dispatcher, set):
'''Holds the set of animation names (strings) returned from the Engine. Animation names are dynamically retrieved from the engine when the SDK connects to it, unlike :class:`Triggers` which are defined at runtime. ''' def __init__(self, conn, **kw): super().__init__(self, **kw) self...
_count, str(ignore_tracks), self.use_lift_safe) def _encode(self): return _clad_to_engine_iface.PlayAnimationTrigger( trigger=self.trigger.id, numLoops=self.loop_count, useLiftSafe=self.use_lift_safe, ignoreBodyTrack=self.ignore_body_track, ignoreHeadTrack=self.ignore_he...
133
133
444
9
124
rootless4real/cozmo-python-sdk
src/cozmo/anim.py
Python
AnimationNames
AnimationNames
135
193
135
135
f7dcabe8a2d12741865d2fdb76e15a6f6f6332db
bigcode/the-stack
train
06f49d2c133661a013e7c1b0
train
function
def csp_darknet_53(num_classes=1000): return CSP_DarkNet([2, 8, 8, 4], num_classes)
def csp_darknet_53(num_classes=1000):
return CSP_DarkNet([2, 8, 8, 4], num_classes)
self.neck(out) out = self.body(out) out = self.global_pool(out) out = out.view(out.size(0), -1) out = self.fc(out) # return F.softmax(out) return out def csp_darknet_53(num_classes=1000):
64
64
34
13
50
Dou-Yu-xuan/deep-learning-visal
models/ClassicNetwork/csp_darknet.py
Python
csp_darknet_53
csp_darknet_53
103
104
103
103
027618a0fcc1bf217af04d537510b7564c529ab3
bigcode/the-stack
train
1f1b46905ca742a934f88985
train
class
class CSPStem(nn.Module): """ CSP structures including downsampling """ def __init__(self, in_chnls, out_chnls, num_block): super(CSPStem, self).__init__() self.dsample = BN_Conv_Mish(in_chnls, out_chnls, 3, 2, 1) self.trans_0 = BN_Conv_Mish(out_chnls, out_chnls//2, 1, 1, 0)...
class CSPStem(nn.Module):
""" CSP structures including downsampling """ def __init__(self, in_chnls, out_chnls, num_block): super(CSPStem, self).__init__() self.dsample = BN_Conv_Mish(in_chnls, out_chnls, 3, 2, 1) self.trans_0 = BN_Conv_Mish(out_chnls, out_chnls//2, 1, 1, 0) self.trans_1 = BN...
forward(self, x): x = self.dsample(x) out_0 = self.trans_0(x) out_1 = self.trans_1(x) out_1 = self.block(out_1) out = torch.cat((out_0, out_1), 1) out = self.trans_cat(out) return out class CSPStem(nn.Module):
81
81
271
6
74
Dou-Yu-xuan/deep-learning-visal
models/ClassicNetwork/csp_darknet.py
Python
CSPStem
CSPStem
54
74
54
54
9e07c702f1846f0aae6d59198a34fcd8ab91aa12
bigcode/the-stack
train
ca38895273322b672e572e54
train
class
class ResidualBlock(nn.Module): """ basic residual block for CSP-Darknet """ def __init__(self, chnls, inner_chnnls=None): super(ResidualBlock, self).__init__() if inner_chnnls is None: inner_chnnls = chnls self.conv1 = BN_Conv_Mish(chnls, inner_chnnls, 1, 1, 0) #...
class ResidualBlock(nn.Module):
""" basic residual block for CSP-Darknet """ def __init__(self, chnls, inner_chnnls=None): super(ResidualBlock, self).__init__() if inner_chnnls is None: inner_chnnls = chnls self.conv1 = BN_Conv_Mish(chnls, inner_chnnls, 1, 1, 0) # always use samepadding ...
arkNet with pytorch @Cai Yichao 2020_09_30 """ import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary from models.blocks.conv_bn import Mish, BN_Conv_Mish class ResidualBlock(nn.Module):
64
64
189
7
56
Dou-Yu-xuan/deep-learning-visal
models/ClassicNetwork/csp_darknet.py
Python
ResidualBlock
ResidualBlock
13
29
13
13
56e110d598ede29e5f8253d28d81c4dbe862085c
bigcode/the-stack
train
3c7d2fc16268a218d08ddf92
train
class
class CSP_DarkNet(nn.Module): """ CSP-DarkNet """ def __init__(self, num_blocks: object, num_classes=1000) -> object: super(CSP_DarkNet, self).__init__() chnls = [64, 128, 256, 512, 1024] self.conv0 = BN_Conv_Mish(3, 32, 3, 1, 1) # same padding self.neck = CSPFirst(32,...
class CSP_DarkNet(nn.Module):
""" CSP-DarkNet """ def __init__(self, num_blocks: object, num_classes=1000) -> object: super(CSP_DarkNet, self).__init__() chnls = [64, 128, 256, 512, 1024] self.conv0 = BN_Conv_Mish(3, 32, 3, 1, 1) # same padding self.neck = CSPFirst(32, chnls[0]) self.body =...
= self.dsample(x) out_0 = self.trans_0(x) out_1 = self.trans_1(x) out_1 = self.blocks(out_1) out = torch.cat((out_0, out_1), 1) out = self.trans_cat(out) return out class CSP_DarkNet(nn.Module):
76
76
256
8
67
Dou-Yu-xuan/deep-learning-visal
models/ClassicNetwork/csp_darknet.py
Python
CSP_DarkNet
CSP_DarkNet
77
100
77
77
605589467d7a983e069ca89c0bf3094bcf193a6c
bigcode/the-stack
train
4d4cf26dfcab0e65086cb765
train
class
class CSPFirst(nn.Module): """ First CSP Stage """ def __init__(self, in_chnnls, out_chnls): super(CSPFirst, self).__init__() self.dsample = BN_Conv_Mish(in_chnnls, out_chnls, 3, 2, 1) # same padding self.trans_0 = BN_Conv_Mish(out_chnls, out_chnls, 1, 1, 0) self.tran...
class CSPFirst(nn.Module):
""" First CSP Stage """ def __init__(self, in_chnnls, out_chnls): super(CSPFirst, self).__init__() self.dsample = BN_Conv_Mish(in_chnnls, out_chnls, 3, 2, 1) # same padding self.trans_0 = BN_Conv_Mish(out_chnls, out_chnls, 1, 1, 0) self.trans_1 = BN_Conv_Mish(out_chnl...
_chnnls, chnls, 3, 1, 1, bias=False) self.bn = nn.BatchNorm2d(chnls) def forward(self, x): out = self.conv1(x) out = self.conv2(out) out = self.bn(out) + x return Mish()(out) class CSPFirst(nn.Module):
79
79
265
6
73
Dou-Yu-xuan/deep-learning-visal
models/ClassicNetwork/csp_darknet.py
Python
CSPFirst
CSPFirst
32
51
32
32
7ae9368bd15e7fd05361d50e3475e58343a40739
bigcode/the-stack
train
5cdc65f058f9c0502a496d5d
train
class
class MemberTestCase(IntegrationTestCase): def test_fetch_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .channels(sid=...
class MemberTestCase(IntegrationTestCase):
def test_fetch_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.ip_messaging.v1.services(sid="ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .channels(sid="CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ ...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class MemberTestCase(IntegrationT...
93
256
2,219
9
83
fefi95/twilio-python
tests/integration/ip_messaging/v1/service/channel/test_member.py
Python
MemberTestCase
MemberTestCase
15
263
15
16
0d51fe88e762032d21da778141827696c65a78e7
bigcode/the-stack
train
731b66bb76649383796e1b33
train
class
class TestRoutingArgs(object): """Tests for the wsgiorg.routing_args middleware.""" def setup(self): self.mw = RoutingArgsMiddleware() self.request = MockRequest({}) def test_arguments_are_stored(self): """The positional and named arguments should be stored in the environ""...
class TestRoutingArgs(object):
"""Tests for the wsgiorg.routing_args middleware.""" def setup(self): self.mw = RoutingArgsMiddleware() self.request = MockRequest({}) def test_arguments_are_stored(self): """The positional and named arguments should be stored in the environ""" args = ("foo", "bar")...
accompany this distribution. THIS SOFTWARE IS PROVIDED "AS IS" # AND ANY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT # NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST # INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. # #############################################...
108
108
363
6
102
grejppi/django-wsgi
tests/test_middleware.py
Python
TestRoutingArgs
TestRoutingArgs
29
66
29
29
c343b18a8cc6f0df2fe96461872c8143ee64df88
bigcode/the-stack
train
f57b4997654e3086e54e7b4d
train
class
class MockRequest(object): """ Mock Django request class. This way we won't need to set the DJANGO_SETTINGS_MODULE. """ def __init__(self, environ): self.environ = environ
class MockRequest(object):
""" Mock Django request class. This way we won't need to set the DJANGO_SETTINGS_MODULE. """ def __init__(self, environ): self.environ = environ
returned.""" args = ("foo", "bar") kwargs = {'arg': "value"} result = self.mw.process_view(self.request, MOCK_VIEW, args, kwargs) ok_(result is None) #{ Mock objects MOCK_VIEW = lambda request: "response" class MockRequest(object):
64
64
47
5
59
grejppi/django-wsgi
tests/test_middleware.py
Python
MockRequest
MockRequest
75
84
75
75
e3a97a6bebb84b8d24061ddb3fa294554cf0c017
bigcode/the-stack
train
869846934eb2b49050e29fe3
train
class
class PayoutAccountInline(admin.StackedInline): model = PayoutAccount fields = [ "name", "iban", "bank_clearing_number", "payout_notes", ]
class PayoutAccountInline(admin.StackedInline):
model = PayoutAccount fields = [ "name", "iban", "bank_clearing_number", "payout_notes", ]
from django.shortcuts import render from django.urls.base import reverse from django.utils.translation import ugettext_lazy as _ from apps.currency.forms import PaperWalletCreateForm from apps.currency.models import Currency, PayoutAccount from apps.wallet.utils import create_claim_transaction class PayoutAccountInlin...
64
64
45
10
53
ecoo-app/ecoo-backend
apps/currency/admin.py
Python
PayoutAccountInline
PayoutAccountInline
18
25
18
18
27a896555e61781d2c4bf1f67e99896fdfddc5e6
bigcode/the-stack
train
51b454691d87db4d22f197fe
train
class
@admin.register(Currency) class CurrencyAdmin(admin.ModelAdmin): inlines = [PayoutAccountInline] filter_horizontal = ("users",) list_display = [ "name", "token_id", "symbol", "decimals", "allow_minting", "campaign_end", "created_at", ] list_fi...
@admin.register(Currency) class CurrencyAdmin(admin.ModelAdmin):
inlines = [PayoutAccountInline] filter_horizontal = ("users",) list_display = [ "name", "token_id", "symbol", "decimals", "allow_minting", "campaign_end", "created_at", ] list_filter = ["allow_minting", "created_at"] readonly_fields = [ ...
import pytezos from django.contrib import admin from django.contrib.messages import constants as message_constants from django.core.exceptions import ValidationError from django.db import IntegrityError from django.db.models.query import QuerySet from django.http.request import HttpRequest from django.http.response imp...
174
256
1,497
13
161
ecoo-app/ecoo-backend
apps/currency/admin.py
Python
CurrencyAdmin
CurrencyAdmin
28
265
28
29
b5ab3099a199beccf519e79a44b7f72ccd6e66cd
bigcode/the-stack
train
e2d619f58212514fca9f48ec
train
function
def import_data_from_file(fname): # Import a dataset from a CSV file. # :param fname [string] the name of the file contianing the data # :return [array<array<int>>] the CSV data can an aarray matrix of int values ret = [] with open(fname, newline='') as csvfile: reader = csv.reader(csvfile, ...
def import_data_from_file(fname): # Import a dataset from a CSV file. # :param fname [string] the name of the file contianing the data # :return [array<array<int>>] the CSV data can an aarray matrix of int values
ret = [] with open(fname, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: new_row = [] for x in row: new_row.append(int(x)) ret.append(new_row) return ret
import csv def import_data_from_file(fname): # Import a dataset from a CSV file. # :param fname [string] the name of the file contianing the data # :return [array<array<int>>] the CSV data can an aarray matrix of int values
62
64
125
59
2
GeorgeSaussy/gaia2
helpers.py
Python
import_data_from_file
import_data_from_file
4
16
4
7
3867f6b781131482a339295c8818821253930fc8
bigcode/the-stack
train
64ffdb2fd45a0c7f87fdc844
train
class
class ActionTestCase(ActionTestCase): @setup_data_function(setup_func='_setup_test_data') def test_attchment(self): test_action = self.action.create({ 'state': "create_partner", 'name': "Test File Action", }) counter = self.env['res.partner'].sudo().s...
class ActionTestCase(ActionTestCase): @setup_data_function(setup_func='_setup_test_data')
def test_attchment(self): test_action = self.action.create({ 'state': "create_partner", 'name': "Test File Action", }) counter = self.env['res.partner'].sudo().search_count([]) test_action.trigger_actions(self.new_file.ids) self.assertTrue(self....
_data_function from odoo.addons.muk_dms_actions.tests.test_action import ActionTestCase _path = os.path.dirname(os.path.dirname(__file__)) _logger = logging.getLogger(__name__) class ActionTestCase(ActionTestCase): @setup_data_function(setup_func='_setup_test_data')
63
64
101
22
41
marionumza/vocal_v12
muk_web_theme/muk_dms_attachment/tests/test_action.py
Python
ActionTestCase
ActionTestCase
35
45
35
37
4391694573a49e8e177dbb9bbc5a3e749c8e4e03
bigcode/the-stack
train
dcf65f7a3e179716bd5bbf03
train
function
def delete_sns_topic(topic_arn): client = boto3.client('sns', region_name='us-east-1',) client.delete_topic(TopicArn=topic_arn)
def delete_sns_topic(topic_arn):
client = boto3.client('sns', region_name='us-east-1',) client.delete_topic(TopicArn=topic_arn)
': topic_arn, 'Transport': 'SNS', 'Version': '2006-05-05', 'EventTypes': ['AssignmentAbandoned', 'AssignmentReturned', 'AssignmentSubmitted'] }, TestEventType=event_type ) def delete_sns_topic(topic_arn):
64
64
39
9
55
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
delete_sns_topic
delete_sns_topic
425
427
425
425
bd6a31a0c25b55d4e04225424905b8d211cc3146
bigcode/the-stack
train
f488e328678b168b7f3f2752
train
function
def subscribe_to_hits(hit_type_id, is_sandbox, sns_arn): # Get the mturk client and create notifications for our hits client = get_mturk_client(is_sandbox) client.update_notification_settings( HITTypeId=hit_type_id, Notification={ 'Destination': sns_arn, 'Transport': ...
def subscribe_to_hits(hit_type_id, is_sandbox, sns_arn): # Get the mturk client and create notifications for our hits
client = get_mturk_client(is_sandbox) client.update_notification_settings( HITTypeId=hit_type_id, Notification={ 'Destination': sns_arn, 'Transport': 'SNS', 'Version': '2006-05-05', 'EventTypes': ['AssignmentAbandoned', 'AssignmentReturned', ...
, arn) client.set_topic_attributes( TopicArn=arn, AttributeName='Policy', AttributeValue=policy_json ) return arn def subscribe_to_hits(hit_type_id, is_sandbox, sns_arn): # Get the mturk client and create notifications for our hits
64
64
114
30
33
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
subscribe_to_hits
subscribe_to_hits
395
408
395
396
eb03442413d7d8914d684964a421e5b2a0001977
bigcode/the-stack
train
c4500db3be7172b83438eeed
train
function
def create_hit_type(hit_title, hit_description, hit_keywords, hit_reward, assignment_duration_in_seconds, is_sandbox, qualifications=None, auto_approve_delay=4*7*24*3600, # default 4 weeks ): """Create a HIT type to be used to generate ...
def create_hit_type(hit_title, hit_description, hit_keywords, hit_reward, assignment_duration_in_seconds, is_sandbox, qualifications=None, auto_approve_delay=4*7*24*3600, # default 4 weeks ):
"""Create a HIT type to be used to generate HITs of the requested params""" client = get_mturk_client(is_sandbox) # Create a qualification with Locale In('US', 'CA') requirement attached localRequirements = [{ 'QualificationTypeId': '00000000000000000071', 'Comparator': 'In', 'L...
client.disassociate_qualification_from_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, Reason=reason ) def create_hit_type(hit_title, hit_description, hit_keywords, hit_reward, assignment_duration_in_seconds, is_sandbox, qualifica...
84
84
282
53
31
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
create_hit_type
create_hit_type
276
311
276
280
8ff0400332b372339a56520e4468f376e7409517
bigcode/the-stack
train
13bae8f35512a5d125524d2a
train
function
def find_or_create_qualification(qualification_name, description, is_sandbox, must_be_owned=True): """Query amazon to find the existing qualification name, return the Id. If it exists and must_be_owned is true but we don't own it, this prints an error and returns none. If it...
def find_or_create_qualification(qualification_name, description, is_sandbox, must_be_owned=True):
"""Query amazon to find the existing qualification name, return the Id. If it exists and must_be_owned is true but we don't own it, this prints an error and returns none. If it doesn't exist, the qualification is created """ qual_id = find_qualification( qualification_name, is_sandbo...
{} is already owned, ' 'please use a different name for your qualification.' ''.format(qualification_name) ) return False return qualification['QualificationTypeId'] return None def find_or_create_qualification(qualification_name, ...
64
64
192
22
41
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
find_or_create_qualification
find_or_create_qualification
217
241
217
218
6f84cce571f0c05d0f749d364fb1694251435c34
bigcode/the-stack
train
3bc5140c45b67d62f0463fd4
train
function
def give_worker_qualification(worker_id, qualification_id, value=None, is_sandbox=True): """Give a qualification to the given worker""" client = get_mturk_client(is_sandbox) if value is not None: client.associate_qualification_with_worker( QualificationType...
def give_worker_qualification(worker_id, qualification_id, value=None, is_sandbox=True):
"""Give a qualification to the given worker""" client = get_mturk_client(is_sandbox) if value is not None: client.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, IntegerValue=value, SendNotification=False...
(is_sandbox) response = client.create_qualification_type( Name=qualification_name, Description=description, QualificationTypeStatus='Active', ) return response['QualificationType']['QualificationTypeId'] def give_worker_qualification(worker_id, qualification_id, value=None, ...
64
64
125
20
44
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
give_worker_qualification
give_worker_qualification
244
262
244
245
57b2b6ed53b3520671c850ae089de4eb70daff82
bigcode/the-stack
train
9352c3d7e7d5e2242add1940
train
function
def expire_hit(is_sandbox, hit_id): client = get_mturk_client(is_sandbox) # Update expiration to a time in the past, the HIT expires instantly past_time = datetime(2015, 1, 1) client.update_expiration_for_hit(HITId=hit_id, ExpireAt=past_time)
def expire_hit(is_sandbox, hit_id):
client = get_mturk_client(is_sandbox) # Update expiration to a time in the past, the HIT expires instantly past_time = datetime(2015, 1, 1) client.update_expiration_for_hit(HITId=hit_id, ExpireAt=past_time)
not is_sandbox: url_target = 'www' hit_link = 'https://{}.mturk.com/mturk/preview?groupId={}'.format( url_target, hit_type_id ) return hit_link, hit_id def expire_hit(is_sandbox, hit_id):
64
64
74
10
53
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
expire_hit
expire_hit
355
359
355
355
ae0246f32aae015eb829105f4fea803383e0096c
bigcode/the-stack
train
fee7c3d38c022f34314434ac
train
function
def find_qualification(qualification_name, is_sandbox, must_be_owned=True): """Query amazon to find the existing qualification name, return the Id, otherwise return none. If must_be_owned is true, it only returns qualifications owned by the user. Will return False if it finds another's qualification ...
def find_qualification(qualification_name, is_sandbox, must_be_owned=True):
"""Query amazon to find the existing qualification name, return the Id, otherwise return none. If must_be_owned is true, it only returns qualifications owned by the user. Will return False if it finds another's qualification """ client = get_mturk_client(is_sandbox) # Search for the qualifi...
_name='mturk', region_name='us-east-1') return client def delete_qualification(qualification_id, is_sandbox): """Deletes a qualification by id""" client = get_mturk_client(is_sandbox) client.delete_qualification_type( QualificationTypeId=qualification_id ) def find_qualification(qualificat...
83
83
277
17
66
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
find_qualification
find_qualification
178
214
178
178
3703856a0fa6773c5422202708f13ba8d4f6cdca
bigcode/the-stack
train
983c114af240f448cf3084d2
train
function
def setup_sns_topic(task_name, server_url, task_group_id): # Create the topic and subscribe to it so that our server receives notifs client = boto3.client('sns', region_name='us-east-1',) response = client.create_topic(Name=task_name) arn = response['TopicArn'] topic_sub_url = \ '{}/sns_post...
def setup_sns_topic(task_name, server_url, task_group_id): # Create the topic and subscribe to it so that our server receives notifs
client = boto3.client('sns', region_name='us-east-1',) response = client.create_topic(Name=task_name) arn = response['TopicArn'] topic_sub_url = \ '{}/sns_posts?task_group_id={}'.format(server_url, task_group_id) client.subscribe(TopicArn=arn, Protocol='https', Endpoint=topic_sub_url) re...
time in the past, the HIT expires instantly past_time = datetime(2015, 1, 1) client.update_expiration_for_hit(HITId=hit_id, ExpireAt=past_time) def setup_sns_topic(task_name, server_url, task_group_id): # Create the topic and subscribe to it so that our server receives notifs
78
78
261
32
46
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
setup_sns_topic
setup_sns_topic
362
392
362
363
45964e1d7b8725808ab1c562e7ff668cff580949
bigcode/the-stack
train
7a27cdb50df9c0a77283d72e
train
function
def remove_worker_qualification(worker_id, qualification_id, is_sandbox=True, reason=''): """Give a qualification to the given worker""" client = get_mturk_client(is_sandbox) client.disassociate_qualification_from_worker( QualificationTypeId=qualification_id, ...
def remove_worker_qualification(worker_id, qualification_id, is_sandbox=True, reason=''):
"""Give a qualification to the given worker""" client = get_mturk_client(is_sandbox) client.disassociate_qualification_from_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, Reason=reason )
=False ) else: client.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, IntegerValue=1, SendNotification=False ) def remove_worker_qualification(worker_id, qualification_id, ...
64
64
73
20
44
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
remove_worker_qualification
remove_worker_qualification
265
273
265
266
dff9d6ca5b9a6f1e9f15d7b1d27bf2a55538480f
bigcode/the-stack
train
79ba70e6c617a30d83019850
train
function
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and Administr...
def setup_aws_credentials():
try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' ...
reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import boto3 import os import json from datetime import datetime from botocore.exc...
135
135
452
6
128
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
setup_aws_credentials
setup_aws_credentials
23
68
23
23
211d1c6fc3a8a0f963c58e506325fdc27049d999
bigcode/the-stack
train
02ac3deb2776277b28da4c98
train
function
def send_test_notif(topic_arn, event_type): client = get_mturk_client(True) client.send_test_event_notification( Notification={ 'Destination': topic_arn, 'Transport': 'SNS', 'Version': '2006-05-05', 'EventTypes': ['AssignmentAbandoned', 'AssignmentReturned...
def send_test_notif(topic_arn, event_type):
client = get_mturk_client(True) client.send_test_event_notification( Notification={ 'Destination': topic_arn, 'Transport': 'SNS', 'Version': '2006-05-05', 'EventTypes': ['AssignmentAbandoned', 'AssignmentReturned', 'AssignmentSub...
Destination': sns_arn, 'Transport': 'SNS', 'Version': '2006-05-05', 'EventTypes': ['AssignmentAbandoned', 'AssignmentReturned', 'AssignmentSubmitted'] }, Active=True ) def send_test_notif(topic_arn, event_type):
64
64
90
12
52
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
send_test_notif
send_test_notif
411
422
411
411
a4992c0053389b7d9dccb24a2d3d88f674a2fa2c
bigcode/the-stack
train
faefa2cc5f617fdb802c0c8a
train
function
def create_hit_with_hit_type(page_url, hit_type_id, num_assignments, is_sandbox): """Creates the actual HIT given the type and page to direct clients to""" page_url = page_url.replace('&', '&amp;') amazon_ext_url = ( 'http://mechanicalturk.amazonaws.com/' 'AWSMec...
def create_hit_with_hit_type(page_url, hit_type_id, num_assignments, is_sandbox):
"""Creates the actual HIT given the type and page to direct clients to""" page_url = page_url.replace('&', '&amp;') amazon_ext_url = ( 'http://mechanicalturk.amazonaws.com/' 'AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd' ) question_data_struture = ( '<External...
_hit_type( AutoApprovalDelayInSeconds=auto_approve_delay, AssignmentDurationInSeconds=assignment_duration_in_seconds, Reward=str(hit_reward), Title=hit_title, Keywords=hit_keywords, Description=hit_description, QualificationRequirements=localRequirements ) ...
99
99
330
22
76
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
create_hit_with_hit_type
create_hit_with_hit_type
314
352
314
315
97e880f3faf7760af930ccc265be9230f21e252f
bigcode/the-stack
train
26ba94dc144f048362bf9a52
train
function
def check_mturk_balance(balance_needed, is_sandbox): """Checks to see if there is at least balance_needed amount in the requester account, returns True if the balance is greater than balance_needed """ client = get_mturk_client(is_sandbox) # Test that you can connect to the API by checking your...
def check_mturk_balance(balance_needed, is_sandbox):
"""Checks to see if there is at least balance_needed amount in the requester account, returns True if the balance is greater than balance_needed """ client = get_mturk_client(is_sandbox) # Test that you can connect to the API by checking your account balance # In Sandbox this always returns...
= 0 if payment_opt['type'] == 'reward': mult = 1.2 total_cost = \ payment_opt['num_total_assignments'] * payment_opt['reward'] * mult elif payment_opt['type'] == 'bonus': total_cost = payment_opt['amount'] * 1.2 return total_cost def check_mturk_balance(balance_needed, i...
90
90
301
13
76
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
check_mturk_balance
check_mturk_balance
100
132
100
100
bae3cf0b35152c9c4abb3f4d9ee6e66c61944304
bigcode/the-stack
train
9ffbbbe8345f11ffcad7faae
train
function
def delete_qualification(qualification_id, is_sandbox): """Deletes a qualification by id""" client = get_mturk_client(is_sandbox) client.delete_qualification_type( QualificationTypeId=qualification_id )
def delete_qualification(qualification_id, is_sandbox):
"""Deletes a qualification by id""" client = get_mturk_client(is_sandbox) client.delete_qualification_type( QualificationTypeId=qualification_id )
.us-east-1.amazonaws.com' ) # Region is always us-east-1 if not is_sandbox: client = \ boto3.client(service_name='mturk', region_name='us-east-1') return client def delete_qualification(qualification_id, is_sandbox):
64
64
49
12
51
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
delete_qualification
delete_qualification
170
175
170
170
de34ad486c58faf7b1144fb83404416b1941a2f8
bigcode/the-stack
train
f4a676e2591b38dfe582374f
train
function
def create_hit_config(task_description, unique_worker, is_sandbox): """Writes a HIT config to file""" mturk_submit_url = 'https://workersandbox.mturk.com/mturk/externalSubmit' if not is_sandbox: mturk_submit_url = 'https://www.mturk.com/mturk/externalSubmit' hit_config = { 'task_descript...
def create_hit_config(task_description, unique_worker, is_sandbox):
"""Writes a HIT config to file""" mturk_submit_url = 'https://workersandbox.mturk.com/mturk/externalSubmit' if not is_sandbox: mturk_submit_url = 'https://www.mturk.com/mturk/externalSubmit' hit_config = { 'task_description': task_description, 'is_sandbox': is_sandbox, 'm...
urk account. Please go ' 'to https://requester.mturk.com/account and increase your balance ' 'to at least ${}, and then try again.'.format(balance_needed)) return False else: return True def create_hit_config(task_description, unique_worker, is_sandbox):
64
64
190
14
49
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
create_hit_config
create_hit_config
135
151
135
135
b2c685828530c865f83b864a27cfc6f228d81758
bigcode/the-stack
train
cd950b279ea93bf0bbc023cd
train
function
def calculate_mturk_cost(payment_opt): """MTurk Pricing: https://requester.mturk.com/pricing 20% fee on the reward and bonus amount (if any) you pay Workers. HITs with 10 or more assignments will be charged an additional 20% fee on the reward you pay Workers. Example payment_opt format for paying r...
def calculate_mturk_cost(payment_opt):
"""MTurk Pricing: https://requester.mturk.com/pricing 20% fee on the reward and bonus amount (if any) you pay Workers. HITs with 10 or more assignments will be charged an additional 20% fee on the reward you pay Workers. Example payment_opt format for paying reward: { 'type': 'reward', ...
aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print('AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path )) os.environ['AWS_PROFILE'] = aws_profile_name def calculate_mturk_cost(paymen...
68
68
229
9
58
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
calculate_mturk_cost
calculate_mturk_cost
71
97
71
71
2315c390f3dc739fab32c7eae10e7162dfe0f6ce
bigcode/the-stack
train
583f57e9c22b9a1c5277cde2
train
function
def get_mturk_client(is_sandbox): """Returns the appropriate mturk client given sandbox option""" global client if client is None: client = boto3.client( service_name='mturk', region_name='us-east-1', endpoint_url='https://mturk-requester-sandbox.us-east-1.amazona...
def get_mturk_client(is_sandbox):
"""Returns the appropriate mturk client given sandbox option""" global client if client is None: client = boto3.client( service_name='mturk', region_name='us-east-1', endpoint_url='https://mturk-requester-sandbox.us-east-1.amazonaws.com' ) # Region...
.path.join(parent_dir, 'hit_config.json') if os.path.exists(hit_config_file_path): os.remove(hit_config_file_path) with open(hit_config_file_path, 'w') as hit_config_file: hit_config_file.write(json.dumps(hit_config)) def get_mturk_client(is_sandbox):
64
64
119
10
54
manailin/facebookresearch-ParlAI
parlai/mturk/core/mturk_utils.py
Python
get_mturk_client
get_mturk_client
154
167
154
154
9da4c791521ee44e137a662ee02d2549d71886b7
bigcode/the-stack
train
08daa40aae738a8784729e7f
train
class
class Executor(object): def __init__(self, ip, port, filename, delay, wait, exe, icon, hide, persist): self.ip = ip self.exe = exe self.port = port self.hide = hide self.wait = wait self.icon = icon self.binary = b'' self.delay = delay ...
class Executor(object):
def __init__(self, ip, port, filename, delay, wait, exe, icon, hide, persist): self.ip = ip self.exe = exe self.port = port self.hide = hide self.wait = wait self.icon = icon self.binary = b'' self.delay = delay self.persist = persist ...
# Date: 09/01/2018 # Author: Pure-L0G1C # Description: Execute creator import os import sys import zlib import shlex import shutil import smtplib import tempfile from lib.file import File from lib.args import Args from lib.aes import CryptoAES try: from PyInstaller import __main__ as pyi, is...
114
229
766
4
110
FlatL1neAPT/Loki
builder/builder.py
Python
Executor
Executor
22
120
22
23
2e45cbb8a697175f01dcd131fa7c8e86ac69b14b
bigcode/the-stack
train
2e7739aa6904207e45533ec3
train
class
class ChangeCommitMessageTask(Task): def __init__(self, revision_key, priority=NORMAL_PRIORITY): super(ChangeCommitMessageTask, self).__init__(priority) self.revision_key = revision_key def __repr__(self): return '<ChangeCommitMessageTask %s>' % (self.revision_key,) def __eq__(self...
class ChangeCommitMessageTask(Task):
def __init__(self, revision_key, priority=NORMAL_PRIORITY): super(ChangeCommitMessageTask, self).__init__(priority) self.revision_key = revision_key def __repr__(self): return '<ChangeCommitMessageTask %s>' % (self.revision_key,) def __eq__(self, other): if (other.__class__...
session.delete(cp) # Inside db session for rollback ret = sync.post('changes/%s/revisions/%s/cherrypick' % (cp.revision.change.id, cp.revision.commit), data) if ret and 'id' in ret: sync.submitTask(SyncChange...
81
81
272
7
74
pierreprinetti/hubtty
hubtty/sync.py
Python
ChangeCommitMessageTask
ChangeCommitMessageTask
1,203
1,231
1,203
1,203
80f84e6b99abe099d9629dc0067529384ed0bfea
bigcode/the-stack
train
3e0d8c91e54179de03f8ff0b
train
class
class RebaseChangeTask(Task): def __init__(self, change_key, priority=NORMAL_PRIORITY): super(RebaseChangeTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<RebaseChangeTask %s>' % (self.change_key,) def __eq__(self, other): if (other._...
class RebaseChangeTask(Task):
def __init__(self, change_key, priority=NORMAL_PRIORITY): super(RebaseChangeTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<RebaseChangeTask %s>' % (self.change_key,) def __eq__(self, other): if (other.__class__ == self.__class__ and...
(add=add, remove=remove) change.pending_hashtags = False # Inside db session for rollback sync.post('changes/%s/hashtags' % (change.id,), data) sync.submitTask(SyncChangeTask(change.id, priority=self.priority)) class RebaseChangeTask(Task):
64
64
187
7
57
pierreprinetti/hubtty
hubtty/sync.py
Python
RebaseChangeTask
RebaseChangeTask
1,090
1,111
1,090
1,090
6f093c460b8592a58619880e16f8222a867d60d4
bigcode/the-stack
train
8cc8c382c9d300e29f7e008b
train
class
class CheckRevisionsTask(Task): def __init__(self, project_key, force_fetch=False, priority=NORMAL_PRIORITY): super(CheckRevisionsTask, self).__init__(priority) self.project_key = project_key self.force_fetch = force_fetch def __repr__(self): return '<CheckRevis...
class CheckRevisionsTask(Task):
def __init__(self, project_key, force_fetch=False, priority=NORMAL_PRIORITY): super(CheckRevisionsTask, self).__init__(priority) self.project_key = project_key self.force_fetch = force_fetch def __repr__(self): return '<CheckRevisionsTask %s>' % (self.project_ke...
except gitrepo.GitCloneError: missing = True if missing or app.fetch_missing_refs: sync.submitTask( CheckRevisionsTask(project.key, force_fetch=app.fetch_missing_refs, ...
81
82
275
7
75
pierreprinetti/hubtty
hubtty/sync.py
Python
CheckRevisionsTask
CheckRevisionsTask
984
1,020
984
984
17bb85d52038cd093b22b270677e591835f816b3
bigcode/the-stack
train
38940f1425e70451150ffe0a
train
class
class SyncOwnAccountTask(Task): def __repr__(self): return '<SyncOwnAccountTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return False def run(self, sync): app = sync.app remote = sync.get('users/' + app.config.username...
class SyncOwnAccountTask(Task):
def __repr__(self): return '<SyncOwnAccountTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return False def run(self, sync): app = sync.app remote = sync.get('users/' + app.config.username) sync.account_id = remo...
.results = [] def complete(self, success): self.succeeded = success self.event.set() def wait(self, timeout=None): self.event.wait(timeout) return self.succeeded def __eq__(self, other): raise NotImplementedError() class SyncOwnAccountTask(Task):
64
64
145
7
57
pierreprinetti/hubtty
hubtty/sync.py
Python
SyncOwnAccountTask
SyncOwnAccountTask
187
206
187
187
9998f8435c04d4a8c4301cd206fcbfbbdc2b4a6b
bigcode/the-stack
train
6134a0a49412d74f8634c256
train
class
class ProjectAddedEvent(UpdateEvent): def __repr__(self): return '<ProjectAddedEvent project_key:%s>' % ( self.project_key,) def __init__(self, project): self.project_key = project.key
class ProjectAddedEvent(UpdateEvent):
def __repr__(self): return '<ProjectAddedEvent project_key:%s>' % ( self.project_key,) def __init__(self, project): self.project_key = project.key
parent = session.getCommitBySha(revision.parent) if parent: related_change_keys.add(parent.change.key) for child in session.getCommitsByParent(revision.commit): related_change_keys.add(child.change.key) self.related_change_keys = related_change_keys class...
64
64
50
7
56
pierreprinetti/hubtty
hubtty/sync.py
Python
ProjectAddedEvent
ProjectAddedEvent
133
139
133
133
0ea90dc664ceddf3ec22e6ebef83b8a7353be3a1
bigcode/the-stack
train
30fec9d9ac9e8ef60e602046
train
class
class VacuumDatabaseTask(Task): def __init__(self, priority=NORMAL_PRIORITY): super(VacuumDatabaseTask, self).__init__(priority) def __repr__(self): return '<VacuumDatabaseTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return F...
class VacuumDatabaseTask(Task):
def __init__(self, priority=NORMAL_PRIORITY): super(VacuumDatabaseTask, self).__init__(priority) def __repr__(self): return '<VacuumDatabaseTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return False def run(self, sync): ...
s ref %s" % ( change.project.name, change_ref)) try: repo.deleteRef(change_ref) except OSError as e: if e.errno not in [errno.EISDIR, errno.EPERM]: raise session.delete(change) class VacuumDatabaseTask(Task):
64
64
106
6
58
pierreprinetti/hubtty
hubtty/sync.py
Python
VacuumDatabaseTask
VacuumDatabaseTask
1,377
1,392
1,377
1,377
ed65a31f8ca80cd6027726f01a22f975f0d6db5b
bigcode/the-stack
train
256397e8487ea8f4303bdf0d
train
class
class UploadReviewsTask(Task): def __repr__(self): return '<UploadReviewsTask>' def __eq__(self, other): if (other.__class__ == self.__class__): return True return False def run(self, sync): app = sync.app with app.db.getSession() as session: ...
class UploadReviewsTask(Task):
def __repr__(self): return '<UploadReviewsTask>' def __eq__(self, other): if (other.__class__ == self.__class__): return True return False def run(self, sync): app = sync.app with app.db.getSession() as session: for c in session.getPendingHas...
.revisions: if repo.checkCommits([revision.parent, revision.commit]): to_sync.add(change.change_id) else: to_sync.add(change.change_id) for change_id in to_sync: sync.submitTask(SyncChangeTask(change_id, ...
72
72
242
6
66
pierreprinetti/hubtty
hubtty/sync.py
Python
UploadReviewsTask
UploadReviewsTask
1,022
1,047
1,022
1,022
2a8492f4e1a092214370fd921b20d4ce5756722b
bigcode/the-stack
train
31412c36efa16d0cbe6428aa
train
class
class SyncSubscribedProjectBranchesTask(Task): def __repr__(self): return '<SyncSubscribedProjectBranchesTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return False def run(self, sync): app = sync.app with app.db.getSes...
class SyncSubscribedProjectBranchesTask(Task):
def __repr__(self): return '<SyncSubscribedProjectBranchesTask>' def __eq__(self, other): if other.__class__ == self.__class__: return True return False def run(self, sync): app = sync.app with app.db.getSession() as session: projects = sessi...
s", name) local[name].delete() for name in remote_keys-local_keys: project = session.createProject(name, description=remote_desc[name]) self.log.info("Created project %s", project.name) self.resu...
64
64
108
8
56
pierreprinetti/hubtty
hubtty/sync.py
Python
SyncSubscribedProjectBranchesTask
SyncSubscribedProjectBranchesTask
266
280
266
266
c257b5ea5f3e4999aecfdbf2fa5330c9288dccd2
bigcode/the-stack
train
cdb32b77772c34fe9dd6c9b4
train
class
class Task(object): def __init__(self, priority=NORMAL_PRIORITY): self.log = logging.getLogger('hubtty.sync') self.priority = priority self.succeeded = None self.event = threading.Event() self.tasks = [] self.results = [] def complete(self, success): self...
class Task(object):
def __init__(self, priority=NORMAL_PRIORITY): self.log = logging.getLogger('hubtty.sync') self.priority = priority self.succeeded = None self.event = threading.Event() self.tasks = [] self.results = [] def complete(self, success): self.succeeded = success...
.status_changed) def __init__(self, change): self.project_key = change.project.key self.change_key = change.key self.related_change_keys = set() self.review_flag_changed = False self.status_changed = False self.held_changed = False class Task(object):
64
64
112
4
59
pierreprinetti/hubtty
hubtty/sync.py
Python
Task
Task
167
185
167
167
8e7467728ef33e902083770b522fc1fa9733f200
bigcode/the-stack
train
c1be8c92c8ad8e8d1a1fac3f
train
class
class SyncQueriedChangesTask(Task): def __init__(self, query_name, query, priority=NORMAL_PRIORITY): super(SyncQueriedChangesTask, self).__init__(priority) self.query_name = query_name self.query = query def __repr__(self): return '<SyncQueriedChangesTask %s>' % self.query_name ...
class SyncQueriedChangesTask(Task):
def __init__(self, query_name, query, priority=NORMAL_PRIORITY): super(SyncQueriedChangesTask, self).__init__(priority) self.query_name = query_name self.query = query def __repr__(self): return '<SyncQueriedChangesTask %s>' % self.query_name def __eq__(self, other): ...
)) class SetProjectUpdatedTask(Task): def __init__(self, project_key, updated, priority=NORMAL_PRIORITY): super(SetProjectUpdatedTask, self).__init__(priority) self.project_key = project_key self.updated = updated def __repr__(self): return '<SetProjectUpdatedTask %s %s>' % (se...
176
176
589
8
167
pierreprinetti/hubtty
hubtty/sync.py
Python
SyncQueriedChangesTask
SyncQueriedChangesTask
401
460
401
401
5fbdca0f52af5c89970e1bbaea823fbfe76a925a
bigcode/the-stack
train
3ec93792d39c097bbebe9c78
train
class
class SetProjectUpdatedTask(Task): def __init__(self, project_key, updated, priority=NORMAL_PRIORITY): super(SetProjectUpdatedTask, self).__init__(priority) self.project_key = project_key self.updated = updated def __repr__(self): return '<SetProjectUpdatedTask %s %s>' % (self.p...
class SetProjectUpdatedTask(Task):
def __init__(self, project_key, updated, priority=NORMAL_PRIORITY): super(SetProjectUpdatedTask, self).__init__(priority) self.project_key = project_key self.updated = updated def __repr__(self): return '<SetProjectUpdatedTask %s %s>' % (self.project_key, self.updated) def ...
) for c in changes: sync.submitTask(SyncChangeTask(c['pull_request']['url'].split('repos/')[1], priority=self.priority)) for key in self.project_keys: sync.submitTask(SetProjectUpdatedTask(key, now, priority=self.priority)) class SetProjectUpdatedTask(Task):
64
64
167
7
57
pierreprinetti/hubtty
hubtty/sync.py
Python
SetProjectUpdatedTask
SetProjectUpdatedTask
379
399
379
379
4aa942ef285d9cbe6123095e4356efa39fe835fb
bigcode/the-stack
train
a111c120235d509ed1f4ea04
train
class
class PruneChangeTask(Task): def __init__(self, key, priority=NORMAL_PRIORITY): super(PruneChangeTask, self).__init__(priority) self.key = key def __repr__(self): return '<PruneChangeTask %s>' % (self.key,) def __eq__(self, other): if (other.__class__ == self.__class__ and ...
class PruneChangeTask(Task):
def __init__(self, key, priority=NORMAL_PRIORITY): super(PruneChangeTask, self).__init__(priority) self.key = key def __repr__(self): return '<PruneChangeTask %s>' % (self.key,) def __eq__(self, other): if (other.__class__ == self.__class__ and other.key == self...
not self.age: return app = sync.app with app.db.getSession() as session: for change in session.getChanges('status:closed age:%s' % self.age): t = PruneChangeTask(change.key, priority=self.priority) self.tasks.append(t) sync.submitT...
97
97
325
7
90
pierreprinetti/hubtty
hubtty/sync.py
Python
PruneChangeTask
PruneChangeTask
1,338
1,375
1,338
1,338
97ec3e10e7f3c992ae767d5cb939ed1bc7f54006
bigcode/the-stack
train
07f20e43496a030a394dcecb
train
class
class SyncSubscribedProjectsTask(Task): def __repr__(self): return '<SyncSubscribedProjectsTask>' def __eq__(self, other): if (other.__class__ == self.__class__): return True return False def run(self, sync): app = sync.app with app.db.getSession() as se...
class SyncSubscribedProjectsTask(Task):
def __repr__(self): return '<SyncSubscribedProjectsTask>' def __eq__(self, other): if (other.__class__ == self.__class__): return True return False def run(self, sync): app = sync.app with app.db.getSession() as session: keys = [p.key for p i...
("Deleted branch %s from project %s in local DB.", name, project.name) for name in remote_branches-local_branches: project.createBranch(name) self.log.info("Added branch %s to project %s in local DB.", name, project.name) class SyncSubscribedProjectsTask(Task):
64
64
133
7
57
pierreprinetti/hubtty
hubtty/sync.py
Python
SyncSubscribedProjectsTask
SyncSubscribedProjectsTask
317
333
317
317
294dce19e08de091e634ad8ca30bb441ddaeca06
bigcode/the-stack
train
90fa0f45c361fa92c84cd643
train
class
class ChangeStarredTask(Task): def __init__(self, change_key, priority=NORMAL_PRIORITY): super(ChangeStarredTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<ChangeStarredTask %s>' % (self.change_key,) def __eq__(self, other): if (othe...
class ChangeStarredTask(Task):
def __init__(self, change_key, priority=NORMAL_PRIORITY): super(ChangeStarredTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<ChangeStarredTask %s>' % (self.change_key,) def __eq__(self, other): if (other.__class__ == self.__class__ a...
change = session.getChange(self.change_key) change.pending_rebase = False # Inside db session for rollback sync.post('changes/%s/rebase' % (change.id,), {}) sync.submitTask(SyncChangeTask(change.id, priority=self.priority)) class ChangeStarredTask(Task):
64
64
216
7
57
pierreprinetti/hubtty
hubtty/sync.py
Python
ChangeStarredTask
ChangeStarredTask
1,113
1,138
1,113
1,113
d6c06bf47a05d89272b1a724102466fb9d3f9b91
bigcode/the-stack
train
f0e480757cdde45cb3829ae0
train
class
class ChangeStatusTask(Task): def __init__(self, change_key, priority=NORMAL_PRIORITY): super(ChangeStatusTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<ChangeStatusTask %s>' % (self.change_key,) def __eq__(self, other): if (other._...
class ChangeStatusTask(Task):
def __init__(self, change_key, priority=NORMAL_PRIORITY): super(ChangeStatusTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<ChangeStatusTask %s>' % (self.change_key,) def __eq__(self, other): if (other.__class__ == self.__class__ and...
_key) if change.starred: sync.put('accounts/self/starred.changes/%s' % (change.id,), data={}) else: sync.delete('accounts/self/starred.changes/%s' % (change.id,), data={}) change.pending_starred = Fa...
84
84
281
6
78
pierreprinetti/hubtty
hubtty/sync.py
Python
ChangeStatusTask
ChangeStatusTask
1,140
1,173
1,140
1,140
8b99132e25fa0b6b5b56ebf918720e389a1de272
bigcode/the-stack
train
edf54b5930991a2a5690d75e
train
class
class SetHashtagsTask(Task): def __init__(self, change_key, priority=NORMAL_PRIORITY): super(SetHashtagsTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<SetHashtagsTask %s>' % (self.change_key,) def __eq__(self, other): if (other.__cl...
class SetHashtagsTask(Task):
def __init__(self, change_key, priority=NORMAL_PRIORITY): super(SetHashtagsTask, self).__init__(priority) self.change_key = change_key def __repr__(self): return '<SetHashtagsTask %s>' % (self.change_key,) def __eq__(self, other): if (other.__class__ == self.__class__ and ...
(): sync.submitTask(ChangeStarredTask(c.key, self.priority)) for c in session.getPendingCherryPicks(): sync.submitTask(SendCherryPickTask(c.key, self.priority)) for r in session.getPendingCommitMessages(): sync.submitTask(ChangeCommitMessageTask(r....
95
95
319
7
88
pierreprinetti/hubtty
hubtty/sync.py
Python
SetHashtagsTask
SetHashtagsTask
1,049
1,088
1,049
1,049
994ac9a2870acdded7cca37117d9066ff50c36d9
bigcode/the-stack
train