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
90a21894792e0db23322018c
train
class
class ParseBinaryMultiplyIntegerInteger(ParseBinaryOperator, ParseInteger): def __init__(self, left: ParseInteger, right: ParseInteger): super().__init__(left, right) self._left = left self._right = right def __repr__(self) -> str: return f"Multiply({self._left!r}, {self._right!r...
class ParseBinaryMultiplyIntegerInteger(ParseBinaryOperator, ParseInteger):
def __init__(self, left: ParseInteger, right: ParseInteger): super().__init__(left, right) self._left = left self._right = right def __repr__(self) -> str: return f"Multiply({self._left!r}, {self._right!r})" def eval(self, vars: Dict[str, ParseAtom]) -> int: return se...
__(left, ParseCastIntegerFloat(right)) class ParseBinaryMultiplyIntegerFloat(ParseBinaryMultiplyFloatFloat): def __init__(self, left: ParseInteger, right: ParseFloat): super().__init__(ParseCastIntegerFloat(left), right) class ParseBinaryMultiplyIntegerInteger(ParseBinaryOperator, ParseInteger):
64
64
114
13
51
jesopo/scpl
scpl/parser/operators/multiply.py
Python
ParseBinaryMultiplyIntegerInteger
ParseBinaryMultiplyIntegerInteger
22
30
22
22
5fd4040852e7acdb87a003718991a4fca214c256
bigcode/the-stack
train
96807f4b16d0898b090745c1
train
class
class CarInterface(CarInterfaceBase): @staticmethod def compute_gb(accel, speed): return float(accel) / 3.0 @staticmethod def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # pylint: disable=dangerous-default-value ret = CarInterfaceBase.get_std_params(candidate, fingerprint) ...
class CarInterface(CarInterfaceBase): @staticmethod
def compute_gb(accel, speed): return float(accel) / 3.0 @staticmethod def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # pylint: disable=dangerous-default-value ret = CarInterfaceBase.get_std_params(candidate, fingerprint) ret.carName = "hyundai" ret.safetyModel = car....
#!/usr/bin/env python3 from cereal import car from selfdrive.config import Conversions as CV from selfdrive.car.hyundai.values import CAR from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint from selfdrive.car.interfaces import CarInterfaceBase from common.dp_common imp...
104
256
4,482
11
92
R6auto/op1
selfdrive/car/hyundai/interface.py
Python
CarInterface
CarInterface
10
297
10
12
9e0f2db63879b13ac5f37d2ca93887c22d4761e2
bigcode/the-stack
train
505e6e990e88e28b63578bea
train
function
def ct_plot(t=False): def get_ct(): countries = [] flag = False while True: clear() print("Step 1: Choose the countries you want to plot\n") print("Country -- The country to be plotted") print("Now supported multiple countries! You can put any ...
def ct_plot(t=False):
def get_ct(): countries = [] flag = False while True: clear() print("Step 1: Choose the countries you want to plot\n") print("Country -- The country to be plotted") print("Now supported multiple countries! You can put any countries in a list") ...
from data_miner import plot_tally from helper import clear, is_valid_date from helper import print_error as stderr from json import load from sys import exit from pathlib import Path countries = None try: path = Path(__file__).absolute().parents[1].joinpath("cache", "countries.json") with open(path) as f: ...
201
256
1,337
6
195
MunchDev/EpidemicVisualiser
src/console_application.py
Python
ct_plot
ct_plot
32
192
32
32
d94fcbf5225783463f0a9e78fc74878a7948793d
bigcode/the-stack
train
dbf85d8cc7639d5a28c327f7
train
function
def welcome_screen_option(options): i = None while True: clear() print("Welcome to Epidemic Simulator -- Console version") print("What do you like to do? (-1 to exit)\n") for i, option in zip(range(len(options)), options): print("({0}) {1}".format(i + 1, option)) ...
def welcome_screen_option(options):
i = None while True: clear() print("Welcome to Epidemic Simulator -- Console version") print("What do you like to do? (-1 to exit)\n") for i, option in zip(range(len(options)), options): print("({0}) {1}".format(i + 1, option)) i = input("Your option > ") ...
continue if type(opt) != str: data[p] = opt() print(data) plot_tally(data["c"], data["d"], data["t"], scale=data["s"], plot_type=data["p"], transpose=t) return 0 def welcome_screen_option(options):
64
64
134
6
57
MunchDev/EpidemicVisualiser
src/console_application.py
Python
welcome_screen_option
welcome_screen_option
195
210
195
195
6101c1d7122b062c7d465873f2c23abc0140cdcb
bigcode/the-stack
train
6ed3e16a1020619725dcdcbf
train
function
def main(): welcome_options = [ "Show country tally plot", "Tranposed version of the above" ] def w_plot(): return ct_plot(True) f = [ct_plot, w_plot] option = welcome_screen_option(welcome_options) return f[option]()
def main():
welcome_options = [ "Show country tally plot", "Tranposed version of the above" ] def w_plot(): return ct_plot(True) f = [ct_plot, w_plot] option = welcome_screen_option(welcome_options) return f[option]()
(path) as f: countries = f.readlines() if countries == None or len(countries) == 0: stderr("Unable to load countries! Aborting...") input("Press Enter to continue...") raise RuntimeError("Unable to load countries!") except: exit(-1) def main():
64
64
62
3
61
MunchDev/EpidemicVisualiser
src/console_application.py
Python
main
main
21
29
21
21
415485dd075252e788b53ddffbceb1af4d8ab078
bigcode/the-stack
train
5ca28250797e6ea06d1d598e
train
function
def _dataset_from_backend_dataset( backend_ds, filename_or_obj, engine, chunks, cache, overwrite_encoded_chunks, **extra_tokens, ): if not (isinstance(chunks, (int, dict)) or chunks is None): if chunks != "auto": raise ValueError( "chunks must be an in...
def _dataset_from_backend_dataset( backend_ds, filename_or_obj, engine, chunks, cache, overwrite_encoded_chunks, **extra_tokens, ):
if not (isinstance(chunks, (int, dict)) or chunks is None): if chunks != "auto": raise ValueError( "chunks must be an int, dict, 'auto', or None. " "Instead found %s. " % chunks ) _protect_dataset_variables_inplace(backend_ds, cache) if chunks...
_encoded_chunks, name_prefix=name_prefix, token=token, ) ds = backend_ds._replace(variables) return ds def _dataset_from_backend_dataset( backend_ds, filename_or_obj, engine, chunks, cache, overwrite_encoded_chunks, **extra_tokens, ):
66
66
220
36
29
observingClouds/xarray
xarray/backends/apiv2.py
Python
_dataset_from_backend_dataset
_dataset_from_backend_dataset
64
100
64
72
5d794e94d4c716c722ad96f71ae3df09a633dfcb
bigcode/the-stack
train
e2a9fbbbf5921b6856873cd7
train
function
def _protect_dataset_variables_inplace(dataset, cache): for name, variable in dataset.variables.items(): if name not in variable.dims: # no need to protect IndexVariable objects data = indexing.CopyOnWriteArray(variable._data) if cache: data = indexing.Mem...
def _protect_dataset_variables_inplace(dataset, cache):
for name, variable in dataset.variables.items(): if name not in variable.dims: # no need to protect IndexVariable objects data = indexing.CopyOnWriteArray(variable._data) if cache: data = indexing.MemoryCachedArray(data) variable.data = data
import os from ..core import indexing from ..core.dataset import _get_chunk, _maybe_chunk from ..core.utils import is_remote_uri from . import plugins def _protect_dataset_variables_inplace(dataset, cache):
47
64
71
11
35
observingClouds/xarray
xarray/backends/apiv2.py
Python
_protect_dataset_variables_inplace
_protect_dataset_variables_inplace
9
16
9
9
7d06d7fb9952aa5b73f9f762b4db9fd81b43a222
bigcode/the-stack
train
185c0cead9aebaca43277abe
train
function
def open_dataset( filename_or_obj, *, engine=None, chunks=None, cache=None, decode_cf=None, mask_and_scale=None, decode_times=None, decode_timedelta=None, use_cftime=None, concat_characters=None, decode_coords=None, drop_variables=None, backend_kwargs=None, **...
def open_dataset( filename_or_obj, *, engine=None, chunks=None, cache=None, decode_cf=None, mask_and_scale=None, decode_times=None, decode_timedelta=None, use_cftime=None, concat_characters=None, decode_coords=None, drop_variables=None, backend_kwargs=None, **...
"""Open and decode a dataset from a file or file-like object. Parameters ---------- filename_or_obj : str, Path, file-like or DataStore Strings and Path objects are interpreted as a path to a netCDF file or an OpenDAP URL and opened with python-netCDF4, unless the filename ends ...
if chunks is None: ds = backend_ds else: ds = _chunk_ds( backend_ds, filename_or_obj, engine, chunks, overwrite_encoded_chunks, **extra_tokens, ) ds.set_close(backend_ds._close) # Ensure source filename alw...
256
256
1,717
77
178
observingClouds/xarray
xarray/backends/apiv2.py
Python
open_dataset
open_dataset
112
286
112
128
3aca55ad5a9587cca5b3e7b65c0065dd88c8e11a
bigcode/the-stack
train
ccdd61afa33118b8b30ebb51
train
function
def _resolve_decoders_kwargs(decode_cf, open_backend_dataset_parameters, **decoders): for d in list(decoders): if decode_cf is False and d in open_backend_dataset_parameters: decoders[d] = False if decoders[d] is None: decoders.pop(d) return decoders
def _resolve_decoders_kwargs(decode_cf, open_backend_dataset_parameters, **decoders):
for d in list(decoders): if decode_cf is False and d in open_backend_dataset_parameters: decoders[d] = False if decoders[d] is None: decoders.pop(d) return decoders
stored in dataset object (GH issue #2550) if "source" not in ds.encoding: if isinstance(filename_or_obj, str): ds.encoding["source"] = filename_or_obj return ds def _resolve_decoders_kwargs(decode_cf, open_backend_dataset_parameters, **decoders):
64
64
69
19
44
observingClouds/xarray
xarray/backends/apiv2.py
Python
_resolve_decoders_kwargs
_resolve_decoders_kwargs
103
109
103
103
efd54416e09f8c1ff11407a573a3443926d92394
bigcode/the-stack
train
3b066ea2dff1f1ac3d0ecad9
train
function
def _chunk_ds( backend_ds, filename_or_obj, engine, chunks, overwrite_encoded_chunks, **extra_tokens, ): from dask.base import tokenize mtime = _get_mtime(filename_or_obj) token = tokenize(filename_or_obj, mtime, engine, chunks, **extra_tokens) name_prefix = "open_dataset-%s" % ...
def _chunk_ds( backend_ds, filename_or_obj, engine, chunks, overwrite_encoded_chunks, **extra_tokens, ):
from dask.base import tokenize mtime = _get_mtime(filename_or_obj) token = tokenize(filename_or_obj, mtime, engine, chunks, **extra_tokens) name_prefix = "open_dataset-%s" % token variables = {} for name, var in backend_ds.variables.items(): var_chunks = _get_chunk(var, chunks) ...
: path = None if path and not is_remote_uri(path): mtime = os.path.getmtime(filename_or_obj) return mtime def _chunk_ds( backend_ds, filename_or_obj, engine, chunks, overwrite_encoded_chunks, **extra_tokens, ):
64
64
164
31
32
observingClouds/xarray
xarray/backends/apiv2.py
Python
_chunk_ds
_chunk_ds
35
61
35
42
92da7a966fca7b26bf952b7eb8b71c5e5969b659
bigcode/the-stack
train
ed01d9b265c3ed8ca553b00d
train
function
def _get_mtime(filename_or_obj): # if passed an actual file path, augment the token with # the file modification time mtime = None try: path = os.fspath(filename_or_obj) except TypeError: path = None if path and not is_remote_uri(path): mtime = os.path.getmtime(filename...
def _get_mtime(filename_or_obj): # if passed an actual file path, augment the token with # the file modification time
mtime = None try: path = os.fspath(filename_or_obj) except TypeError: path = None if path and not is_remote_uri(path): mtime = os.path.getmtime(filename_or_obj) return mtime
Variable objects data = indexing.CopyOnWriteArray(variable._data) if cache: data = indexing.MemoryCachedArray(data) variable.data = data def _get_mtime(filename_or_obj): # if passed an actual file path, augment the token with # the file modification time
64
64
86
30
33
observingClouds/xarray
xarray/backends/apiv2.py
Python
_get_mtime
_get_mtime
19
32
19
21
6a30d93578ec1be5abe0e17ac6975099b7d5e5dd
bigcode/the-stack
train
a087fb5b391736dddab7fccd
train
function
def new_filters_from_events(events: List[DecodedEvent]) -> RaidenContractFilter: new_filter = RaidenContractFilter( token_network_addresses={ entry.event_data["args"]["token_network_address"] for entry in events if entry.event_data["event"] == EVENT_TOKEN_NETWORK_CREATED ...
def new_filters_from_events(events: List[DecodedEvent]) -> RaidenContractFilter:
new_filter = RaidenContractFilter( token_network_addresses={ entry.event_data["args"]["token_network_address"] for entry in events if entry.event_data["event"] == EVENT_TOKEN_NETWORK_CREATED }, ignore_secret_registry_until_channel_found=True, ) for...
(log_event["address"]), event_data=data, block_number=log_event["blockNumber"], block_hash=BlockHash(log_event["blockHash"]), transaction_hash=TransactionHash(log_event["transactionHash"]), ) def new_filters_from_events(events: List[DecodedEvent]) -> RaidenContractFilter:
64
64
162
18
46
tirkarthi/raiden
raiden/blockchain/events.py
Python
new_filters_from_events
new_filters_from_events
228
245
228
228
b837667cfa1be13ac936b416b47e4d450695072f
bigcode/the-stack
train
8d9d8ff06cda0137717093bd
train
function
def get_all_netting_channel_events( proxy_manager: ProxyManager, token_network_address: TokenNetworkAddress, netting_channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]:...
def get_all_netting_channel_events( proxy_manager: ProxyManager, token_network_address: TokenNetworkAddress, netting_channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]:...
"""Helper to get all events of a NettingChannelContract.""" filter_args = get_filter_args_for_all_events_from_channel( token_network_address=token_network_address, channel_identifier=netting_channel_identifier, contract_manager=contract_manager, from_block=from_block, to...
def get_all_netting_channel_events( proxy_manager: ProxyManager, token_network_address: TokenNetworkAddress, netting_channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]:...
77
64
195
77
0
tirkarthi/raiden
raiden/blockchain/events.py
Python
get_all_netting_channel_events
get_all_netting_channel_events
125
150
125
132
a7ab2bc3f1036a5f48e202a117ef1c16718fbe27
bigcode/the-stack
train
aeacedc0a83873d3f7c4cd33
train
function
def sort_events(events: List[DecodedEvent]) -> None: events.sort(key=lambda e: e.block_number)
def sort_events(events: List[DecodedEvent]) -> None:
events.sort(key=lambda e: e.block_number)
ating_contract), set() ).add(entry.event_data["args"]["channel_identifier"]) # Now that we have a channel, we need to watch for registered secrets. new_filter.ignore_secret_registry_until_channel_found = False return new_filter def sort_events(events: List[DecodedEvent]) -> None...
64
64
24
13
50
tirkarthi/raiden
raiden/blockchain/events.py
Python
sort_events
sort_events
248
249
248
248
700e82e7ad87e5324763c991384a59dbce0a0598
bigcode/the-stack
train
21688d7a5e3ee37b62953a85
train
class
@dataclass(frozen=True) class DecodedEvent: """A confirmed event with the data decoded to conform with Raiden's internals. Raiden prefers bytes for addresses and hashes, and it uses snake_case as a naming convention. Instances of this class are created at the edges of the code base to conform with the ...
@dataclass(frozen=True) class DecodedEvent:
"""A confirmed event with the data decoded to conform with Raiden's internals. Raiden prefers bytes for addresses and hashes, and it uses snake_case as a naming convention. Instances of this class are created at the edges of the code base to conform with the internal data types, i.e. this type describe...
_SERVICE, EVENT_TOKEN_NETWORK_CREATED, ChannelEvent, ) from raiden_contracts.contract_manager import ContractManager log = structlog.get_logger(__name__) # `new_filter` uses None to signal the absence of topics filters ALL_EVENTS = None @dataclass(frozen=True) class DecodedEvent:
64
64
140
11
52
tirkarthi/raiden
raiden/blockchain/events.py
Python
DecodedEvent
DecodedEvent
59
74
59
60
209936cf985909f4f3c2bd9459034a18d51a71e6
bigcode/the-stack
train
70130397d3d9ecc56214b78f
train
function
def verify_block_number(number: BlockIdentifier, argname: str) -> None: if isinstance(number, int) and (number < 0 or number > UINT64_MAX): raise InvalidBlockNumberInput( "Provided block number {} for {} is invalid. Has to be in the range " "of [0, UINT64_MAX]".format(number, argname...
def verify_block_number(number: BlockIdentifier, argname: str) -> None:
if isinstance(number, int) and (number < 0 or number > UINT64_MAX): raise InvalidBlockNumberInput( "Provided block number {} for {} is invalid. Has to be in the range " "of [0, UINT64_MAX]".format(number, argname) )
can confirm it in its storage. """ polled_block_number: BlockNumber polled_block_hash: BlockHash polled_block_gas_limit: BlockGasLimit events: List[DecodedEvent] def verify_block_number(number: BlockIdentifier, argname: str) -> None:
64
64
81
17
47
tirkarthi/raiden
raiden/blockchain/events.py
Python
verify_block_number
verify_block_number
89
94
89
89
8399ab03e7f1945ed09ae9678cd1027a1c4c5cc8
bigcode/the-stack
train
9972b715437bad218492541d
train
function
def decode_raiden_event_to_internal( abi: ABI, chain_id: ChainID, log_event: LogReceipt ) -> DecodedEvent: """Enforce the sandwich encoding. Converts the JSON RPC/web3 data types to the internal representation. Note:: This function must only on confirmed data. """ # Note: All addresses...
def decode_raiden_event_to_internal( abi: ABI, chain_id: ChainID, log_event: LogReceipt ) -> DecodedEvent:
"""Enforce the sandwich encoding. Converts the JSON RPC/web3 data types to the internal representation. Note:: This function must only on confirmed data. """ # Note: All addresses inside the event_data must be decoded. decoded_event = decode_event(abi, log_event) if not decoded_e...
Manager, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]: # pragma: no unittest """Helper to get all events of a NettingChannelContract.""" filter_args = get_filter_args_for_all_events_from_channel( token_network_address=token_ne...
188
188
628
31
157
tirkarthi/raiden
raiden/blockchain/events.py
Python
decode_raiden_event_to_internal
decode_raiden_event_to_internal
153
225
153
155
b5cd5943c0d5b1114a0c66b2685ea1fb1d7109f4
bigcode/the-stack
train
31808f739201f975fad0f917
train
class
@dataclass(frozen=True) class PollResult: """Result of a poll request. The block number is provided so that the caller can confirm it in its storage. """ polled_block_number: BlockNumber polled_block_hash: BlockHash polled_block_gas_limit: BlockGasLimit events: List[DecodedEvent]
@dataclass(frozen=True) class PollResult:
"""Result of a poll request. The block number is provided so that the caller can confirm it in its storage. """ polled_block_number: BlockNumber polled_block_hash: BlockHash polled_block_gas_limit: BlockGasLimit events: List[DecodedEvent]
IO boundaries to conform with the sandwich encoding. """ chain_id: ChainID block_number: BlockNumber block_hash: BlockHash transaction_hash: TransactionHash originating_contract: Address event_data: Dict[str, Any] @dataclass(frozen=True) class PollResult:
64
64
76
10
54
tirkarthi/raiden
raiden/blockchain/events.py
Python
PollResult
PollResult
77
86
77
78
62395cffcdba22ec9103b62b067da3388d6e8d7f
bigcode/the-stack
train
aa81d75b2f9d8e68b7c92bf3
train
function
def get_contract_events( proxy_manager: ProxyManager, abi: ABI, contract_address: Address, topics: Optional[List[str]] = ALL_EVENTS, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]: """Query the blockchain for all events of the...
def get_contract_events( proxy_manager: ProxyManager, abi: ABI, contract_address: Address, topics: Optional[List[str]] = ALL_EVENTS, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]:
"""Query the blockchain for all events of the smart contract at `contract_address` that match the filters `topics`, `from_block`, and `to_block`. """ verify_block_number(from_block, "from_block") verify_block_number(to_block, "to_block") events = proxy_manager.client.get_filter_events( ...
) def get_contract_events( proxy_manager: ProxyManager, abi: ABI, contract_address: Address, topics: Optional[List[str]] = ALL_EVENTS, from_block: BlockIdentifier = GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier = BLOCK_ID_LATEST, ) -> List[Dict]:
65
65
219
64
1
tirkarthi/raiden
raiden/blockchain/events.py
Python
get_contract_events
get_contract_events
97
122
97
104
f7f46529ca69d0a96d608ba5a360af6f48d31a0f
bigcode/the-stack
train
c8c898097dcc2ff240e2a4be
train
class
class BlockchainEvents: def __init__( self, web3: Web3, chain_id: ChainID, contract_manager: ContractManager, last_fetched_block: BlockNumber, event_filter: RaidenContractFilter, block_batch_size_config: BlockBatchSizeConfig, node_address: Address, ...
class BlockchainEvents:
def __init__( self, web3: Web3, chain_id: ChainID, contract_manager: ContractManager, last_fetched_block: BlockNumber, event_filter: RaidenContractFilter, block_batch_size_config: BlockBatchSizeConfig, node_address: Address, ) -> None: self...
return DecodedEvent( chain_id=chain_id, originating_contract=to_canonical_address(log_event["address"]), event_data=data, block_number=log_event["blockNumber"], block_hash=BlockHash(log_event["blockHash"]), transaction_hash=TransactionHash(log_event["transactionHash"]), ...
256
256
3,340
4
252
tirkarthi/raiden
raiden/blockchain/events.py
Python
BlockchainEvents
BlockchainEvents
252
593
252
252
4ad2401f86b49cc75c05d51584ff60699975f895
bigcode/the-stack
train
ad0092a73094e578a9180724
train
class
class Repl(object): def __init__(self, prompt_message, lexer, parser): self.lexer = lexer self.parser = parser self.message = prompt_message self.create_repl() def create_repl(self): is_repl_launched = True while is_repl_launched: try: ...
class Repl(object):
def __init__(self, prompt_message, lexer, parser): self.lexer = lexer self.parser = parser self.message = prompt_message self.create_repl() def create_repl(self): is_repl_launched = True while is_repl_launched: try: repl_inpu...
class Repl(object):
5
64
120
5
0
cvython/vython1
repl.py
Python
Repl
Repl
1
17
1
1
ee22f440c87d236c4f9fe1d1e209c022581489ea
bigcode/the-stack
train
f83500577da3adcdf9fbe09c
train
class
class CustomersApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() ...
class CustomersApi(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = ap...
# coding: utf-8 """ Modern Logic Api Manage and version your customer decision logic outside of your codebase # noqa: E501 OpenAPI spec version: 1.0.0 Contact: info@usemodernlogic.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import im...
118
256
4,003
5
112
latourette359/modern_logic_client
modern_logic_client/api/customers_api.py
Python
CustomersApi
CustomersApi
23
514
23
23
13c76205bff7bde93f8fcadfbf8e47f36474bdcc
bigcode/the-stack
train
dbf863096da6a308f85b7c4d
train
class
class Trie: "Prototypes: Constructor, Build, PrintAll, autosuggestion, serialize, deserialize " # Constructor; Establishes the root node of the entire Tree/Trie def __init__(self): self.root = TrieNode() def __str__(self): return "{"+str(self.root)+"\n}" # This funct...
class Trie:
"Prototypes: Constructor, Build, PrintAll, autosuggestion, serialize, deserialize " # Constructor; Establishes the root node of the entire Tree/Trie def __init__(self): self.root = TrieNode() def __str__(self): return "{"+str(self.root)+"\n}" # This function builds th...
the Trie class TrieNode: def __init__(self): self.children = defaultdict(TrieNode) self.confirmation = False self.parent = None def __str__(self): ans = ["\t"] for child in self.children.keys(): childnode = self.children[child] add = str(...
256
256
960
3
253
19690ao/Instantutor
server/algos/SearchBar/Trie.py
Python
Trie
Trie
38
120
38
39
469c99f35a872dd326e28fd3d50425ce44332f3a
bigcode/the-stack
train
edab8a837b0cc70343d18915
train
function
def main(): obj = Trie() obj.deserialize() #print(obj) """ f = open("test.json", "w") f.write(str(obj)) f.close() """ """ print(obj) with open("sample.json", "w") as outfile: outfile.write(str(obj)) outfile.close() """ if len(sys.argv) == 2: print(","....
def main():
obj = Trie() obj.deserialize() #print(obj) """ f = open("test.json", "w") f.write(str(obj)) f.close() """ """ print(obj) with open("sample.json", "w") as outfile: outfile.write(str(obj)) outfile.close() """ if len(sys.argv) == 2: print(",".join(obj.aut...
.keys(): curr.children[key] = self.convertdict(trie[key][1], curr) #print(trie) #print(self) f.close() # Driver for now, when there are more Tries for different search bars I will fix this. Too lazy for now def main():
64
64
118
3
60
19690ao/Instantutor
server/algos/SearchBar/Trie.py
Python
main
main
124
142
124
124
c1de5205d7aab8170c88331a5883d028a8ab475e
bigcode/the-stack
train
0244af4df69fec6ec77153e3
train
class
class TrieNode: def __init__(self): self.children = defaultdict(TrieNode) self.confirmation = False self.parent = None def __str__(self): ans = ["\t"] for child in self.children.keys(): childnode = self.children[child] add = str(self.child...
class TrieNode:
def __init__(self): self.children = defaultdict(TrieNode) self.confirmation = False self.parent = None def __str__(self): ans = ["\t"] for child in self.children.keys(): childnode = self.children[child] add = str(self.children[child]) ...
to increase the speed of the search querry for the user we can look at confirming if the search is correct, return a boolean value and retrieving a proper profile from the database # ---------------------------------------------------------------------------------------------------------------------------------# from...
64
64
190
4
59
19690ao/Instantutor
server/algos/SearchBar/Trie.py
Python
TrieNode
TrieNode
9
32
9
9
c5968a788df2614b6017e8274989a065d06b78fc
bigcode/the-stack
train
81e1e1fc20e8e81b8e235241
train
function
def run_pert(run_index): df_test = PP.get_params_for_specific_runs([run_index]) pars = df_test.iloc[0, :] print(pars) exit() this_run_ind = int(df_test.iloc[0, :].run) # rp = PP._get_RPs(pars, NDoses=101) # grid_default = RunGrid(rp.fung_parms).run(rp.grid_conf) filename = f"./param_...
def run_pert(run_index):
df_test = PP.get_params_for_specific_runs([run_index]) pars = df_test.iloc[0, :] print(pars) exit() this_run_ind = int(df_test.iloc[0, :].run) # rp = PP._get_RPs(pars, NDoses=101) # grid_default = RunGrid(rp.fung_parms).run(rp.grid_conf) filename = f"./param_scan/outputs/failed/grid_...
""" Plot failed SR run """ import pickle from plotting.paper_figs import DoseSpaceScenarioDouble from model.simulator import RunGrid from param_scan.fns.config import config_rand from param_scan.fns.post_process import PostProcess def run_pert(run_index):
57
90
301
7
49
nt409/HRHR
src/figs/failed_run_pert.py
Python
run_pert
run_pert
13
45
13
13
8e9d3c21d50880a0d19731000ce9b06d78290a7d
bigcode/the-stack
train
4d3e6af1e78069bd95122844
train
function
def leiadinheiro(msg): n = str(input(msg))
def leiadinheiro(msg):
n = str(input(msg))
def leiadinheiro(msg):
7
64
14
7
0
LucasHenrique-dev/Exercicios-Python
Desafios/desafio111/utilidadesCev/dado/__init__.py
Python
leiadinheiro
leiadinheiro
1
2
1
1
5b65c38a78f672438deb3a79a861c49bcf9f547b
bigcode/the-stack
train
c5bbb98f391a9390d25b91f1
train
class
class Show(ShowBase): def __call__(self, block=None): from matplotlib._pylab_helpers import Gcf managers = Gcf.get_all_fig_managers() if not managers: return interactive = is_interactive() for manager in managers: manager.show() # plt....
class Show(ShowBase):
def __call__(self, block=None): from matplotlib._pylab_helpers import Gcf managers = Gcf.get_all_fig_managers() if not managers: return interactive = is_interactive() for manager in managers: manager.show() # plt.figure adds an event wh...
json.load(fid)['version'] cursors_str = { cursors.HAND: 'pointer', cursors.POINTER: 'default', cursors.SELECT_REGION: 'crosshair', cursors.MOVE: 'move', cursors.WAIT: 'wait' } class Show(ShowBase):
64
64
163
6
58
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
Show
Show
39
61
39
40
761f3d0d71ccbc26d6a689c1d647101b53442a38
bigcode/the-stack
train
f5162056e553183c4752d036
train
class
class Canvas(DOMWidget, FigureCanvasWebAggCore): _model_module = Unicode('jupyter-matplotlib').tag(sync=True) _model_module_version = Unicode(js_semver).tag(sync=True) _model_name = Unicode('MPLCanvasModel').tag(sync=True) _view_module = Unicode('jupyter-matplotlib').tag(sync=True) _view_module_ve...
class Canvas(DOMWidget, FigureCanvasWebAggCore):
_model_module = Unicode('jupyter-matplotlib').tag(sync=True) _model_module_version = Unicode(js_semver).tag(sync=True) _model_name = Unicode('MPLCanvasModel').tag(sync=True) _view_module = Unicode('jupyter-matplotlib').tag(sync=True) _view_module_version = Unicode(js_semver).tag(sync=True) _vie...
.figure.get_figwidth() * self.canvas.figure.get_dpi()) # Scale size to match widget on HiPD monitors width = pwidth / self.canvas._dpi_ratio data = "<img src='data:image/png;base64,{0}' width={1}/>" data = data.format(b64encode(buf.getvalue()).decode('utf-8'), width) ...
251
251
839
12
239
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
Canvas
Canvas
158
258
158
159
ee1d5320520c2e9ef14b75083c9876190163addd
bigcode/the-stack
train
2be5256b77c893e1d7a70927
train
function
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ figure_class = kwargs.pop('FigureClass', Figure) this_fig = figure_class(*args, **kwargs) return new_figure_manager_given_figure(num, this_fig)
def new_figure_manager(num, *args, **kwargs):
""" Create a new figure manager instance """ figure_class = kwargs.pop('FigureClass', Figure) this_fig = figure_class(*args, **kwargs) return new_figure_manager_given_figure(num, this_fig)
_sockets = [self.canvas] def show(self): if self.canvas._closed: self.canvas._closed = False display(self.canvas) else: self.canvas.draw_idle() def destroy(self): self.canvas.close() def new_figure_manager(num, *args, **kwargs):
64
64
63
13
51
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
new_figure_manager
new_figure_manager
279
285
279
279
3ad2756cd738440c5231f3a81196d328a4c5ef84
bigcode/the-stack
train
2417b9f5b4fde0019fec7378
train
function
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ from matplotlib._pylab_helpers import Gcf def closer(event): Gcf.destroy(num) canvas = Canvas(figure) if 'nbagg.transparent' in rcParams and rcParams['nbagg.transpar...
def new_figure_manager_given_figure(num, figure):
""" Create a new figure manager instance for the given figure. """ from matplotlib._pylab_helpers import Gcf def closer(event): Gcf.destroy(num) canvas = Canvas(figure) if 'nbagg.transparent' in rcParams and rcParams['nbagg.transparent']: figure.patch.set_alpha(0) manag...
kwargs): """ Create a new figure manager instance """ figure_class = kwargs.pop('FigureClass', Figure) this_fig = figure_class(*args, **kwargs) return new_figure_manager_given_figure(num, this_fig) def new_figure_manager_given_figure(num, figure):
64
64
124
12
52
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
new_figure_manager_given_figure
new_figure_manager_given_figure
288
308
288
288
c76b99a45dffeecc8182b0cdfe4801fa5b7ebec4
bigcode/the-stack
train
13db8f8970a570f4a5af2c1c
train
function
def connection_info(): """ Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager...
def connection_info():
""" Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure ...
Gcf._activeQue.remove(manager) show = Show() def draw_if_interactive(): import matplotlib._pylab_helpers as pylab_helpers if is_interactive(): manager = pylab_helpers.Gcf.get_active() if manager is not None: manager.show() def connection_info():
64
64
143
4
60
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
connection_info
connection_info
76
92
76
76
0b4cdfed558cf6b45d3f20368be1e3b95f6917a9
bigcode/the-stack
train
29bf4c7d458c951a904bd77a
train
class
class FigureManager(FigureManagerWebAgg): ToolbarCls = Toolbar def __init__(self, canvas, num): FigureManagerWebAgg.__init__(self, canvas, num) self.web_sockets = [self.canvas] def show(self): if self.canvas._closed: self.canvas._closed = False display(self....
class FigureManager(FigureManagerWebAgg):
ToolbarCls = Toolbar def __init__(self, canvas, num): FigureManagerWebAgg.__init__(self, canvas, num) self.web_sockets = [self.canvas] def show(self): if self.canvas._closed: self.canvas._closed = False display(self.canvas) else: self.can...
*args, **kwargs): return TimerTornado(*args, **kwargs) def start_event_loop(self, timeout): FigureCanvasBase.start_event_loop_default(self, timeout) def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) class FigureManager(FigureManagerWebAgg):
64
64
94
9
55
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
FigureManager
FigureManager
261
276
261
261
ccd706123819ff9d6bb6e66ee5424f712c6a66a8
bigcode/the-stack
train
abc145ce63266ea86a94615a
train
class
class Toolbar(DOMWidget, NavigationToolbar2WebAgg): _model_module = Unicode('jupyter-matplotlib').tag(sync=True) _model_module_version = Unicode(js_semver).tag(sync=True) _model_name = Unicode('ToolbarModel').tag(sync=True) _view_module = Unicode('jupyter-matplotlib').tag(sync=True) _view_module_v...
class Toolbar(DOMWidget, NavigationToolbar2WebAgg):
_model_module = Unicode('jupyter-matplotlib').tag(sync=True) _model_module_version = Unicode(js_semver).tag(sync=True) _model_name = Unicode('ToolbarModel').tag(sync=True) _view_module = Unicode('jupyter-matplotlib').tag(sync=True) _view_module_version = Unicode(js_semver).tag(sync=True) _view_...
if manager is not None: manager.show() def connection_info(): """ Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ from matplotlib._pylab_helpers import Gcf result = [] for...
166
166
555
12
154
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
Toolbar
Toolbar
95
155
95
96
aed978643c0068c798ba6ace8cab6e636bfdd944
bigcode/the-stack
train
52492a888a5f9e5ed099e795
train
function
def draw_if_interactive(): import matplotlib._pylab_helpers as pylab_helpers if is_interactive(): manager = pylab_helpers.Gcf.get_active() if manager is not None: manager.show()
def draw_if_interactive():
import matplotlib._pylab_helpers as pylab_helpers if is_interactive(): manager = pylab_helpers.Gcf.get_active() if manager is not None: manager.show()
# shown, even in non-interactive mode. if hasattr(manager, '_cidgcf'): manager.canvas.mpl_disconnect(manager._cidgcf) if not interactive and manager in Gcf._activeQue: Gcf._activeQue.remove(manager) show = Show() def draw_if_interactive():
64
64
47
6
58
eo1989/VectorBTanalysis
.venv/lib/python3.8/site-packages/ipympl/backend_nbagg.py
Python
draw_if_interactive
draw_if_interactive
67
73
67
67
b830c05001dcd9e8203f347ab8aff9f494034edf
bigcode/the-stack
train
6811a62e8efd18c95e4e7fb1
train
function
@raises(Exception) def test_005_writes_to_node2_fail(): node2.run_sql_query("INSERT INTO t1 VALUES (3)")
@raises(Exception) def test_005_writes_to_node2_fail():
node2.run_sql_query("INSERT INTO t1 VALUES (3)")
="secondary") assert node1.wait_until_state(target_state="primary") def test_004_read_from_secondary(): results = node2.run_sql_query("SELECT * FROM t1") assert results == [(1,), (2,)] @raises(Exception) def test_005_writes_to_node2_fail():
64
64
30
15
49
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_005_writes_to_node2_fail
test_005_writes_to_node2_fail
49
51
49
50
a3107ffa4879ee2b4b57ff238de84bf7acc5d268
bigcode/the-stack
train
b3fede1ed2ff81cb8097a6d4
train
function
def test_009_start_node1_again(): node1.run() assert node2.wait_until_state(target_state="primary") assert node1.wait_until_state(target_state="secondary")
def test_009_start_node1_again():
node1.run() assert node2.wait_until_state(target_state="primary") assert node1.wait_until_state(target_state="secondary")
_node2_succeed(): node2.run_sql_query("INSERT INTO t1 VALUES (4)") results = node2.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)] def test_009_start_node1_again():
64
64
38
9
55
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_009_start_node1_again
test_009_start_node1_again
78
81
78
78
618eeec13b27df8cd46ce6c77147665e81475ee2
bigcode/the-stack
train
b783e97ed782a417b639879a
train
function
def test_006_maintenance(): print() print("Enabling maintenance on node2") node2.enable_maintenance() assert node2.wait_until_state(target_state="maintenance") node2.stop_postgres() node1.run_sql_query("INSERT INTO t1 VALUES (3)") print("Disabling maintenance on node2") node2.disable_ma...
def test_006_maintenance():
print() print("Enabling maintenance on node2") node2.enable_maintenance() assert node2.wait_until_state(target_state="maintenance") node2.stop_postgres() node1.run_sql_query("INSERT INTO t1 VALUES (3)") print("Disabling maintenance on node2") node2.disable_maintenance() assert node2...
results = node2.run_sql_query("SELECT * FROM t1") assert results == [(1,), (2,)] @raises(Exception) def test_005_writes_to_node2_fail(): node2.run_sql_query("INSERT INTO t1 VALUES (3)") def test_006_maintenance():
63
64
113
7
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_006_maintenance
test_006_maintenance
53
65
53
53
9215ba90d753fd81308ab7ba00f61d663ce3cea8
bigcode/the-stack
train
6d8b9a109fc4eca7bbd8ea71
train
function
def setup_module(): global cluster cluster = pgautofailover.Cluster()
def setup_module():
global cluster cluster = pgautofailover.Cluster()
import pgautofailover_utils as pgautofailover from nose.tools import * cluster = None monitor = None node1 = None node2 = None node3 = None def setup_module():
46
64
18
4
41
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
setup_module
setup_module
10
12
10
10
9c98ca71caddd0cce804060aa31d683da62e7212
bigcode/the-stack
train
3e63be155dbf3598d4f7beb5
train
function
def test_007_fail_primary(): print() print("Injecting failure of node1") node1.fail() assert node2.wait_until_state(target_state="wait_primary")
def test_007_fail_primary():
print() print("Injecting failure of node1") node1.fail() assert node2.wait_until_state(target_state="wait_primary")
1 VALUES (3)") print("Disabling maintenance on node2") node2.disable_maintenance() assert node2.wait_until_pg_is_running() assert node2.wait_until_state(target_state="secondary") assert node1.wait_until_state(target_state="primary") def test_007_fail_primary():
64
64
38
7
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_007_fail_primary
test_007_fail_primary
67
71
67
67
1d33f9ec83afbf164ec50344ce144ba46e2247fc
bigcode/the-stack
train
86ed2f2550ae4ac6212ec89a
train
function
def test_000_create_monitor(): global monitor monitor = cluster.create_monitor("/tmp/basic/monitor") monitor.run()
def test_000_create_monitor():
global monitor monitor = cluster.create_monitor("/tmp/basic/monitor") monitor.run()
ailover from nose.tools import * cluster = None monitor = None node1 = None node2 = None node3 = None def setup_module(): global cluster cluster = pgautofailover.Cluster() def teardown_module(): cluster.destroy() def test_000_create_monitor():
64
64
27
7
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_000_create_monitor
test_000_create_monitor
17
20
17
17
a99884380ceeb8f366cd3dab2e3f44902df291a0
bigcode/the-stack
train
0e45ad5aeb7e954866db6faf
train
function
def test_015_multiple_manual_failover_verify_replication_slot_removed(): count_repl_slots = "select count(*) from pg_replication_slots" print() print("Calling pgautofailover.failover() on the monitor") monitor.failover() assert node3.wait_until_state(target_state="primary") assert node2.wait_un...
def test_015_multiple_manual_failover_verify_replication_slot_removed():
count_repl_slots = "select count(*) from pg_replication_slots" print() print("Calling pgautofailover.failover() on the monitor") monitor.failover() assert node3.wait_until_state(target_state="primary") assert node2.wait_until_state(target_state="secondary") node2_replication_slots = node2.r...
_new_secondary(): global node3 node3 = cluster.create_datanode("/tmp/basic/node3") node3.create() node3.run() assert node3.wait_until_state(target_state="secondary") assert node2.wait_until_state(target_state="primary") def test_015_multiple_manual_failover_verify_replication_slot_removed():
71
71
239
14
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_015_multiple_manual_failover_verify_replication_slot_removed
test_015_multiple_manual_failover_verify_replication_slot_removed
112
132
112
112
c166144153909a8403c6edb43d2ae8d8c6bfc980
bigcode/the-stack
train
9d212ed07bff537e7a5594dc
train
function
def test_001_init_primary(): global node1 node1 = cluster.create_datanode("/tmp/basic/node1") node1.create() node1.run() assert node1.wait_until_state(target_state="single")
def test_001_init_primary():
global node1 node1 = cluster.create_datanode("/tmp/basic/node1") node1.create() node1.run() assert node1.wait_until_state(target_state="single")
3 = None def setup_module(): global cluster cluster = pgautofailover.Cluster() def teardown_module(): cluster.destroy() def test_000_create_monitor(): global monitor monitor = cluster.create_monitor("/tmp/basic/monitor") monitor.run() def test_001_init_primary():
64
64
49
7
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_001_init_primary
test_001_init_primary
22
27
22
22
fa58d4622708bdc1993dbec959d0859676a9e634
bigcode/the-stack
train
d0eda6ede964bd983f817a40
train
function
def test_004_read_from_secondary(): results = node2.run_sql_query("SELECT * FROM t1") assert results == [(1,), (2,)]
def test_004_read_from_secondary():
results = node2.run_sql_query("SELECT * FROM t1") assert results == [(1,), (2,)]
_secondary(): global node2 node2 = cluster.create_datanode("/tmp/basic/node2") node2.create() node2.run() assert node2.wait_until_state(target_state="secondary") assert node1.wait_until_state(target_state="primary") def test_004_read_from_secondary():
64
64
34
8
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_004_read_from_secondary
test_004_read_from_secondary
45
47
45
45
463aee555922e2dfa70ef9e66f3a222cbb5bb2da
bigcode/the-stack
train
3c7107453a1bba854db23057
train
function
@raises(Exception) def test_011_writes_to_node1_fail(): node1.run_sql_query("INSERT INTO t1 VALUES (3)")
@raises(Exception) def test_011_writes_to_node1_fail():
node1.run_sql_query("INSERT INTO t1 VALUES (3)")
(target_state="secondary") def test_010_read_from_new_secondary(): results = node1.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)] @raises(Exception) def test_011_writes_to_node1_fail():
64
64
30
15
49
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_011_writes_to_node1_fail
test_011_writes_to_node1_fail
87
89
87
88
cae9eada6cf11bef4d0c75943104987c94aaab9d
bigcode/the-stack
train
6a449f4d38d9c62fd608b144
train
function
def test_003_init_secondary(): global node2 node2 = cluster.create_datanode("/tmp/basic/node2") node2.create() node2.run() assert node2.wait_until_state(target_state="secondary") assert node1.wait_until_state(target_state="primary")
def test_003_init_secondary():
global node2 node2 = cluster.create_datanode("/tmp/basic/node2") node2.create() node2.run() assert node2.wait_until_state(target_state="secondary") assert node1.wait_until_state(target_state="primary")
node1.stop_postgres() assert node1.wait_until_pg_is_running() def test_002_create_t1(): node1.run_sql_query("CREATE TABLE t1(a int)") node1.run_sql_query("INSERT INTO t1 VALUES (1), (2)") def test_003_init_secondary():
63
64
61
7
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_003_init_secondary
test_003_init_secondary
37
43
37
37
41a9359b4fffe0ebe36902668277f687333ed7a6
bigcode/the-stack
train
c3cab187aee8439557daae49
train
function
def test_016_drop_primary(): node2.drop() assert not node2.pg_is_running() assert node3.wait_until_state(target_state="single")
def test_016_drop_primary():
node2.drop() assert not node2.pg_is_running() assert node3.wait_until_state(target_state="single")
node2_replication_slots = node2.run_sql_query(count_repl_slots); assert node2_replication_slots == [(1,)] node3_replication_slots = node3.run_sql_query(count_repl_slots); assert node3_replication_slots == [(0,)] def test_016_drop_primary():
64
64
33
7
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_016_drop_primary
test_016_drop_primary
134
137
134
134
fae47bb3ac2c6d48889927aafc3309b704c01b4f
bigcode/the-stack
train
8dcf1689a164c9fb43d75a33
train
function
def test_001_stop_postgres(): node1.stop_postgres() assert node1.wait_until_pg_is_running()
def test_001_stop_postgres():
node1.stop_postgres() assert node1.wait_until_pg_is_running()
/monitor") monitor.run() def test_001_init_primary(): global node1 node1 = cluster.create_datanode("/tmp/basic/node1") node1.create() node1.run() assert node1.wait_until_state(target_state="single") def test_001_stop_postgres():
64
64
25
8
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_001_stop_postgres
test_001_stop_postgres
29
31
29
29
e565763b45d05861c7dc01d41929f37fa92f667f
bigcode/the-stack
train
9ce6b1738fbfc71ba983cf9d
train
function
def test_013_drop_secondary(): node1.run() assert node1.wait_until_state(target_state="secondary") node1.drop() assert not node1.pg_is_running() assert node2.wait_until_state(target_state="single")
def test_013_drop_secondary():
node1.run() assert node1.wait_until_state(target_state="secondary") node1.drop() assert not node1.pg_is_running() assert node2.wait_until_state(target_state="single")
)] @raises(Exception) def test_011_writes_to_node1_fail(): node1.run_sql_query("INSERT INTO t1 VALUES (3)") def test_012_fail_secondary(): node1.fail() assert node2.wait_until_state(target_state="wait_primary") def test_013_drop_secondary():
64
64
50
7
57
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_013_drop_secondary
test_013_drop_secondary
95
100
95
95
77e7897fa85658fb8d375ba21701466378de9328
bigcode/the-stack
train
1d6fb7c672a752bb1310c45a
train
function
def test_008_writes_to_node2_succeed(): node2.run_sql_query("INSERT INTO t1 VALUES (4)") results = node2.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)]
def test_008_writes_to_node2_succeed():
node2.run_sql_query("INSERT INTO t1 VALUES (4)") results = node2.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)]
secondary") assert node1.wait_until_state(target_state="primary") def test_007_fail_primary(): print() print("Injecting failure of node1") node1.fail() assert node2.wait_until_state(target_state="wait_primary") def test_008_writes_to_node2_succeed():
64
64
62
12
52
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_008_writes_to_node2_succeed
test_008_writes_to_node2_succeed
73
76
73
73
9f8fe832cd167dc7d1efbb3c3b98a3fa62893a32
bigcode/the-stack
train
a34c4ef6123b0ca8aa3308d6
train
function
def test_014_add_new_secondary(): global node3 node3 = cluster.create_datanode("/tmp/basic/node3") node3.create() node3.run() assert node3.wait_until_state(target_state="secondary") assert node2.wait_until_state(target_state="primary")
def test_014_add_new_secondary():
global node3 node3 = cluster.create_datanode("/tmp/basic/node3") node3.create() node3.run() assert node3.wait_until_state(target_state="secondary") assert node2.wait_until_state(target_state="primary")
(target_state="wait_primary") def test_013_drop_secondary(): node1.run() assert node1.wait_until_state(target_state="secondary") node1.drop() assert not node1.pg_is_running() assert node2.wait_until_state(target_state="single") def test_014_add_new_secondary():
64
64
62
8
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_014_add_new_secondary
test_014_add_new_secondary
103
109
103
103
e46079ef2ad335ac37862d81b2b04ea45f0bcbe6
bigcode/the-stack
train
8e71b754b68b492c99dee1ef
train
function
def test_017_stop_postgres_monitor(): original_state = node3.get_state() monitor.stop_postgres() monitor.wait_until_pg_is_running() assert node3.wait_until_state(target_state=original_state)
def test_017_stop_postgres_monitor():
original_state = node3.get_state() monitor.stop_postgres() monitor.wait_until_pg_is_running() assert node3.wait_until_state(target_state=original_state)
node3.run_sql_query(count_repl_slots); assert node3_replication_slots == [(0,)] def test_016_drop_primary(): node2.drop() assert not node2.pg_is_running() assert node3.wait_until_state(target_state="single") def test_017_stop_postgres_monitor():
64
64
45
9
55
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_017_stop_postgres_monitor
test_017_stop_postgres_monitor
139
143
139
139
5d1cce1b3aa08db086e550b5a4ec75844f115c0f
bigcode/the-stack
train
ab9d5c1b6f21b2680a19e216
train
function
def test_010_read_from_new_secondary(): results = node1.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)]
def test_010_read_from_new_secondary():
results = node1.run_sql_query("SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)]
assert results == [(1,), (2,), (3,), (4,)] def test_009_start_node1_again(): node1.run() assert node2.wait_until_state(target_state="primary") assert node1.wait_until_state(target_state="secondary") def test_010_read_from_new_secondary():
64
64
44
9
55
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_010_read_from_new_secondary
test_010_read_from_new_secondary
83
85
83
83
2ae0b3c8c3374566f44b8eeb467d694f9fa72084
bigcode/the-stack
train
d4b00d46a64cf457332c7bb7
train
function
def test_012_fail_secondary(): node1.fail() assert node2.wait_until_state(target_state="wait_primary")
def test_012_fail_secondary():
node1.fail() assert node2.wait_until_state(target_state="wait_primary")
SELECT * FROM t1 ORDER BY a") assert results == [(1,), (2,), (3,), (4,)] @raises(Exception) def test_011_writes_to_node1_fail(): node1.run_sql_query("INSERT INTO t1 VALUES (3)") def test_012_fail_secondary():
63
64
25
7
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_012_fail_secondary
test_012_fail_secondary
91
93
91
91
347477ca6404619b6def18daba62e2e4b53e3d04
bigcode/the-stack
train
907dbb90e3f9635f39678003
train
function
def teardown_module(): cluster.destroy()
def teardown_module():
cluster.destroy()
import pgautofailover_utils as pgautofailover from nose.tools import * cluster = None monitor = None node1 = None node2 = None node3 = None def setup_module(): global cluster cluster = pgautofailover.Cluster() def teardown_module():
64
64
8
4
60
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
teardown_module
teardown_module
14
15
14
14
d793a0252595541510e33116dcc5e7ed7cc8e4f4
bigcode/the-stack
train
b6587ce65a507a549a46b36a
train
function
def test_002_create_t1(): node1.run_sql_query("CREATE TABLE t1(a int)") node1.run_sql_query("INSERT INTO t1 VALUES (1), (2)")
def test_002_create_t1():
node1.run_sql_query("CREATE TABLE t1(a int)") node1.run_sql_query("INSERT INTO t1 VALUES (1), (2)")
_datanode("/tmp/basic/node1") node1.create() node1.run() assert node1.wait_until_state(target_state="single") def test_001_stop_postgres(): node1.stop_postgres() assert node1.wait_until_pg_is_running() def test_002_create_t1():
64
64
40
8
56
Bouke/pg_auto_failover
tests/test_basic_operation.py
Python
test_002_create_t1
test_002_create_t1
33
35
33
33
1bb402325d00ce2ef2ed88b6419455cd3bc01504
bigcode/the-stack
train
c5261901a4c60b90bd9fb5fb
train
function
def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready trainset = TextMelLoader(hparams.training_files, hparams) # trainset.__getitem__(index) = (text, mel), text in [num_char], mel in [num_mel, ceil((len(audio)+1)/hop_length)] valset = TextMelLoader(hparams.validation_files, ...
def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready
trainset = TextMelLoader(hparams.training_files, hparams) # trainset.__getitem__(index) = (text, mel), text in [num_char], mel in [num_mel, ceil((len(audio)+1)/hop_length)] valset = TextMelLoader(hparams.validation_files, hparams) collate_fn = TextMelCollate(hparams.n_frames_per_step) # train_sampler = ...
.init_process_group( backend=hparams.dist_backend, init_method=hparams.dist_url, world_size=n_gpus, rank=rank, group_name=group_name) print("Done initializing distributed") def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready
64
64
188
22
42
CookiePPP/mellotron
GTA.py
Python
prepare_dataloaders
prepare_dataloaders
66
77
66
67
710e8e4540b0f32e981f763e667fb82bff0e7d1c
bigcode/the-stack
train
43bc30b99e9aabec393e99a3
train
function
def warm_start_model(checkpoint_path, model): assert os.path.isfile(checkpoint_path) print("Warm starting model from checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model.load_state_dict(checkpoint_dict['state_dict']) return model
def warm_start_model(checkpoint_path, model):
assert os.path.isfile(checkpoint_path) print("Warm starting model from checkpoint '{}'".format(checkpoint_path)) checkpoint_dict = torch.load(checkpoint_path, map_location='cpu') model.load_state_dict(checkpoint_dict['state_dict']) return model
): model = Tacotron2(hparams).cuda() if hparams.fp16_run: model = batchnorm_to_float(model.half()) model.decoder.attention_layer.score_mask_value = float(finfo('float16').min) return model def warm_start_model(checkpoint_path, model):
64
64
65
10
53
CookiePPP/mellotron
GTA.py
Python
warm_start_model
warm_start_model
107
112
107
107
5d45af641b38b8f755ae1f5ad3df343b48f5abef
bigcode/the-stack
train
ba265bfe7ef699e10a1ee3e1
train
function
def init_distributed(hparams, n_gpus, rank, group_name): assert torch.cuda.is_available(), "Distributed mode requires CUDA." print("Initializing distributed") # Set cuda device so everything is done on the right GPU. torch.cuda.set_device(rank % torch.cuda.device_count()) # Initialize distributed co...
def init_distributed(hparams, n_gpus, rank, group_name):
assert torch.cuda.is_available(), "Distributed mode requires CUDA." print("Initializing distributed") # Set cuda device so everything is done on the right GPU. torch.cuda.set_device(rank % torch.cuda.device_count()) # Initialize distributed communication torch.distributed.init_process_group( ...
return module def reduce_tensor(tensor, num_gpus): rt = tensor.clone() torch.distributed.all_reduce(rt, op=torch.distributed.reduce_op.SUM) rt /= num_gpus return rt def init_distributed(hparams, n_gpus, rank, group_name):
64
64
113
16
47
CookiePPP/mellotron
GTA.py
Python
init_distributed
init_distributed
54
63
54
54
2b66a53e85f39665c26cca3577cb7c114c11d632
bigcode/the-stack
train
055d9b309114a649ac876cbe
train
function
def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready trainset = TextMelLoader(hparams.training_files, hparams) valset = TextMelLoader(hparams.validation_files, hparams, speaker_ids=trainset.speaker_ids) collate_fn = TextMelCollate(hparams.n_fra...
def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready
trainset = TextMelLoader(hparams.training_files, hparams) valset = TextMelLoader(hparams.validation_files, hparams, speaker_ids=trainset.speaker_ids) collate_fn = TextMelCollate(hparams.n_frames_per_step) if hparams.distributed_run: train_sampler = DistributedSampler(...
_sampler, batch_size=hparams.batch_size, pin_memory=False, drop_last=True, collate_fn=collate_fn) return train_loader, valset, collate_fn, trainset def prepare_dataloaders(hparams): # Get data, data loaders and collate function ready
64
64
208
22
41
CookiePPP/mellotron
GTA.py
Python
prepare_dataloaders
prepare_dataloaders
79
97
79
80
29155dd6f7901d554b4504427a084640344e21ba
bigcode/the-stack
train
807251366f78f015fa78d4ad
train
function
def reduce_tensor(tensor, num_gpus): rt = tensor.clone() torch.distributed.all_reduce(rt, op=torch.distributed.reduce_op.SUM) rt /= num_gpus return rt
def reduce_tensor(tensor, num_gpus):
rt = tensor.clone() torch.distributed.all_reduce(rt, op=torch.distributed.reduce_op.SUM) rt /= num_gpus return rt
def batchnorm_to_float(module): """Converts batch norm modules to FP32""" if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): batchnorm_to_float(child) return module def reduce_tensor(tensor, num_gpus):
64
64
44
10
53
CookiePPP/mellotron
GTA.py
Python
reduce_tensor
reduce_tensor
47
51
47
47
d9ee015feda396c54c125ed9c5ea7d3e4dab7c7f
bigcode/the-stack
train
d57c895f66cb0d630739f6e3
train
function
def load_model(hparams): model = Tacotron2(hparams).cuda() if hparams.fp16_run: model = batchnorm_to_float(model.half()) model.decoder.attention_layer.score_mask_value = float(finfo('float16').min) return model
def load_model(hparams):
model = Tacotron2(hparams).cuda() if hparams.fp16_run: model = batchnorm_to_float(model.half()) model.decoder.attention_layer.score_mask_value = float(finfo('float16').min) return model
, # default pin_memory=False, True should allow async memory transfers # Causes very random CUDA errors (after like 4+ hours) drop_last=True, collate_fn=collate_fn) return train_loader, valset, collate_fn, train_sampler, trainset def load_model(hparams):
64
64
59
6
57
CookiePPP/mellotron
GTA.py
Python
load_model
load_model
99
104
99
99
dedb33b99c4d04dcbc87224be329915eeef58bc6
bigcode/the-stack
train
ca0ab66a1d89c52ec46e3928
train
function
def batchnorm_to_float(module): """Converts batch norm modules to FP32""" if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): batchnorm_to_float(child) return module
def batchnorm_to_float(module):
"""Converts batch norm modules to FP32""" if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): batchnorm_to_float(child) return module
self.sum = 0 def process(self, value): self.values.append(value) self.sum += value if len(self.values) > self.window_size: self.sum -= self.values.pop(0) return float(self.sum) / len(self.values) def batchnorm_to_float(module):
64
64
54
7
57
CookiePPP/mellotron
GTA.py
Python
batchnorm_to_float
batchnorm_to_float
38
44
38
38
308122e215f33369ddd6900e21f5170e6c895837
bigcode/the-stack
train
9594c99e33195b619c4b2d20
train
class
class StreamingMovingAverage: def __init__(self, window_size): self.window_size = window_size self.values = [] self.sum = 0 def process(self, value): self.values.append(value) self.sum += value if len(self.values) > self.window_size: self.sum -= self....
class StreamingMovingAverage:
def __init__(self, window_size): self.window_size = window_size self.values = [] self.sum = 0 def process(self, value): self.values.append(value) self.sum += value if len(self.values) > self.window_size: self.sum -= self.values.pop(0) return f...
DataParallel from torch.utils.data import DataLoader from fp16_optimizer import FP16_Optimizer from model import Tacotron2 from data_utils import TextMelLoader, TextMelCollate from hparams import create_hparams from train import init_distributed import time class StreamingMovingAverage:
64
64
86
5
58
CookiePPP/mellotron
GTA.py
Python
StreamingMovingAverage
StreamingMovingAverage
24
35
24
24
f9d7e7543e48f01367c7f659d765c5df8fdbc5ff
bigcode/the-stack
train
a09e84d7fe3ea92b641d0be2
train
function
def GTA_Synthesis(output_directory, checkpoint_path, n_gpus, rank, group_name, hparams): """Generate Ground-Truth-Aligned Spectrograms for Training WaveGlow.""" if hparams.distributed_run: init_distributed(hparams, n_gpus, rank, group_name) torch.manual_seed(hparams.seed) torch.cuda.ma...
def GTA_Synthesis(output_directory, checkpoint_path, n_gpus, rank, group_name, hparams):
"""Generate Ground-Truth-Aligned Spectrograms for Training WaveGlow.""" if hparams.distributed_run: init_distributed(hparams, n_gpus, rank, group_name) torch.manual_seed(hparams.seed) torch.cuda.manual_seed(hparams.seed) model = load_model(hparams) train_loader, valset, collate_fn, train...
= False else: train_sampler = None shuffle = False train_loader = DataLoader(trainset, num_workers=1, shuffle=shuffle, sampler=train_sampler, batch_size=hparams.batch_size, pin_memory=False, # default pin_memory=False, True should all...
256
256
957
23
232
CookiePPP/mellotron
GTA.py
Python
GTA_Synthesis
GTA_Synthesis
115
193
115
116
525438ebed243acf7ca55fe06f9643dc1d12d752
bigcode/the-stack
train
16ca9f780c82c3dd27311170
train
class
class Translator(object): def __init__(self, args): super(Translator, self).__init__() self.config = configurations.get_config(args.proto, getattr(configurations, args.proto), args.config_overrides) self.logger = ut.get_logger(self.config['log_file']) self.num_preload = args.num_prel...
class Translator(object):
def __init__(self, args): super(Translator, self).__init__() self.config = configurations.get_config(args.proto, getattr(configurations, args.proto), args.config_overrides) self.logger = ut.get_logger(self.config['log_file']) self.num_preload = args.num_preload self.model_fi...
import os import time import sys import numpy import torch import nmt.all_constants as ac import nmt.utils as ut from nmt.model import Model from nmt.data_manager import DataManager import nmt.configurations as configurations class Translator(object):
58
256
876
4
53
HerbertMcSnout/witwicky-trees
nmt/translate.py
Python
Translator
Translator
14
100
14
14
18819e0b67585d02715d06a76dc5c1cf2390a43d
bigcode/the-stack
train
fa2a6420fb47c3ade49fb1e2
train
class
@pytest.mark.usefixtures('testmockoperations_plugin') @pytest.mark.usefixtures('cloudmock_plugin') @pytest.mark.usefixtures('mock_workflows_plugin') class TestDeploymentWorkflows(AgentlessTestCase): def test_deployment_workflows(self): dsl_path = resource("dsl/custom_workflow_mapping.yaml") deploym...
@pytest.mark.usefixtures('testmockoperations_plugin') @pytest.mark.usefixtures('cloudmock_plugin') @pytest.mark.usefixtures('mock_workflows_plugin') class TestDeploymentWorkflows(AgentlessTestCase):
def test_deployment_workflows(self): dsl_path = resource("dsl/custom_workflow_mapping.yaml") deployment, _ = self.deploy_application(dsl_path) deployment_id = deployment.id workflows = self.client.deployments.get(deployment_id).workflows self.assertEqual(14, len(workflows)) ...
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed un...
256
256
905
40
215
cloudify-cosmo/cloudify-manager
tests/integration_tests/tests/agentless_tests/test_deployment_workflows.py
Python
TestDeploymentWorkflows
TestDeploymentWorkflows
33
127
33
37
0ae123545f1afb0bc49a33342245087f01a07cf8
bigcode/the-stack
train
7260fd354ec98c947d7b07aa
train
class
class AuthByPlugin(object): """ External Authenticator interface. """ @property def assertion_content(self): raise NotImplementedError def update_body(self, body): raise NotImplementedError def authenticate( self, authenticator, service_name, account, user, pas...
class AuthByPlugin(object):
""" External Authenticator interface. """ @property def assertion_content(self): raise NotImplementedError def update_body(self, body): raise NotImplementedError def authenticate( self, authenticator, service_name, account, user, password): raise NotImp...
/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved. # from .errors import Error, DatabaseError from .sqlstate import SQLSTATE_CONNECTION_WAS_NOT_ESTABLISHED class AuthByPlugin(object):
64
64
211
6
57
felixitous/snowflake-connector-python
auth_by_plugin.py
Python
AuthByPlugin
AuthByPlugin
11
44
11
11
5780b02268a7e1e46dddf460a732f722f52387d3
bigcode/the-stack
train
9e58837d9a70c5a97047704f
train
function
@pytest.mark.parametrize( 'name', (MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT) def test_multilabel_sample_weight_invariance(name): # multilabel indicator random_state = check_random_state(0) _, ya = make_multilabel_cla...
@pytest.mark.parametrize( 'name', (MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT) def test_multilabel_sample_weight_invariance(name): # multilabel indicator
random_state = check_random_state(0) _, ya = make_multilabel_classification(n_features=1, n_classes=20, random_state=0, n_samples=100, allow_unlabeled=False) _, yb = make_multilabel_classification(n_features=1, n_classes=2...
(name, metric, y_true, y_pred) @pytest.mark.parametrize( 'name', (MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT) def test_multilabel_sample_weight_invariance(name): # multilabel indicator
74
74
248
64
10
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multilabel_sample_weight_invariance
test_multilabel_sample_weight_invariance
1,160
1,181
1,160
1,165
ca0bf8fead8933d21b6115492af16db0b531b9e9
bigcode/the-stack
train
5309b4781f447c93ca823309
train
function
@pytest.mark.parametrize( 'name', THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) def test_thresholded_multilabel_multioutput_permutations_invariance(name): random_state = check_random_state(0) n_samples, n_classes = 20, 4 y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_scor...
@pytest.mark.parametrize( 'name', THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) def test_thresholded_multilabel_multioutput_permutations_invariance(name):
random_state = check_random_state(0) n_samples, n_classes = 20, 4 y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_score = random_state.normal(size=y_true.shape) # Makes sure all samples have at least one label. This works around errors # when running metrics where average="sa...
= y_true[:, perm] current_score = metric(y_true_perm, y_score_perm) assert_almost_equal(score, current_score) @pytest.mark.parametrize( 'name', THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) def test_thresholded_multilabel_multioutput_permutations_invariance(name):
72
72
240
43
29
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_thresholded_multilabel_multioutput_permutations_invariance
test_thresholded_multilabel_multioutput_permutations_invariance
1,228
1,249
1,228
1,230
7886d51ffbad801c583f20ad09c8f12a0502f608
bigcode/the-stack
train
3096f1e7ce2b070b7a223821
train
function
@ignore_warnings def check_single_sample_multioutput(name): metric = ALL_METRICS[name] for i, j, k, l in product([0, 1], repeat=4): metric(np.array([[i, j]]), np.array([[k, l]]))
@ignore_warnings def check_single_sample_multioutput(name):
metric = ALL_METRICS[name] for i, j, k, l in product([0, 1], repeat=4): metric(np.array([[i, j]]), np.array([[k, l]]))
into a 0-d array (!). metric = ALL_METRICS[name] # assert that no exception is thrown for i, j in product([0, 1], repeat=2): metric([i], [j]) @ignore_warnings def check_single_sample_multioutput(name):
64
64
61
13
51
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
check_single_sample_multioutput
check_single_sample_multioutput
733
737
733
734
55c967075e0b52ddfcaa985edfc58575610d3832
bigcode/the-stack
train
4dd474f7ba4ea912d06942ab
train
function
@pytest.mark.parametrize( 'name', set(CLASSIFICATION_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) def test_classification_invariance_string_vs_numbers_labels(name): # Ensure that classification metrics with string labels are invariant random_state = check_random_state(0) y1 = random_state.ra...
@pytest.mark.parametrize( 'name', set(CLASSIFICATION_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) def test_classification_invariance_string_vs_numbers_labels(name): # Ensure that classification metrics with string labels are invariant
random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_str = np.array(["eggs", "spam"])[y1] y2_str = np.array(["eggs", "spam"])[y2] pos_label_str = "spam" labels_str = ["eggs", "spam"] with ignore_warnings(): ...
y2_column) # NB: We do not test for y1_row, y2_row as these may be # interpreted as multilabel or multioutput data. if (name not in (MULTIOUTPUT_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTILABELS_METRICS)): assert_raises(ValueError, metric, y1_row, y2_r...
140
140
468
52
88
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_classification_invariance_string_vs_numbers_labels
test_classification_invariance_string_vs_numbers_labels
609
656
609
613
4f643c16963ff888f995672b7dd23ef0f4eb5fb2
bigcode/the-stack
train
b717263b2128347347b696f6
train
function
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_regression_invariance_to_dimension_shuffling(name): # test invariance to dimension shuffling random_state = check_random_state(0) y_true = random_state.uniform(0, 2, size=(20, 5)) y_pred = random_state.uniform(0, 2, size=(20, 5))...
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_regression_invariance_to_dimension_shuffling(name): # test invariance to dimension shuffling
random_state = check_random_state(0) y_true = random_state.uniform(0, 2, size=(20, 5)) y_pred = random_state.uniform(0, 2, size=(20, 5)) metric = ALL_METRICS[name] error = metric(y_true, y_pred) for _ in range(3): perm = random_state.permutation(y_true.shape[1]) assert_allclose...
0]]) metric = ALL_METRICS[name] assert_raises(ValueError, metric, y_true, y_pred) @pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_regression_invariance_to_dimension_shuffling(name): # test invariance to dimension shuffling
64
64
163
38
26
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multioutput_regression_invariance_to_dimension_shuffling
test_multioutput_regression_invariance_to_dimension_shuffling
765
780
765
767
f72fdb1743d3a03baed2891bc21d334a5b70d648
bigcode/the-stack
train
46a2e7f46dd59bf034db4f8b
train
function
def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score): is_multilabel = type_of_target(y_true).startswith("multilabel") metric = ALL_METRICS[name] if name in METRICS_WITH_AVERAGING: _check_averaging(metric, y_true, y_pred, y_true_binarize, ...
def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score):
is_multilabel = type_of_target(y_true).startswith("multilabel") metric = ALL_METRICS[name] if name in METRICS_WITH_AVERAGING: _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel) elif name in THRESHOLDED_METRICS_WITH_AVERAGING: ...
(ValueError, metric, y_true, y_pred, average="unknown") assert_raises(ValueError, metric, y_true, y_pred, average="garbage") def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score):
64
64
163
29
35
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
check_averaging
check_averaging
944
957
944
945
10ecd983817aad4468322d904dfb82a8ce5f25a1
bigcode/the-stack
train
a672afeb4bf07808d4ffcdd7
train
function
@pytest.mark.parametrize( 'name', set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) def test_format_invariance_with_1d_vectors(name): random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_list = list(y1) ...
@pytest.mark.parametrize( 'name', set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) def test_format_invariance_with_1d_vectors(name):
random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_list = list(y1) y2_list = list(y2) y1_1d, y2_1d = np.array(y1), np.array(y2) assert_array_equal(y1_1d.ndim, 1) assert_array_equal(y2_1d.ndim, 1) y1_colu...
for name in MULTILABELS_METRICS: metric = ALL_METRICS[name] assert_allclose(metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name) for name in THRESHOLDED_MULTILABEL_METRICS: metr...
245
245
817
39
206
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_format_invariance_with_1d_vectors
test_format_invariance_with_1d_vectors
533
606
533
536
c0718260b9bb141481cc1783466990647302aad0
bigcode/the-stack
train
c2963c9cfdb701e74b51bbf1
train
function
@pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_zeroes(name): y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_score = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, ...
@pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_zeroes(name):
y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_score = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) @pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_zeroes(name):
64
64
112
27
37
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_averaging_multilabel_all_zeroes
test_averaging_multilabel_all_zeroes
993
1,002
993
994
746cd23ad3d8abdb6aca399f163b1ff7281eab3b
bigcode/the-stack
train
fb3f205a844c63d830a97029
train
function
@pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_multiclass_classification(name): # Test in the multiclass case random_state = check_random_state(0) y_true = random_state.randint(0, 4, size=(20, )) y_pred = random_state.randint(0, 4, size=(20, )) n_samples = ...
@pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_multiclass_classification(name): # Test in the multiclass case
random_state = check_random_state(0) y_true = random_state.randint(0, 4, size=(20, )) y_pred = random_state.randint(0, 4, size=(20, )) n_samples = y_true.shape[0] metrics = ALL_METRICS[name] measure = metrics(y_true, y_pred, normalize=True) assert_array_less(-1.0 * measure, 0, ...
correctly the normalize " "option") assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, measure) @pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_multiclass_classification(name): # Test in the multiclas...
64
64
164
35
29
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_normalize_option_multiclass_classification
test_normalize_option_multiclass_classification
853
867
853
855
6e6b8cc32e4382ab1c7fcfb43740667245ff6569
bigcode/the-stack
train
8649d1375ecdeda2a1687715
train
function
@ignore_warnings def test_multilabel_representation_invariance(): # Generate some data n_classes = 4 n_samples = 50 _, y1 = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=0, n_samples=n_samples, ...
@ignore_warnings def test_multilabel_representation_invariance(): # Generate some data
n_classes = 4 n_samples = 50 _, y1 = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=0, n_samples=n_samples, allow_unlabeled=True) _, y2 = make_multilabel_classification(n_features=1, n_...
[name] error = metric(y_true, y_pred) for _ in range(3): perm = random_state.permutation(y_true.shape[1]) assert_allclose(metric(y_true[:, perm], y_pred[:, perm]), error, err_msg="%s is not dimension shuffling invariant" % ( ...
89
89
299
21
68
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multilabel_representation_invariance
test_multilabel_representation_invariance
783
817
783
785
6b058e0db200bd62a83ec5554be77d6cc204d3a2
bigcode/the-stack
train
33c86ec5dbec4f5374e8a708
train
function
@ignore_warnings def test_no_averaging_labels(): # test labels argument when not using averaging # in multi-class and multi-label cases y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) y_true_multiclass = np.array([0, 1, 2]) y_...
@ignore_warnings def test_no_averaging_labels(): # test labels argument when not using averaging # in multi-class and multi-label cases
y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) y_true_multiclass = np.array([0, 1, 2]) y_pred_multiclass = np.array([0, 2, 3]) labels = np.array([3, 0, 1, 2]) _, inverse_labels = np.unique(labels, return_inverse=True) fo...
ALL_METRICS[name] if name in THRESHOLDED_METRICS: check_sample_weight_invariance(name, metric, y_true, y_score) else: check_sample_weight_invariance(name, metric, y_true, y_pred) @ignore_warnings def test_no_averaging_labels(): # test labels argument when not using averaging # in multi-...
86
86
288
33
53
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_no_averaging_labels
test_no_averaging_labels
1,184
1,205
1,184
1,187
c9ebf86cac7c85522c6ecb0de8f36740c5bd3395
bigcode/the-stack
train
9b8ad4d86d1764ca4ed699ce
train
function
@pytest.mark.parametrize( 'name', MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"}) def test_multilabel_label_permutations_invariance(name): random_state = check_random_state(0) n_samples, n_classes = 20, 4 y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_score =...
@pytest.mark.parametrize( 'name', MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"}) def test_multilabel_label_permutations_invariance(name):
random_state = check_random_state(0) n_samples, n_classes = 20, 4 y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_score = random_state.randint(0, 2, size=(n_samples, n_classes)) metric = ALL_METRICS[name] score = metric(y_true, y_score) for perm in permutations(range(n_...
score = metric(y_true, y_pred, average=None) assert_array_equal(score_labels, score[inverse_labels]) @pytest.mark.parametrize( 'name', MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"}) def test_multilabel_label_permutations_invariance(name):
64
64
179
40
24
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multilabel_label_permutations_invariance
test_multilabel_label_permutations_invariance
1,208
1,225
1,208
1,210
1103327114d7d9c44a310f6edbb1211ab25205f3
bigcode/the-stack
train
443b7d14e69681ce0711b382
train
function
def test_normalize_option_multilabel_classification(): # Test in the multilabel case n_classes = 4 n_samples = 100 # for both random_state 0 and 1, y_true and y_pred has at least one # unlabelled entry _, y_true = make_multilabel_classification(n_features=1, ...
def test_normalize_option_multilabel_classification(): # Test in the multilabel case
n_classes = 4 n_samples = 100 # for both random_state 0 and 1, y_true and y_pred has at least one # unlabelled entry _, y_true = make_multilabel_classification(n_features=1, n_classes=n_classes, random_sta...
= metrics(y_true, y_pred, normalize=True) assert_array_less(-1.0 * measure, 0, err_msg="We failed to test correctly the normalize " "option") assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, measure) def test_normalize...
82
82
274
20
62
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_normalize_option_multilabel_classification
test_normalize_option_multilabel_classification
870
899
870
871
8b282a96f66cf7b8ff36114079a718ed4e566b2e
bigcode/the-stack
train
8d431910c3f7de9f373ca2ac
train
function
@pytest.mark.parametrize( 'metric', chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values())) def test_regression_thresholded_inf_nan_input(metric): for y_true, y_score in invalids: assert_raise_message(ValueError, "contains NaN, infinity", ...
@pytest.mark.parametrize( 'metric', chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values())) def test_regression_thresholded_inf_nan_input(metric):
for y_true, y_score in invalids: assert_raise_message(ValueError, "contains NaN, infinity", metric, y_true, y_score)
1], [np.nan, np.nan]), ([0, 1], [np.nan, np.inf])] @pytest.mark.parametrize( 'metric', chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values())) def test_regression_thresholded_inf_nan_input(metric):
63
64
74
39
24
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_regression_thresholded_inf_nan_input
test_regression_thresholded_inf_nan_input
699
707
699
703
b7513a60cd2fe8baa0aebdbccf86d8883316a54d
bigcode/the-stack
train
9dd6cce6021b6af389594ccc
train
function
@ignore_warnings def _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel): n_samples, n_classes = y_true_binarize.shape # No averaging label_measure = metric(y_true, y_pred, average=None) assert_allclose(label_measure, [metri...
@ignore_warnings def _check_averaging(metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel):
n_samples, n_classes = y_true_binarize.shape # No averaging label_measure = metric(y_true, y_pred, average=None) assert_allclose(label_measure, [metric(y_true_binarize[:, i], y_pred_binarize[:, i]) for i in range(n_classes)]) # Micro measure micro_measu...
] measure = metrics(y_true, y_pred, normalize=True) assert_array_less(-1.0 * measure, 0, err_msg="We failed to test correctly the normalize " "option") assert_allclose(metrics(y_true, y_pred, normalize=False) / n_samples, ...
113
113
379
37
76
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
_check_averaging
_check_averaging
902
941
902
904
3a5e456aa078a092f08585ef4a9843fad7f14066
bigcode/the-stack
train
b5984e609b29e6881fddaa01
train
function
@pytest.mark.parametrize( 'name', METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING) def test_averaging_multilabel(name): n_samples, n_classes = 40, 5 _, y = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=5, n_samples=n_...
@pytest.mark.parametrize( 'name', METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING) def test_averaging_multilabel(name):
n_samples, n_classes = 40, 5 _, y = make_multilabel_classification(n_features=1, n_classes=n_classes, random_state=5, n_samples=n_samples, allow_unlabeled=False) y_true = y[:20] y_pred = y[20:] y_score = check_random...
averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) @pytest.mark.parametrize( 'name', METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING) def test_averaging_multilabel(name):
64
64
172
38
26
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_averaging_multilabel
test_averaging_multilabel
976
990
976
978
eb7f77b64bf8cd84adc002f7ad2dce3f30a4740a
bigcode/the-stack
train
5301e7e0042ee3a3d8326742
train
function
@pytest.mark.parametrize( 'name', (set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) - METRICS_WITHOUT_SAMPLE_WEIGHT)) def test_regression_sample_weight_invariance(name): n_samples = 50 random_state = check_random_state(0) # regression y_true = random_state.random_sample(si...
@pytest.mark.parametrize( 'name', (set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) - METRICS_WITHOUT_SAMPLE_WEIGHT)) def test_regression_sample_weight_invariance(name):
n_samples = 50 random_state = check_random_state(0) # regression y_true = random_state.random_sample(size=(n_samples,)) y_pred = random_state.random_sample(size=(n_samples,)) metric = ALL_METRICS[name] check_sample_weight_invariance(name, metric, y_true, y_pred)
y2, sample_weight=np.hstack([sample_weight, sample_weight])) @pytest.mark.parametrize( 'name', (set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) - METRICS_WITHOUT_SAMPLE_WEIGHT)) def test_regression_sample_weight_...
63
64
118
46
17
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_regression_sample_weight_invariance
test_regression_sample_weight_invariance
1,109
1,120
1,109
1,113
dc68bc0e5dd42dffac2176dc8d45140105d05ba0
bigcode/the-stack
train
3bf27ab4503d103ac3c5edbe
train
function
@pytest.mark.parametrize('name', THRESHOLDED_METRICS) def test_thresholded_invariance_string_vs_numbers_labels(name): # Ensure that thresholded metrics with string labels are invariant random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=...
@pytest.mark.parametrize('name', THRESHOLDED_METRICS) def test_thresholded_invariance_string_vs_numbers_labels(name): # Ensure that thresholded metrics with string labels are invariant
random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20, )) y2 = random_state.randint(0, 2, size=(20, )) y1_str = np.array(["eggs", "spam"])[y1] pos_label_str = "spam" with ignore_warnings(): metric = THRESHOLDED_METRICS[name] if name not in METRIC_UNDEFI...
test".format(name)) measure_with_strobj = metric_str(y1_str.astype('O'), y2_str.astype('O')) assert_array_equal(measure_with_number, measure_with_strobj, err_msg="{0} failed string vs number " ...
104
104
349
39
65
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_thresholded_invariance_string_vs_numbers_labels
test_thresholded_invariance_string_vs_numbers_labels
659
691
659
661
49f5a0d670561ecc08e8c5ada4fcc31a1d1862d6
bigcode/the-stack
train
b87652a9d86be78163f19d6e
train
function
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY)) def test_binary_sample_weight_invariance(name): # binary n_samples = 50 random_state = check_random_state(0) y_true = random_state.randint(0,...
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY)) def test_binary_sample_weight_invariance(name): # binary
n_samples = 50 random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples, )) y_pred = random_state.randint(0, 2, size=(n_samples, )) y_score = random_state.random_sample(size=(n_samples,)) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: check...
, metric, y_true, y_pred) @pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY)) def test_binary_sample_weight_invariance(name): # binary
64
64
179
55
9
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_binary_sample_weight_invariance
test_binary_sample_weight_invariance
1,123
1,138
1,123
1,128
410060e5f6c5d3932a38795049e70a866437d37f
bigcode/the-stack
train
93ae6a2803762675fee73662
train
function
@pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_ones(name): y_true = np.ones((20, 3)) y_pred = np.ones((20, 3)) y_score = np.ones((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, ...
@pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_ones(name):
y_true = np.ones((20, 3)) y_pred = np.ones((20, 3)) y_score = np.ones((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
, average)) _check_averaging(binary_metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel=True) @pytest.mark.parametrize('name', METRICS_WITH_AVERAGING) def test_averaging_multilabel_all_ones(name):
64
64
112
27
37
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_averaging_multilabel_all_ones
test_averaging_multilabel_all_ones
1,018
1,027
1,018
1,019
88d916498ed7132ee27dcfc28014cbdc70070ceb
bigcode/the-stack
train
98d3d9d5fec3d91cdcaabb74
train
function
@ignore_warnings def test_symmetry(): # Test the symmetry of score and loss functions random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20, )) y_pred = random_state.randint(0, 2, size=(20, )) # We shouldn't forget any metrics assert_equal(SYMMETRIC_METRICS.union( ...
@ignore_warnings def test_symmetry(): # Test the symmetry of score and loss functions
random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20, )) y_pred = random_state.randint(0, 2, size=(20, )) # We shouldn't forget any metrics assert_equal(SYMMETRIC_METRICS.union( NOT_SYMMETRIC_METRICS, set(THRESHOLDED_METRICS), METRIC_UNDEFINED_BINARY_MUL...
usion_matrix", "macro_f0.5_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "log_loss", "hinge_loss" } # No Sample weight support METRICS_WITHOUT_SAMPLE_WEIGHT = { "median_absolute_error", "max_error" } @ignore_warnings def test_symmetry(): # Test the symmetry of score and...
88
88
295
21
67
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_symmetry
test_symmetry
448
478
448
450
b89bb856d271fb98be816eb5b7a6f0d78a638f7a
bigcode/the-stack
train
bb35cd3680f8e1b0236c1114
train
function
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) # Those metrics are not always defined with one sample # or in multiclass classification - METRIC_UNDEFINED_BINARY_MULTICLASS - set(THRESHOLDED_METRICS))) def test_single_sample(name): check_single_sample(name)
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) # Those metrics are not always defined with one sample # or in multiclass classification - METRIC_UNDEFINED_BINARY_MULTICLASS - set(THRESHOLDED_METRICS))) def test_single_sample(name):
check_single_sample(name)
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) # Those metrics are not always defined with one sample # or in multiclass classification - METRIC_UNDEFINED_BINARY_MULTICLASS - set(THRESHOLDED_METRICS))) def test_single_sample(name):
67
64
73
67
0
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_single_sample
test_single_sample
740
748
740
747
c436a2e94895b48adb7bb9602a400ff3d5aa690a
bigcode/the-stack
train
dab78079dc4def33e55b04a6
train
function
@ignore_warnings def check_sample_weight_invariance(name, metric, y1, y2): rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y1)) # check that unit weights gives the same score as no weight unweighted_score = metric(y1, y2, sample_weight=None) assert_allclose( unwe...
@ignore_warnings def check_sample_weight_invariance(name, metric, y1, y2):
rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y1)) # check that unit weights gives the same score as no weight unweighted_score = metric(y1, y2, sample_weight=None) assert_allclose( unweighted_score, metric(y1, y2, sample_weight=np.ones(shape=len(y1))),...
y_true_binarize = y_true y_pred_binarize = y_pred # Test _average_binary_score for weight.sum() == 0 binary_metric = (lambda y_true, y_score, average="macro": _average_binary_score( precision_score, y_true, y_score, average)) _check_averaging(binary_metric,...
235
235
784
21
214
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
check_sample_weight_invariance
check_sample_weight_invariance
1,030
1,106
1,030
1,031
cc0a1b5e6c7c23eec111e5b4f3159bb67ede891f
bigcode/the-stack
train
801c65f4d53a5945a259c67a
train
function
def precision_recall_curve_padded_thresholds(*args, **kwargs): """ The dimensions of precision-recall pairs and the threshold array as returned by the precision_recall_curve do not match. See func:`sklearn.metrics.precision_recall_curve` This prevents implicit conversion of return value triple to a...
def precision_recall_curve_padded_thresholds(*args, **kwargs):
""" The dimensions of precision-recall pairs and the threshold array as returned by the precision_recall_curve do not match. See func:`sklearn.metrics.precision_recall_curve` This prevents implicit conversion of return value triple to an higher dimensional np.array of dtype('float64') (it will ...
=2), "samples_precision_score": partial(precision_score, average="samples"), "samples_recall_score": partial(recall_score, average="samples"), "cohen_kappa_score": cohen_kappa_score, } def precision_recall_curve_padded_thresholds(*args, **kwargs):
64
64
206
15
49
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
precision_recall_curve_padded_thresholds
precision_recall_curve_padded_thresholds
169
193
169
169
e4da142fe9d4960edfd9aaa23c309741d45c4145
bigcode/the-stack
train
1423f13a6fb03b589228fad3
train
function
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS | MULTILABELS_METRICS) def test_single_sample_multioutput(name): check_single_sample_multioutput(name)
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS | MULTILABELS_METRICS) def test_single_sample_multioutput(name):
check_single_sample_multioutput(name)
METRIC_UNDEFINED_BINARY_MULTICLASS - set(THRESHOLDED_METRICS))) def test_single_sample(name): check_single_sample(name) @pytest.mark.parametrize('name', MULTIOUTPUT_METRICS | MULTILABELS_METRICS) def test_single_sample_multioutput(name):
64
64
38
30
34
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_single_sample_multioutput
test_single_sample_multioutput
751
753
751
752
7a921d8fb2cdfea8703318acd837658eded2ccb8
bigcode/the-stack
train
f94db4a567fb12be24095162
train
function
@pytest.mark.parametrize('name', MULTILABELS_METRICS) def test_raise_value_error_multilabel_sequences(name): # make sure the multilabel-sequence format raises ValueError multilabel_sequences = [ [[0, 1]], [[1], [2], [0, 1]], [(), (2), (0, 1)], [[]], [()], np.array...
@pytest.mark.parametrize('name', MULTILABELS_METRICS) def test_raise_value_error_multilabel_sequences(name): # make sure the multilabel-sequence format raises ValueError
multilabel_sequences = [ [[0, 1]], [[1], [2], [0, 1]], [(), (2), (0, 1)], [[]], [()], np.array([[], [1, 2]], dtype='object')] metric = ALL_METRICS[name] for seq in multilabel_sequences: assert_raises(ValueError, metric, seq, seq)
measure, err_msg="%s failed representation invariance between " "dense and sparse indicator formats." % name) @pytest.mark.parametrize('name', MULTILABELS_METRICS) def test_raise_value_error_multilabel_sequences(name): # make sure the m...
64
64
129
39
25
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_raise_value_error_multilabel_sequences
test_raise_value_error_multilabel_sequences
820
833
820
822
090e6bb0b982df2c24e27ca23bba359a219d4e9f
bigcode/the-stack
train
5377598ae7f7bfffb03b4af8
train
function
@ignore_warnings def test_sample_order_invariance_multilabel_and_multioutput(): random_state = check_random_state(0) # Generate some data y_true = random_state.randint(0, 2, size=(20, 25)) y_pred = random_state.randint(0, 2, size=(20, 25)) y_score = random_state.normal(size=y_true.shape) y_tru...
@ignore_warnings def test_sample_order_invariance_multilabel_and_multioutput():
random_state = check_random_state(0) # Generate some data y_true = random_state.randint(0, 2, size=(20, 25)) y_pred = random_state.randint(0, 2, size=(20, 25)) y_score = random_state.normal(size=y_true.shape) y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle(y_true, ...
2, size=(20, )) y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0) with ignore_warnings(): metric = ALL_METRICS[name] assert_allclose(metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample o...
96
96
323
18
78
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_sample_order_invariance_multilabel_and_multioutput
test_sample_order_invariance_multilabel_and_multioutput
497
530
497
498
3f235aa65409f0760fe179ecda5bafcca8762b06
bigcode/the-stack
train
c8bf202b762e1218377627cf
train
function
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_number_of_output_differ(name): y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) y_pred = np.array([[0, 0], [1, 0], [0, 0]]) metric = ALL_METRICS[name] assert_raises(ValueError, metric, y_true, y_pred)
@pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_number_of_output_differ(name):
y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) y_pred = np.array([[0, 0], [1, 0], [0, 0]]) metric = ALL_METRICS[name] assert_raises(ValueError, metric, y_true, y_pred)
) @pytest.mark.parametrize('name', MULTIOUTPUT_METRICS | MULTILABELS_METRICS) def test_single_sample_multioutput(name): check_single_sample_multioutput(name) @pytest.mark.parametrize('name', MULTIOUTPUT_METRICS) def test_multioutput_number_of_output_differ(name):
64
64
115
25
39
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multioutput_number_of_output_differ
test_multioutput_number_of_output_differ
756
762
756
757
eef5cb5358a891ec0e54ab37250fc637e0214e21
bigcode/the-stack
train
9738fdfd5a3c8bb4ad69b973
train
function
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY_MULTICLASS)) def test_multiclass_sample_weight_invariance(name): # multiclass n_samples = 50 random_state = check_random_state(0) y_tr...
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY_MULTICLASS)) def test_multiclass_sample_weight_invariance(name): # multiclass
n_samples = 50 random_state = check_random_state(0) y_true = random_state.randint(0, 5, size=(n_samples, )) y_pred = random_state.randint(0, 5, size=(n_samples, )) y_score = random_state.random_sample(size=(n_samples, 5)) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: che...
@pytest.mark.parametrize( 'name', (set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY_MULTICLASS)) def test_multiclass_sample_weight_invariance(name): # multiclass
64
64
191
64
0
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_multiclass_sample_weight_invariance
test_multiclass_sample_weight_invariance
1,141
1,157
1,141
1,147
58868d3f7e38f28ec91418e116f0b3d5c769fbb3
bigcode/the-stack
train
ea3ecb0a54d21a410735d11e
train
function
def test_averaging_binary_multilabel_all_zeroes(): y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred # Test _average_binary_score for weight.sum() == 0 binary_metric = (lambda y_true, y_score, average="macro": _average_bi...
def test_averaging_binary_multilabel_all_zeroes():
y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred # Test _average_binary_score for weight.sum() == 0 binary_metric = (lambda y_true, y_score, average="macro": _average_binary_score( precision_scor...
3)) y_true_binarize = y_true y_pred_binarize = y_pred check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) def test_averaging_binary_multilabel_all_zeroes():
64
64
140
13
51
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_averaging_binary_multilabel_all_zeroes
test_averaging_binary_multilabel_all_zeroes
1,005
1,015
1,005
1,005
621f43233618710bded9cd18fe57f1a80f28f293
bigcode/the-stack
train
4a60b39e0efc0f07788ce4bf
train
function
@pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_binary_classification(name): # Test in the binary case n_samples = 20 random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples, )) y_pred = random_state.randint(0, 2, size=(n_sam...
@pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_binary_classification(name): # Test in the binary case
n_samples = 20 random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples, )) y_pred = random_state.randint(0, 2, size=(n_samples, )) metrics = ALL_METRICS[name] measure = metrics(y_true, y_pred, normalize=True) assert_array_less(-1.0 * measure, 0, ...
')] metric = ALL_METRICS[name] for seq in multilabel_sequences: assert_raises(ValueError, metric, seq, seq) @pytest.mark.parametrize('name', METRICS_WITH_NORMALIZE_OPTION) def test_normalize_option_binary_classification(name): # Test in the binary case
64
64
160
32
32
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_normalize_option_binary_classification
test_normalize_option_binary_classification
836
850
836
838
51f4bcdd1d3d2a16b316b26388dc65104d6ac58c
bigcode/the-stack
train
08d301c0000817e5bc066c71
train
function
@pytest.mark.parametrize('metric', CLASSIFICATION_METRICS.values()) def test_classification_inf_nan_input(metric): # Classification metrics all raise a mixed input exception for y_true, y_score in invalids: assert_raise_message(ValueError, "Classification metrics can't handl...
@pytest.mark.parametrize('metric', CLASSIFICATION_METRICS.values()) def test_classification_inf_nan_input(metric): # Classification metrics all raise a mixed input exception
for y_true, y_score in invalids: assert_raise_message(ValueError, "Classification metrics can't handle a mix " "of binary and continuous targets", metric, y_true, y_score)
, y_score in invalids: assert_raise_message(ValueError, "contains NaN, infinity", metric, y_true, y_score) @pytest.mark.parametrize('metric', CLASSIFICATION_METRICS.values()) def test_classification_inf_nan_input(metric): # Classification metrics all...
64
64
77
33
31
lqkweb/learnMLflow
scikit-learn-master/sklearn/metrics/tests/test_common.py
Python
test_classification_inf_nan_input
test_classification_inf_nan_input
710
717
710
712
c4f86acab81933363d4988a56c143ea428e86028
bigcode/the-stack
train