language stringclasses 4
values | return_type stringlengths 1 1.81k | code stringlengths 14 59k | code_with_masked_return_types stringlengths 14 59k |
|---|---|---|---|
Python | QueryDenomMetadataResponse | def query_bank_denom_metadata(self, denom: str) -> QueryDenomMetadataResponse:
res = self.bank_client.DenomMetadata(QueryDenomMetadataRequest(denom=denom))
return res | def query_bank_denom_metadata(self, denom: str) <MASK>
res = self.bank_client.DenomMetadata(QueryDenomMetadataRequest(denom=denom))
return res |
Python | QueryBalanceResponse | def query_account_balance(self, address: str) -> QueryBalanceResponse:
res = self.bank_client.Balance(
QueryBalanceRequest(address=address, denom=self.network.coin_base_denom)
)
return res | def query_account_balance(self, address: str) <MASK>
res = self.bank_client.Balance(
QueryBalanceRequest(address=address, denom=self.network.coin_base_denom)
)
return res |
Python | int | def edit_distance(s1: str, s2: str) -> int:
if len(s1) < len(s2):
return edit_distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous... | def edit_distance(s1: str, s2: str) <MASK>
if len(s1) < len(s2):
return edit_distance(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_... |
Python | Dict[str, str] | def find_correct_spelling(model: FastText, incorrect_word: str, num_neighbours: int, clean_vocab_counter: Counter,
mixed_vocab_counter: Counter, mixed_vocab_min_freq: int,
max_edit_distance: int) -> Dict[str, str]:
correct_word, message = '', ''
mixed_vocab_se... | def find_correct_spelling(model: FastText, incorrect_word: str, num_neighbours: int, clean_vocab_counter: Counter,
mixed_vocab_counter: Counter, mixed_vocab_min_freq: int,
max_edit_distance: int) <MASK>
correct_word, message = '', ''
mixed_vocab_set = set()
... |
Python | Unit | def default_unit(key: str) -> Unit:
units = {
'temp': Unit(Unit.degree_symbol()+"C"),
'deg': Unit(Unit.degree_symbol()),
'speed': Unit('m/sec'),
'presssure': Unit('hPa'),
'humidity': Unit('%'),
}
return units[key] if key in units else None | def default_unit(key: str) <MASK>
units = {
'temp': Unit(Unit.degree_symbol()+"C"),
'deg': Unit(Unit.degree_symbol()),
'speed': Unit('m/sec'),
'presssure': Unit('hPa'),
'humidity': Unit('%'),
}
return units[key] if key in units else None |
Python | rx.Observable | def rx_fetch(self, zip: str) -> rx.Observable:
url = "http://"+self.host+'/data/2.5/weather'
def observable(observer, scheduler):
params = {'zip': zip, 'appid': self.api_key}
rsp = requests.get(url, params=params)
try:
rsp.raise_for_status()
... | def rx_fetch(self, zip: str) <MASK>
url = "http://"+self.host+'/data/2.5/weather'
def observable(observer, scheduler):
params = {'zip': zip, 'appid': self.api_key}
rsp = requests.get(url, params=params)
try:
rsp.raise_for_status()
obser... |
Python | WeatherForecast | def parse_weather(self, json: dict) -> WeatherForecast:
def observable(observer, scheduler):
try:
if len(json) == 0:
raise(Exception('No Weather Data'))
location = Location(id=json['id'])
location.name = json['name']
... | def parse_weather(self, json: dict) <MASK>
def observable(observer, scheduler):
try:
if len(json) == 0:
raise(Exception('No Weather Data'))
location = Location(id=json['id'])
location.name = json['name']
if 'sys' in ... |
Python | List[str] | def split(self, text: str) -> List[str]:
states = OrderedDict()
offsets = [0]
skip = None
for current, current_char in enumerate(text):
if skip and current < skip:
continue
to_remove = set()
reset = False
for start, trie_poi... | def split(self, text: str) <MASK>
states = OrderedDict()
offsets = [0]
skip = None
for current, current_char in enumerate(text):
if skip and current < skip:
continue
to_remove = set()
reset = False
for start, trie_pointer in... |
Python | str | def clean_up_tokenization(out_string: str) -> str:
out_string = (
out_string.replace(" .", ".")
.replace(" ?", "?")
.replace(" !", "!")
.replace(" ,", ",")
.replace(" ' ", "'")
.replace(" n't", "n't")
.re... | def clean_up_tokenization(out_string: str) <MASK>
out_string = (
out_string.replace(" .", ".")
.replace(" ?", "?")
.replace(" !", "!")
.replace(" ,", ",")
.replace(" ' ", "'")
.replace(" n't", "n't")
.rep... |
Python | int | def find_pivot(matrix, col: int) -> int:
col_terms = (matrix[line][col] for line in range(col, len(matrix)))
col_terms_abs = list(map(abs, col_terms))
max_abs = max(col_terms_abs)
return col_terms_abs.index(max_abs) + col | def find_pivot(matrix, col: int) <MASK>
col_terms = (matrix[line][col] for line in range(col, len(matrix)))
col_terms_abs = list(map(abs, col_terms))
max_abs = max(col_terms_abs)
return col_terms_abs.index(max_abs) + col |
Python | Iterator[ArchiveEntry] | def iter_extractall(self, outdir:str, **kwargs) -> Iterator[ArchiveEntry]:
with self.open() as arcfile:
for i, entry in enumerate(self.entries):
yield entry
with open(os.path.join(outdir, entry.fullname or str(i))) as dstfile:
self._extract(entry, ... | def iter_extractall(self, outdir:str, **kwargs) <MASK>
with self.open() as arcfile:
for i, entry in enumerate(self.entries):
yield entry
with open(os.path.join(outdir, entry.fullname or str(i))) as dstfile:
self._extract(entry, dstfile, arcfile, **... |
Python | List[globalentry] | def globalkey_read(vcode1seed:int, file) -> List[globalentry]:
import hashlib
if isinstance(file, str):
with open(file, 'rb') as f:
return globalkey_read(vcode1seed, f)
if isinstance(vcode1seed, (str,bytes,bytearray)):
vcode1 = vcode1seed
vcode1seed = vcode_seed(vcode1)
... | def globalkey_read(vcode1seed:int, file) <MASK>
import hashlib
if isinstance(file, str):
with open(file, 'rb') as f:
return globalkey_read(vcode1seed, f)
if isinstance(vcode1seed, (str,bytes,bytearray)):
vcode1 = vcode1seed
vcode1seed = vcode_seed(vcode1)
elif not isi... |
Python | NoReturn | def seed(self, seed:int) -> NoReturn:
if not isinstance(seed, int):
raise TypeError('{0.__class__.__name__} seed() argument \'seed\' must be an integer, not {1.__class__.__name__}'.format(self, seed))
elif not (0 <= seed <= 0xffffffff):
raise ValueError('{0.__class__.__name__} se... | def seed(self, seed:int) <MASK>
if not isinstance(seed, int):
raise TypeError('{0.__class__.__name__} seed() argument \'seed\' must be an integer, not {1.__class__.__name__}'.format(self, seed))
elif not (0 <= seed <= 0xffffffff):
raise ValueError('{0.__class__.__name__} seed() a... |
Python | NoReturn | def twist(self) -> NoReturn:
if self._index >= self._N+1:
self.seed(self.INITIAL_SEED)
state, N, M = self._state, self._N, self._M
mag01 = (0, self._MATRIX_A)
y = 0
for kk in range( 0, N-M):
y = (state[kk] & 0x80000000) | (state[kk+1] & 0x7fffffff)
... | def twist(self) <MASK>
if self._index >= self._N+1:
self.seed(self.INITIAL_SEED)
state, N, M = self._state, self._N, self._M
mag01 = (0, self._MATRIX_A)
y = 0
for kk in range( 0, N-M):
y = (state[kk] & 0x80000000) | (state[kk+1] & 0x7fffffff)
... |
Python | int | def genrand(self) -> int:
if self._index >= self._N:
self.twist()
y = self._state[self._index]
self._index += 1
return self.temper(y) | def genrand(self) <MASK>
if self._index >= self._N:
self.twist()
y = self._state[self._index]
self._index += 1
return self.temper(y) |
Python | float | def genrand_real1(self) -> float:
y = self.genrand()
return (y * 2.3283064370807974e-10) | def genrand_real1(self) <MASK>
y = self.genrand()
return (y * 2.3283064370807974e-10) |
Python | float | def genrand_real2(self) -> float:
y = self.genrand()
return (y * 2.3283064365386963e-10) | def genrand_real2(self) <MASK>
y = self.genrand()
return (y * 2.3283064365386963e-10) |
Python | float | def genrand_real3(self) -> float:
y = self.genrand()
return ((y + 1.0) * 2.3283064359965952e-10) | def genrand_real3(self) <MASK>
y = self.genrand()
return ((y + 1.0) * 2.3283064359965952e-10) |
Python | int | def temper(cls, y:int) -> int:
y ^= (y >> cls._SHIFT_U)
y ^= (y << cls._SHIFT_S) & cls._MASK_B
y ^= (y << cls._SHIFT_T) & cls._MASK_C
y ^= (y >> cls._SHIFT_L)
return y & 0xffffffff | def temper(cls, y:int) <MASK>
y ^= (y >> cls._SHIFT_U)
y ^= (y << cls._SHIFT_S) & cls._MASK_B
y ^= (y << cls._SHIFT_T) & cls._MASK_C
y ^= (y >> cls._SHIFT_L)
return y & 0xffffffff |
Python | int | def untemper(cls, y:int) -> int:
y ^= (y >> cls._SHIFT_L)
y ^= (y << cls._SHIFT_T) & cls._MASK_C
for _ in range(7):
y ^= (y << cls._SHIFT_S) & cls._MASK_B
for _ in range(3):
y ^= (y >> cls._SHIFT_U)
return y & 0xffffffff | def untemper(cls, y:int) <MASK>
y ^= (y >> cls._SHIFT_L)
y ^= (y << cls._SHIFT_T) & cls._MASK_C
for _ in range(7):
y ^= (y << cls._SHIFT_S) & cls._MASK_B
for _ in range(3):
y ^= (y >> cls._SHIFT_U)
return y & 0xffffffff |
Python | int | def mt_genrand(seed:int) -> int:
if not isinstance(seed, int):
raise TypeError('mt_genrand() argument \'seed\' must be an integer, not {0.__class__.__name__}'.format(seed))
elif not (0 <= seed <= 0xffffffff):
raise ValueError('mt_genrand() argument \'seed\' must be a 32-bit unsigned integer, not... | def mt_genrand(seed:int) <MASK>
if not isinstance(seed, int):
raise TypeError('mt_genrand() argument \'seed\' must be an integer, not {0.__class__.__name__}'.format(seed))
elif not (0 <= seed <= 0xffffffff):
raise ValueError('mt_genrand() argument \'seed\' must be a 32-bit unsigned integer, not ... |
Python | Union[int,str,None] | def cast_entry(entry:Union[pefile.ResourceDataEntryData,pefile.UnicodeStringWrapperPostProcessor,None]) -> Union[int,str,None]:
if entry is None:
return None
elif isinstance(entry, pefile.ResourceDirEntryData):
return entry.name.decode() if entry.name is not None else entry.id
elif isinstance(en... | def cast_entry(entry:Union[pefile.ResourceDataEntryData,pefile.UnicodeStringWrapperPostProcessor,None]) <MASK>
if entry is None:
return None
elif isinstance(entry, pefile.ResourceDirEntryData):
return entry.name.decode() if entry.name is not None else entry.id
elif isinstance(entry, pefile.Unico... |
Python | 'ResourceName' | def from_entry(entry:Union[pefile.ResourceDataEntryData,pefile.UnicodeStringWrapperPostProcessor,None]) -> 'ResourceName':
if entry is None:
return ResourceName(None)
elif isinstance(entry, pefile.ResourceDirEntryData):
return ResourceName(entry.name.decode() if entry.name is not None else entry.id)... | def from_entry(entry:Union[pefile.ResourceDataEntryData,pefile.UnicodeStringWrapperPostProcessor,None]) <MASK>
if entry is None:
return ResourceName(None)
elif isinstance(entry, pefile.ResourceDirEntryData):
return ResourceName(entry.name.decode() if entry.name is not None else entry.id)
elif is... |
Python | bool | def _validate_order(order: "Order") -> bool:
if not order.lines.exists():
return False
shipping_address = order.shipping_address
is_shipping_required = order.is_shipping_required()
address = shipping_address or order.billing_address
return _validate_adddress_details(
shipping_address... | def _validate_order(order: "Order") <MASK>
if not order.lines.exists():
return False
shipping_address = order.shipping_address
is_shipping_required = order.is_shipping_required()
address = shipping_address or order.billing_address
return _validate_adddress_details(
shipping_address, ... |
Python | bool | def _validate_checkout(checkout: "Checkout") -> bool:
if not checkout.lines.exists():
logger.debug("Checkout Lines do NOT exist")
return False
shipping_address = checkout.shipping_address
is_shipping_required = checkout.is_shipping_required
address = shipping_address or checkout.billing_... | def _validate_checkout(checkout: "Checkout") <MASK>
if not checkout.lines.exists():
logger.debug("Checkout Lines do NOT exist")
return False
shipping_address = checkout.shipping_address
is_shipping_required = checkout.is_shipping_required
address = shipping_address or checkout.billing_ad... |
Python | render_template | def show_transaction_page(data: DecodedTransaction) -> render_template:
return (
render_template(
"transaction.html",
eth_price=deps.get_eth_price(),
transaction=data.metadata,
events=data.events,
call=data.calls,
transfers=data.transfe... | def show_transaction_page(data: DecodedTransaction) <MASK>
return (
render_template(
"transaction.html",
eth_price=deps.get_eth_price(),
transaction=data.metadata,
events=data.events,
call=data.calls,
transfers=data.transfers,
... |
Python | Optional[str] | def conv_zertifikat_string(input_str: Optional[str]) -> Optional[str]:
if input_str is None:
return None
else:
conv_str = str(input_str).strip().lower().replace("-", " ")
if conv_str in ("?", "", "x"):
return None
return ZERTIFIKAT_MAPPING[conv_str] | def conv_zertifikat_string(input_str: Optional[str]) <MASK>
if input_str is None:
return None
else:
conv_str = str(input_str).strip().lower().replace("-", " ")
if conv_str in ("?", "", "x"):
return None
return ZERTIFIKAT_MAPPING[conv_str] |
Python | Optional[float] | def conv_ee_anteil(input_value: Optional[Union[str, float, int]]) -> Optional[float]:
if input_value is None:
return None
if isinstance(input_value, int) or isinstance(input_value, float):
number = float(input_value)
else:
try:
number = float(str(input_value.replace("%", ... | def conv_ee_anteil(input_value: Optional[Union[str, float, int]]) <MASK>
if input_value is None:
return None
if isinstance(input_value, int) or isinstance(input_value, float):
number = float(input_value)
else:
try:
number = float(str(input_value.replace("%", "")))
... |
Python | bool | def conv_bool(input_value: Optional[Union[str, int, bool]]) -> bool:
if input_value is None:
return False
elif input_value is False or str(input_value).lower() in ("false", "", "no"):
return False
elif input_value == 0:
return False
else:
return True | def conv_bool(input_value: Optional[Union[str, int, bool]]) <MASK>
if input_value is None:
return False
elif input_value is False or str(input_value).lower() in ("false", "", "no"):
return False
elif input_value == 0:
return False
else:
return True |
Python | Dict[str, Dict[str, str]] | def program_catalogue_data(src: Optional[str] = None) -> Dict[str, Dict[str, str]]:
if src is None:
src = URL_USASK_PROGRAMS_LIST
else:
src = str(src)
content = get_content(src)
return parse_fields(content, src) | def program_catalogue_data(src: Optional[str] = None) <MASK>
if src is None:
src = URL_USASK_PROGRAMS_LIST
else:
src = str(src)
content = get_content(src)
return parse_fields(content, src) |
Python | Dict[str, Dict[str, str]] | def parse_fields(content: str, base_href: str = '') -> Dict[str, Dict[str, str]]:
html_root = html5lib.parse(content)
css_root = cssselect2.ElementWrapper.from_html_root(html_root)
section_heading_selector = 'section.uofs-section h1'
data = {
get_cleaned_text(section): section_data(section, base... | def parse_fields(content: str, base_href: str = '') <MASK>
html_root = html5lib.parse(content)
css_root = cssselect2.ElementWrapper.from_html_root(html_root)
section_heading_selector = 'section.uofs-section h1'
data = {
get_cleaned_text(section): section_data(section, base_href)
for sect... |
Python | dict | def field_data(content: str, base_href: str) -> dict:
root = cssselect2.ElementWrapper.from_html_root(
html5lib.parse(content))
links_selector = 'section#Programs ul>li>a'
links = root.query_all(links_selector)
programs_in_subject = {
clean_whitespace(element.etree_element.text):
... | def field_data(content: str, base_href: str) <MASK>
root = cssselect2.ElementWrapper.from_html_root(
html5lib.parse(content))
links_selector = 'section#Programs ul>li>a'
links = root.query_all(links_selector)
programs_in_subject = {
clean_whitespace(element.etree_element.text):
... |
Python | str | def program_page(program: str, field: str, level: str) -> str:
program_page_url = program_url(field, level, program)
content = get_content(program_page_url)
return content | def program_page(program: str, field: str, level: str) <MASK>
program_page_url = program_url(field, level, program)
content = get_content(program_page_url)
return content |
Python | dict | def parse_program(content: str) -> dict:
content_root = cssselect2.ElementWrapper.from_html_root(html5lib.parse(content))
selector_section_heading = 'section.uofs-section h1'
section_headings = content_root.query_all(selector_section_heading)
return {
clean_whitespace(heading.etree_element.text)... | def parse_program(content: str) <MASK>
content_root = cssselect2.ElementWrapper.from_html_root(html5lib.parse(content))
selector_section_heading = 'section.uofs-section h1'
section_headings = content_root.query_all(selector_section_heading)
return {
clean_whitespace(heading.etree_element.text): ... |
Python | dict | def course_dict(heading: cssselect2.ElementWrapper) -> dict:
parent = heading.parent
selector = 'ul>li'
return {
code: get_course_url(code)
for code in course_codes(parent, selector)
} | def course_dict(heading: cssselect2.ElementWrapper) <MASK>
parent = heading.parent
selector = 'ul>li'
return {
code: get_course_url(code)
for code in course_codes(parent, selector)
} |
Python | Generator[str, Any, None] | def course_codes(parent: ElementWrapper, selector: str) -> Generator[str, Any, None]:
query: ElementWrapper = parent.query_all(selector)
children: Generator[str, Any, None] = (
clean_whitespace(list_item_node.etree_element.text)
for list_item_node in query
)
return children | def course_codes(parent: ElementWrapper, selector: str) <MASK>
query: ElementWrapper = parent.query_all(selector)
children: Generator[str, Any, None] = (
clean_whitespace(list_item_node.etree_element.text)
for list_item_node in query
)
return children |
Python | str | def wrapped(key: str) -> str:
try:
return cache.get(key)
except KeyError:
text = function(key)
cache.set(key, text)
return text | def wrapped(key: str) <MASK>
try:
return cache.get(key)
except KeyError:
text = function(key)
cache.set(key, text)
return text |
Python | Dict[Text, Any] | def parse_course(content: Text) -> Dict[Text, Any]:
root: ElementWrapper = ElementWrapper.from_html_root(
html5lib.parse(content))
description_node = root.query('section#Description'
'>div#Description-subsection-0')
selector_second_p = 'p:nth-child(2)'
selector_... | def parse_course(content: Text) <MASK>
root: ElementWrapper = ElementWrapper.from_html_root(
html5lib.parse(content))
description_node = root.query('section#Description'
'>div#Description-subsection-0')
selector_second_p = 'p:nth-child(2)'
selector_first_p = 'p:... |
Python | Dict[str, Any] | def generate_mapping(prerequisites_node: ElementWrapper, text: str) -> Dict[str, Any]:
data = {
"prerequisites":
course_data(prerequisites_node),
"summary":
clean_whitespace(text),
}
return data | def generate_mapping(prerequisites_node: ElementWrapper, text: str) <MASK>
data = {
"prerequisites":
course_data(prerequisites_node),
"summary":
clean_whitespace(text),
}
return data |
Python | str | def filename_from_url(key: str) -> str:
as_dict = urllib.parse.urlparse(key)._asdict()
exploded = as_dict.values()
base_name = SEP_DOT.join(exploded)
filename = f"{base_name}.html"
return filename | def filename_from_url(key: str) <MASK>
as_dict = urllib.parse.urlparse(key)._asdict()
exploded = as_dict.values()
base_name = SEP_DOT.join(exploded)
filename = f"{base_name}.html"
return filename |
Python | Path | def mkdir_path(path: PATH) -> Path:
resolve = Path(path).resolve()
try:
resolve.mkdir(parents=True,
exist_ok=True)
except FileExistsError:
print(f"File exists at {resolve}.", file=sys.stderr)
if not os.path.isdir(resolve):
raise NotADirectoryError(resolve)... | def mkdir_path(path: PATH) <MASK>
resolve = Path(path).resolve()
try:
resolve.mkdir(parents=True,
exist_ok=True)
except FileExistsError:
print(f"File exists at {resolve}.", file=sys.stderr)
if not os.path.isdir(resolve):
raise NotADirectoryError(resolve)
... |
Python | Generator[Path, None, None] | def dir_path(path: PATH) -> Generator[Path, None, None]:
path = Path(path)
assert path.is_dir()
return path.iterdir() | def dir_path(path: PATH) <MASK>
path = Path(path)
assert path.is_dir()
return path.iterdir() |
Python | str | def load(self, key: str) -> str:
path = self.file_path(key)
try:
result = path.read_text()
except FileNotFoundError:
raise KeyError('Key does not exist: ', key)
return result | def load(self, key: str) <MASK>
path = self.file_path(key)
try:
result = path.read_text()
except FileNotFoundError:
raise KeyError('Key does not exist: ', key)
return result |
Python | int | def save(self, filename: str, text: str) -> int:
file_path = self.file_path(filename)
return file_path.write_text(text) | def save(self, filename: str, text: str) <MASK>
file_path = self.file_path(filename)
return file_path.write_text(text) |
Python | str | def sanitize_filename(filename: str) -> str:
return re.sub(r'(?u)[^-\w.]', '', filename) | def sanitize_filename(filename: str) <MASK>
return re.sub(r'(?u)[^-\w.]', '', filename) |
Python | str | def clean_whitespace(text: str) -> str:
text = str(text or '')
stripped = text.strip()
sub = re.sub(r'\s+', ' ', stripped, )
return sub | def clean_whitespace(text: str) <MASK>
text = str(text or '')
stripped = text.strip()
sub = re.sub(r'\s+', ' ', stripped, )
return sub |
Python | Generator[Any, str, None] | def find_tag_with_text(node: cssselect2.ElementWrapper, tag: str, text: str) -> Generator[Any, str, None]:
return (
child_node.etree_element.tail
for child_node
in node.query_all(tag)
if clean_whitespace(child_node.etree_element.text) == text
) | def find_tag_with_text(node: cssselect2.ElementWrapper, tag: str, text: str) <MASK>
return (
child_node.etree_element.tail
for child_node
in node.query_all(tag)
if clean_whitespace(child_node.etree_element.text) == text
) |
Python | dict | def init_notebook_resources(self) -> dict:
resources = {}
resources['unique_key'] = self.output
if self.config.inline.enabled and self.config.inline.solution:
resources['output_files_dir'] = os.path.join(os.pardir, f'{self.output}_files')
else:
resources['output_f... | def init_notebook_resources(self) <MASK>
resources = {}
resources['unique_key'] = self.output
if self.config.inline.enabled and self.config.inline.solution:
resources['output_files_dir'] = os.path.join(os.pardir, f'{self.output}_files')
else:
resources['output_fil... |
Python | ConfigEntry | def create_mock_myenergi_config_entry(
hass: HomeAssistant,
data: dict[str, Any] | None = None,
options: dict[str, Any] | None = None,
) -> ConfigEntry:
config_entry: MockConfigEntry = MockConfigEntry(
entry_id=TEST_CONFIG_ENTRY_ID,
domain=DOMAIN,
data=data or MOCK_CONFIG,
... | def create_mock_myenergi_config_entry(
hass: HomeAssistant,
data: dict[str, Any] | None = None,
options: dict[str, Any] | None = None,
) <MASK>
config_entry: MockConfigEntry = MockConfigEntry(
entry_id=TEST_CONFIG_ENTRY_ID,
domain=DOMAIN,
data=data or MOCK_CONFIG,
title="... |
Python | Tuple[np.ndarray, float] | def estep(X: np.ndarray, mixture: GaussianMixture) -> Tuple[np.ndarray, float]:
dim = X.shape[1]
exponents = np.sum((X[:, np.newaxis, :] - mixture.mu) ** 2, axis=2) / (2 * mixture.var[np.newaxis, :])
weighted_likelihoods = np.transpose(1 / ((2 * np.pi * mixture.var[:, np.newaxis]) ** (dim / 2))) * np.exp(
... | def estep(X: np.ndarray, mixture: GaussianMixture) <MASK>
dim = X.shape[1]
exponents = np.sum((X[:, np.newaxis, :] - mixture.mu) ** 2, axis=2) / (2 * mixture.var[np.newaxis, :])
weighted_likelihoods = np.transpose(1 / ((2 * np.pi * mixture.var[:, np.newaxis]) ** (dim / 2))) * np.exp(
-exponents) * m... |
Python | GaussianMixture | def mstep(X: np.ndarray, post: np.ndarray) -> GaussianMixture:
dim = X.shape[1]
weight = np.sum(post, axis=0) / X.shape[0]
mean = np.transpose(np.transpose(np.dot(np.transpose(post), X)) / np.sum(post, axis=0))
var = np.sum(np.sum((X[:, np.newaxis, :] - mean) ** 2, axis=2) * post, axis=0) / (dim * np.su... | def mstep(X: np.ndarray, post: np.ndarray) <MASK>
dim = X.shape[1]
weight = np.sum(post, axis=0) / X.shape[0]
mean = np.transpose(np.transpose(np.dot(np.transpose(post), X)) / np.sum(post, axis=0))
var = np.sum(np.sum((X[:, np.newaxis, :] - mean) ** 2, axis=2) * post, axis=0) / (dim * np.sum(post, axis=... |
Python | Tuple[np.ndarray, float] | def estep(X: np.ndarray, mixture: GaussianMixture) -> Tuple[np.ndarray, float]:
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
means = non_null_index[:, np.newaxis, :] * mixture.mu
quadratic = np.sum((X[:, np.newaxis, :] - means) ** 2, axis=2) / (2 * mixture.var[np.newa... | def estep(X: np.ndarray, mixture: GaussianMixture) <MASK>
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
means = non_null_index[:, np.newaxis, :] * mixture.mu
quadratic = np.sum((X[:, np.newaxis, :] - means) ** 2, axis=2) / (2 * mixture.var[np.newaxis, :])
normaliza... |
Python | GaussianMixture | def mstep(X: np.ndarray, post: np.ndarray, mixture: GaussianMixture,
min_variance: float = .25) -> GaussianMixture:
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
reduced_post = np.transpose(non_null_index.T[:, np.newaxis, :] * post.T)
no_update = np.sum(reduc... | def mstep(X: np.ndarray, post: np.ndarray, mixture: GaussianMixture,
min_variance: float = .25) <MASK>
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
reduced_post = np.transpose(non_null_index.T[:, np.newaxis, :] * post.T)
no_update = np.sum(reduced_post, axis... |
Python | np.ndarray | def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray:
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
means = non_null_index[:, np.newaxis, :] * mixture.mu
quadratic = np.sum((X[:, np.newaxis, :] - means) ** 2, axis=2) / (2 * mixture.var[np.newaxis, :])... | def fill_matrix(X: np.ndarray, mixture: GaussianMixture) <MASK>
non_null_index = X.astype(bool).astype(int)
dim = np.sum(non_null_index, axis=1)
means = non_null_index[:, np.newaxis, :] * mixture.mu
quadratic = np.sum((X[:, np.newaxis, :] - means) ** 2, axis=2) / (2 * mixture.var[np.newaxis, :])
nor... |
Python | http.client.HTTPResponse | def make_request(*args, **kwargs) -> http.client.HTTPResponse:
if "headers" not in kwargs:
kwargs["headers"] = _http_headers
return urllib.request.urlopen(urllib.request.Request(*args, **kwargs)) | def make_request(*args, **kwargs) <MASK>
if "headers" not in kwargs:
kwargs["headers"] = _http_headers
return urllib.request.urlopen(urllib.request.Request(*args, **kwargs)) |
Python | list[Symbol] | def find_symbols(self, text: str) -> list[Symbol]:
schedule.run_pending()
symbols = []
stocks = set(re.findall(self.STOCK_REGEX, text))
for stock in stocks:
if stock.upper() in self.stock.symbol_list["symbol"].values:
symbols.append(Stock(stock))
e... | def find_symbols(self, text: str) <MASK>
schedule.run_pending()
symbols = []
stocks = set(re.findall(self.STOCK_REGEX, text))
for stock in stocks:
if stock.upper() in self.stock.symbol_list["symbol"].values:
symbols.append(Stock(stock))
else:
... |
Python | str | def status(self, bot_resp) -> str:
stats = f"""
Bot Status:
{bot_resp}
Stock Market Data:
{self.stock.status()}
Cryptocurrency Data:
{self.crypto.status()}
"""
warning(stats)
return stats | def status(self, bot_resp) <MASK>
stats = f"""
Bot Status:
{bot_resp}
Stock Market Data:
{self.stock.status()}
Cryptocurrency Data:
{self.crypto.status()}
"""
warning(stats)
return stats |
Python | list[str] | def price_reply(self, symbols: list[Symbol]) -> list[str]:
replies = []
for symbol in symbols:
info(symbol)
if isinstance(symbol, Stock):
replies.append(self.stock.price_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.... | def price_reply(self, symbols: list[Symbol]) <MASK>
replies = []
for symbol in symbols:
info(symbol)
if isinstance(symbol, Stock):
replies.append(self.stock.price_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.... |
Python | list[str] | def dividend_reply(self, symbols: list) -> list[str]:
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.dividend_reply(symbol))
elif isinstance(symbol, Coin):
replies.append("Cryptocurrencies do no have Div... | def dividend_reply(self, symbols: list) <MASK>
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.dividend_reply(symbol))
elif isinstance(symbol, Coin):
replies.append("Cryptocurrencies do no have Dividends.... |
Python | list[str] | def news_reply(self, symbols: list) -> list[str]:
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.news_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(
"News is not yet su... | def news_reply(self, symbols: list) <MASK>
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.news_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(
"News is not yet supported... |
Python | list[str] | def info_reply(self, symbols: list) -> list[str]:
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.info_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.info_reply(symbol))
... | def info_reply(self, symbols: list) <MASK>
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.info_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.info_reply(symbol))
els... |
Python | pd.DataFrame | def intra_reply(self, symbol: Symbol) -> pd.DataFrame:
if isinstance(symbol, Stock):
return self.stock.intra_reply(symbol)
elif isinstance(symbol, Coin):
return self.crypto.intra_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
return ... | def intra_reply(self, symbol: Symbol) <MASK>
if isinstance(symbol, Stock):
return self.stock.intra_reply(symbol)
elif isinstance(symbol, Coin):
return self.crypto.intra_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
return pd.DataFra... |
Python | pd.DataFrame | def chart_reply(self, symbol: Symbol) -> pd.DataFrame:
if isinstance(symbol, Stock):
return self.stock.chart_reply(symbol)
elif isinstance(symbol, Coin):
return self.crypto.chart_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
return ... | def chart_reply(self, symbol: Symbol) <MASK>
if isinstance(symbol, Stock):
return self.stock.chart_reply(symbol)
elif isinstance(symbol, Coin):
return self.crypto.chart_reply(symbol)
else:
debug(f"{symbol} is not a Stock or Coin")
return pd.DataFra... |
Python | list[str] | def stat_reply(self, symbols: list[Symbol]) -> list[str]:
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.stat_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.stat_reply(symbol))
... | def stat_reply(self, symbols: list[Symbol]) <MASK>
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.stat_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.stat_reply(symbol))
... |
Python | list[str] | def cap_reply(self, symbols: list[Symbol]) -> list[str]:
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.cap_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.cap_reply(symbol))
... | def cap_reply(self, symbols: list[Symbol]) <MASK>
replies = []
for symbol in symbols:
if isinstance(symbol, Stock):
replies.append(self.stock.cap_reply(symbol))
elif isinstance(symbol, Coin):
replies.append(self.crypto.cap_reply(symbol))
... |
Python | str | def trending(self) -> str:
stocks = self.stock.trending()
coins = self.crypto.trending()
reply = ""
if self.trending_count:
reply += "🔥Trending on the Stock Bot:\n`"
reply += "━" * len("Trending on the Stock Bot:") + "`\n"
sorted_trending = [
... | def trending(self) <MASK>
stocks = self.stock.trending()
coins = self.crypto.trending()
reply = ""
if self.trending_count:
reply += "🔥Trending on the Stock Bot:\n`"
reply += "━" * len("Trending on the Stock Bot:") + "`\n"
sorted_trending = [
... |
Python | list[str] | def batch_price_reply(self, symbols: list[Symbol]) -> list[str]:
replies = []
stocks = []
coins = []
for symbol in symbols:
if isinstance(symbol, Stock):
stocks.append(symbol)
elif isinstance(symbol, Coin):
coins.append(symbol)
... | def batch_price_reply(self, symbols: list[Symbol]) <MASK>
replies = []
stocks = []
coins = []
for symbol in symbols:
if isinstance(symbol, Stock):
stocks.append(symbol)
elif isinstance(symbol, Coin):
coins.append(symbol)
... |
Python | str | def status(self) -> str:
status = r.get(
"https://api.coingecko.com/api/v3/ping",
timeout=5,
)
try:
status.raise_for_status()
return f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
... | def status(self) <MASK>
status = r.get(
"https://api.coingecko.com/api/v3/ping",
timeout=5,
)
try:
status.raise_for_status()
return f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
... |
Python | str | def price_reply(self, coin: Coin) -> str:
if resp := self.get(
"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
):
try:
data = res... | def price_reply(self, coin: Coin) <MASK>
if resp := self.get(
"/simple/price",
params={
"ids": coin.id,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
):
try:
data = resp... |
Python | pd.DataFrame | def intra_reply(self, symbol: Coin) -> pd.DataFrame:
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 1},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropna... | def intra_reply(self, symbol: Coin) <MASK>
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 1},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropna()
... |
Python | pd.DataFrame | def chart_reply(self, symbol: Coin) -> pd.DataFrame:
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 30},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropn... | def chart_reply(self, symbol: Coin) <MASK>
if resp := self.get(
f"/coins/{symbol.id}/ohlc",
params={"vs_currency": self.vs_currency, "days": 30},
):
df = pd.DataFrame(
resp, columns=["Date", "Open", "High", "Low", "Close"]
).dropna()
... |
Python | str | def stat_reply(self, symbol: Coin) -> str:
if data := self.get(
f"/coins/{symbol.id}",
params={
"localization": "false",
},
):
return f"""
[{data['name']}]({data['links']['homepage'][0]}) Statistics:
Market C... | def stat_reply(self, symbol: Coin) <MASK>
if data := self.get(
f"/coins/{symbol.id}",
params={
"localization": "false",
},
):
return f"""
[{data['name']}]({data['links']['homepage'][0]}) Statistics:
Market Ca... |
Python | list[str] | def trending(self) -> list[str]:
coins = self.get("/search/trending")
try:
trending = []
for coin in coins["coins"]:
c = coin["item"]
sym = c["symbol"].upper()
name = c["name"]
change = self.get(
... | def trending(self) <MASK>
coins = self.get("/search/trending")
try:
trending = []
for coin in coins["coins"]:
c = coin["item"]
sym = c["symbol"].upper()
name = c["name"]
change = self.get(
f"/simp... |
Python | list[str] | def batch_price(self, coins: list[Coin]) -> list[str]:
query = ",".join([c.id for c in coins])
prices = self.get(
f"/simple/price",
params={
"ids": query,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
... | def batch_price(self, coins: list[Coin]) <MASK>
query = ",".join([c.id for c in coins])
prices = self.get(
f"/simple/price",
params={
"ids": query,
"vs_currencies": self.vs_currency,
"include_24hr_change": "true",
},
... |
Python | str | def status(self) -> str:
if self.IEX_TOKEN == "":
return "The `IEX_TOKEN` is not set so Stock Market data is not available."
resp = r.get(
"https://pjmps0c34hp7.statuspage.io/api/v2/status.json",
timeout=15,
)
if resp.status_code == 200:
st... | def status(self) <MASK>
if self.IEX_TOKEN == "":
return "The `IEX_TOKEN` is not set so Stock Market data is not available."
resp = r.get(
"https://pjmps0c34hp7.statuspage.io/api/v2/status.json",
timeout=15,
)
if resp.status_code == 200:
sta... |
Python | str | def price_reply(self, symbol: Stock) -> str:
if IEXData := self.get(f"/stock/{symbol.id}/quote"):
if symbol.symbol.upper() in self.otc_list:
return f"OTC - {symbol.symbol.upper()}, {IEXData['companyName']} most recent price is: $**{IEXData['latestPrice']}**"
keys = (
... | def price_reply(self, symbol: Stock) <MASK>
if IEXData := self.get(f"/stock/{symbol.id}/quote"):
if symbol.symbol.upper() in self.otc_list:
return f"OTC - {symbol.symbol.upper()}, {IEXData['companyName']} most recent price is: $**{IEXData['latestPrice']}**"
keys = (
... |
Python | str | def dividend_reply(self, symbol: Stock) -> str:
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if resp := self.get(f"/stock/{symbol.id}/dividends/next"):
try:
IEXData = resp[0]
except IndexError as... | def dividend_reply(self, symbol: Stock) <MASK>
if symbol.symbol.upper() in self.otc_list:
return "OTC stocks do not currently support any commands."
if resp := self.get(f"/stock/{symbol.id}/dividends/next"):
try:
IEXData = resp[0]
except IndexError as ... |
Python | str | def cap_reply(self, symbol: Stock) -> str:
if data := self.get(f"/stock/{symbol.id}/stats"):
try:
cap = data["marketcap"]
except KeyError:
return f"{symbol.id} returned an error."
message = f"The current market cap of {symbol.name} is $**{cap:,... | def cap_reply(self, symbol: Stock) <MASK>
if data := self.get(f"/stock/{symbol.id}/stats"):
try:
cap = data["marketcap"]
except KeyError:
return f"{symbol.id} returned an error."
message = f"The current market cap of {symbol.name} is $**{cap:,.... |
Python | pd.DataFrame | def intra_reply(self, symbol: Stock) -> pd.DataFrame:
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
if data := self.get(f"/stock/{symbol.id}/intraday-prices"):
... | def intra_reply(self, symbol: Stock) <MASK>
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
if data := self.get(f"/stock/{symbol.id}/intraday-prices"):
df = pd... |
Python | pd.DataFrame | def chart_reply(self, symbol: Stock) -> pd.DataFrame:
schedule.run_pending()
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
try:
return self.charts[... | def chart_reply(self, symbol: Stock) <MASK>
schedule.run_pending()
if symbol.symbol.upper() in self.otc_list:
return pd.DataFrame()
if symbol.id.upper() not in list(self.symbol_list["symbol"]):
return pd.DataFrame()
try:
return self.charts[symbol.id.... |
Python | Any | def deserialize(self, string: str) -> Any:
try:
return self._deserializer(string)
except (ValueError, TypeError):
return string | def deserialize(self, string: str) <MASK>
try:
return self._deserializer(string)
except (ValueError, TypeError):
return string |
Python | Response | def prep_response(self, resp: Response, deserialize: bool = True) -> Response:
if deserialize:
resp.body = self.deserialize(resp.raw_body)
if isinstance(resp.body, dict):
resp.error_code = resp.body.get("errorNum")
resp.error_message = resp.body.get("error... | def prep_response(self, resp: Response, deserialize: bool = True) <MASK>
if deserialize:
resp.body = self.deserialize(resp.raw_body)
if isinstance(resp.body, dict):
resp.error_code = resp.body.get("errorNum")
resp.error_message = resp.body.get("errorMessag... |
Python | Response | def prep_bulk_err_response(self, parent_response: Response, body: Json) -> Response:
resp = Response(
method=parent_response.method,
url=parent_response.url,
headers=parent_response.headers,
status_code=parent_response.status_code,
status_text=parent_r... | def prep_bulk_err_response(self, parent_response: Response, body: Json) <MASK>
resp = Response(
method=parent_response.method,
url=parent_response.url,
headers=parent_response.headers,
status_code=parent_response.status_code,
status_text=parent_respons... |
Python | int | def ping(self) -> int:
request = Request(method="get", endpoint="/_api/collection")
resp = self.send_request(request)
if resp.status_code in {401, 403}:
raise ServerConnectionError("bad username and/or password")
if not resp.is_success:
raise ServerConnectionErr... | def ping(self) <MASK>
request = Request(method="get", endpoint="/_api/collection")
resp = self.send_request(request)
if resp.status_code in {401, 403}:
raise ServerConnectionError("bad username and/or password")
if not resp.is_success:
raise ServerConnectionErro... |
Python | Response | def send_request(self, request: Request) -> Response:
raise NotImplementedError | def send_request(self, request: Request) <MASK>
raise NotImplementedError |
Python | Response | def send_request(self, request: Request) -> Response:
host_index = self._host_resolver.get_host_index()
resp = self._http.send_request(
session=self._sessions[host_index],
method=request.method,
url=self._url_prefixes[host_index] + request.endpoint,
params... | def send_request(self, request: Request) <MASK>
host_index = self._host_resolver.get_host_index()
resp = self._http.send_request(
session=self._sessions[host_index],
method=request.method,
url=self._url_prefixes[host_index] + request.endpoint,
params=reque... |
Python | Response | def send_request(self, request: Request) -> Response:
host_index = self._host_resolver.get_host_index()
if self._auth_header is not None:
request.headers["Authorization"] = self._auth_header
resp = self._http.send_request(
session=self._sessions[host_index],
m... | def send_request(self, request: Request) <MASK>
host_index = self._host_resolver.get_host_index()
if self._auth_header is not None:
request.headers["Authorization"] = self._auth_header
resp = self._http.send_request(
session=self._sessions[host_index],
method=... |
Python | Response | def send_request(self, request: Request) -> Response:
host_index = self._host_resolver.get_host_index()
request.headers["Authorization"] = self._auth_header
resp = self._http.send_request(
session=self._sessions[host_index],
method=request.method,
url=self._ur... | def send_request(self, request: Request) <MASK>
host_index = self._host_resolver.get_host_index()
request.headers["Authorization"] = self._auth_header
resp = self._http.send_request(
session=self._sessions[host_index],
method=request.method,
url=self._url_pref... |
Python | Sequence[str] | def hosts(self) -> Sequence[str]:
return self._hosts | def hosts(self) <MASK>
return self._hosts |
Python | StandardDatabase | def db(
self,
name: str = "_system",
username: str = "root",
password: str = "",
verify: bool = False,
auth_method: str = "basic",
superuser_token: Optional[str] = None,
) -> StandardDatabase:
connection: Connection
if superuser_token is not No... | def db(
self,
name: str = "_system",
username: str = "root",
password: str = "",
verify: bool = False,
auth_method: str = "basic",
superuser_token: Optional[str] = None,
) <MASK>
connection: Connection
if superuser_token is not None:
... |
Python | Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]] | def forward(
self,
x: torch.Tensor,
state_init: Tuple[torch.Tensor, torch.Tensor],
) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
seq_length, batch_sz, _ = x.shape
if self.reverse:
x = x.flip(0)
x = torch.unbind(x, dim=0)
h_0, c_0 = s... | def forward(
self,
x: torch.Tensor,
state_init: Tuple[torch.Tensor, torch.Tensor],
) <MASK>
seq_length, batch_sz, _ = x.shape
if self.reverse:
x = x.flip(0)
x = torch.unbind(x, dim=0)
h_0, c_0 = state_init
h_n = [h_0]
c_n = [c_0]
... |
Python | Dict[str, torch.tensor] | def compute_microbatch_grad_sample(
self,
x: torch.Tensor,
module: nn.Module,
batch_first=True,
loss_reduction="mean",
) -> Dict[str, torch.tensor]:
torch.set_deterministic(True)
torch.manual_seed(0)
np.random.seed(0)
module = ModelWithLoss(clo... | def compute_microbatch_grad_sample(
self,
x: torch.Tensor,
module: nn.Module,
batch_first=True,
loss_reduction="mean",
) <MASK>
torch.set_deterministic(True)
torch.manual_seed(0)
np.random.seed(0)
module = ModelWithLoss(clone_module(module), lo... |
Python | Dict[str, torch.tensor] | def compute_opacus_grad_sample(
self,
x: torch.Tensor,
module: nn.Module,
batch_first=True,
loss_reduction="mean",
) -> Dict[str, torch.tensor]:
torch.set_deterministic(True)
torch.manual_seed(0)
np.random.seed(0)
gs_module = clone_module(modul... | def compute_opacus_grad_sample(
self,
x: torch.Tensor,
module: nn.Module,
batch_first=True,
loss_reduction="mean",
) <MASK>
torch.set_deterministic(True)
torch.manual_seed(0)
np.random.seed(0)
gs_module = clone_module(module)
opacus.aut... |
Python | Distro | def guess_distro() -> Distro:
if shutil.which('apt') or shutil.which('apt-get'):
return Distro.debian_derivative
if shutil.which('dnf'):
return Distro.fedora_derivative
return Distro.unknown | def guess_distro() <MASK>
if shutil.which('apt') or shutil.which('apt-get'):
return Distro.debian_derivative
if shutil.which('dnf'):
return Distro.fedora_derivative
return Distro.unknown |
Python | bool | def pypi_version_exists(package_name: str, version: str) -> bool:
l = pypi_versions(package_name)
if not version in l:
sys.stderr.write(
_(
"The specified PyQt5 version does not exist. Valid versions are: {}."
).format(', '.join(l)) + "\n"
)
return... | def pypi_version_exists(package_name: str, version: str) <MASK>
l = pypi_versions(package_name)
if not version in l:
sys.stderr.write(
_(
"The specified PyQt5 version does not exist. Valid versions are: {}."
).format(', '.join(l)) + "\n"
)
return F... |
Python | str | def make_distro_packager_command(distro_family: Distro,
packages: str,
interactive: bool,
command: str='install',
sudo: bool=True) -> str:
installer = installer_cmds[distro_family]
... | def make_distro_packager_command(distro_family: Distro,
packages: str,
interactive: bool,
command: str='install',
sudo: bool=True) <MASK>
installer = installer_cmds[distro_family]
... |
Python | str | def make_distro_mark_commmand(distro_family: Distro,
packages: str,
interactive: bool,
sudo: bool=True) -> str:
marker, command = manually_mark_cmds[distro_family]
cmd = shutil.which(marker)
if sudo:
... | def make_distro_mark_commmand(distro_family: Distro,
packages: str,
interactive: bool,
sudo: bool=True) <MASK>
marker, command = manually_mark_cmds[distro_family]
cmd = shutil.which(marker)
if sudo:
... |
Python | str | def python_package_version(package: str) -> str:
try:
return pkg_resources.get_distribution(package).version
except pkg_resources.DistributionNotFound:
return '' | def python_package_version(package: str) <MASK>
try:
return pkg_resources.get_distribution(package).version
except pkg_resources.DistributionNotFound:
return '' |
Python | int | def popen_capture_output(cmd: str) -> int:
with Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
print(line, end='')
p.wait()
i = p.returncode
return i | def popen_capture_output(cmd: str) <MASK>
with Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
print(line, end='')
p.wait()
i = p.returncode
return i |
Python | int | def install_pygobject_from_pip() -> int:
cmd = make_pip_command(
'install {} -U --disable-pip-version-check pycairo'.format(pip_user)
)
i = popen_capture_output(cmd)
if i != 0:
return i
cmd = make_pip_command(
'install {} -U --disable-pip-version-check PyGObject'.format(pip_u... | def install_pygobject_from_pip() <MASK>
cmd = make_pip_command(
'install {} -U --disable-pip-version-check pycairo'.format(pip_user)
)
i = popen_capture_output(cmd)
if i != 0:
return i
cmd = make_pip_command(
'install {} -U --disable-pip-version-check PyGObject'.format(pip_us... |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 27