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_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
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_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
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_set = set() for word, freq in mixed_vocab_counter.most_common(): if freq >= mixed_vocab_min_freq: mixed_vocab_set.add(word) if incorrect_word in clean_vocab_counter or incorrect_word in mixed_vocab_set: message = f'{incorrect_word} is already correctly spelled' else: tups = model.wv.most_similar(incorrect_word, topn=num_neighbours) candidates = [candidate for candidate, _ in tups] for candidate in candidates: if candidate in clean_vocab_counter and edit_distance(incorrect_word, candidate) <= max_edit_distance: correct_word = candidate break if correct_word == '': for candidate in candidates: if candidate in mixed_vocab_set and edit_distance(incorrect_word, candidate) <= max_edit_distance: correct_word = candidate break if correct_word == '': message = 'Correct spelling not found' return {'incorrect_word': incorrect_word, 'correct_word': correct_word, 'message': message}
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() for word, freq in mixed_vocab_counter.most_common(): if freq >= mixed_vocab_min_freq: mixed_vocab_set.add(word) if incorrect_word in clean_vocab_counter or incorrect_word in mixed_vocab_set: message = f'{incorrect_word} is already correctly spelled' else: tups = model.wv.most_similar(incorrect_word, topn=num_neighbours) candidates = [candidate for candidate, _ in tups] for candidate in candidates: if candidate in clean_vocab_counter and edit_distance(incorrect_word, candidate) <= max_edit_distance: correct_word = candidate break if correct_word == '': for candidate in candidates: if candidate in mixed_vocab_set and edit_distance(incorrect_word, candidate) <= max_edit_distance: correct_word = candidate break if correct_word == '': message = 'Correct spelling not found' return {'incorrect_word': incorrect_word, 'correct_word': correct_word, 'message': message}
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() observer.on_next(rsp.json()) observer.on_completed() except requests.HTTPError as e: observer.on_error(e) return lambda: None return rx.create(observable)
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() observer.on_next(rsp.json()) observer.on_completed() except requests.HTTPError as e: observer.on_error(e) return lambda: None return rx.create(observable)
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'] if 'sys' in json: sys = json['sys'] location.country = sys['country'] sunrise = SolarTimes.utc_to_localdatetime(sys['sunrise']) sunset = SolarTimes.utc_to_localdatetime(sys['sunset']) location.solar = SolarTimes(sunrise, sunset) else: raise Exception("Weather data invalid, missing 'sys'") weather = WeatherForecast(location) if 'coord' in json: lat = json['coord']['lat'] lon = json['coord']['lon'] weather.location.geo_location = GeoPoint(lat, lon) if 'main' not in json: raise Exception("Weather data invalid, missing 'main'") main = json['main'] cc = ClimateCondition() cc.temperature = Measurement( main['temp'], default_unit('temp')) cc.humidity = Measurement( main['humidity'], default_unit('humidity')) if 'wind' in json: wind = json['wind'] speed = Measurement(wind['speed'], default_unit('speed')) dir = Measurement(wind['deg'], default_unit('deg')) cc.wind = Vector(speed, dir) if 'weather' in json: ps = json['weather'] params = [Parameter(p['main'], p['description']) for p in ps] cc.conditions = params weather.current = cc except Exception as e: observer.on_error(e) else: observer.on_next(weather) finally: return lambda: None return rx.create(observable)
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 json: sys = json['sys'] location.country = sys['country'] sunrise = SolarTimes.utc_to_localdatetime(sys['sunrise']) sunset = SolarTimes.utc_to_localdatetime(sys['sunset']) location.solar = SolarTimes(sunrise, sunset) else: raise Exception("Weather data invalid, missing 'sys'") weather = WeatherForecast(location) if 'coord' in json: lat = json['coord']['lat'] lon = json['coord']['lon'] weather.location.geo_location = GeoPoint(lat, lon) if 'main' not in json: raise Exception("Weather data invalid, missing 'main'") main = json['main'] cc = ClimateCondition() cc.temperature = Measurement( main['temp'], default_unit('temp')) cc.humidity = Measurement( main['humidity'], default_unit('humidity')) if 'wind' in json: wind = json['wind'] speed = Measurement(wind['speed'], default_unit('speed')) dir = Measurement(wind['deg'], default_unit('deg')) cc.wind = Vector(speed, dir) if 'weather' in json: ps = json['weather'] params = [Parameter(p['main'], p['description']) for p in ps] cc.conditions = params weather.current = cc except Exception as e: observer.on_error(e) else: observer.on_next(weather) finally: return lambda: None return rx.create(observable)
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_pointer in states.items(): if "" in trie_pointer: for lookstart, looktrie_pointer in states.items(): if lookstart > start: break elif lookstart < start: lookahead_index = current + 1 end = current + 1 else: lookahead_index = current end = current next_char = text[lookahead_index] if lookahead_index < len(text) else None while next_char in looktrie_pointer: looktrie_pointer = looktrie_pointer[next_char] lookahead_index += 1 if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index if lookahead_index == len(text): break next_char = text[lookahead_index] offsets.append(start) offsets.append(end) reset = True break elif current_char in trie_pointer: trie_pointer = trie_pointer[current_char] states[start] = trie_pointer else: to_remove.add(start) if reset: states = {} else: for start in to_remove: del states[start] if current_char in self.data: states[current] = self.data[current_char] for start, trie_pointer in states.items(): if "" in trie_pointer: end = len(text) offsets.append(start) offsets.append(end) break return self.cut_text(text, offsets)
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 states.items(): if "" in trie_pointer: for lookstart, looktrie_pointer in states.items(): if lookstart > start: break elif lookstart < start: lookahead_index = current + 1 end = current + 1 else: lookahead_index = current end = current next_char = text[lookahead_index] if lookahead_index < len(text) else None while next_char in looktrie_pointer: looktrie_pointer = looktrie_pointer[next_char] lookahead_index += 1 if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index if lookahead_index == len(text): break next_char = text[lookahead_index] offsets.append(start) offsets.append(end) reset = True break elif current_char in trie_pointer: trie_pointer = trie_pointer[current_char] states[start] = trie_pointer else: to_remove.add(start) if reset: states = {} else: for start in to_remove: del states[start] if current_char in self.data: states[current] = self.data[current_char] for start, trie_pointer in states.items(): if "" in trie_pointer: end = len(text) offsets.append(start) offsets.append(end) break return self.cut_text(text, offsets)
Python
str
def clean_up_tokenization(out_string: str) -> str: out_string = ( out_string.replace(" .", ".") .replace(" ?", "?") .replace(" !", "!") .replace(" ,", ",") .replace(" ' ", "'") .replace(" n't", "n't") .replace(" 'm", "'m") .replace(" 's", "'s") .replace(" 've", "'ve") .replace(" 're", "'re") ) return out_string
def clean_up_tokenization(out_string: str) <MASK> out_string = ( out_string.replace(" .", ".") .replace(" ?", "?") .replace(" !", "!") .replace(" ,", ",") .replace(" ' ", "'") .replace(" n't", "n't") .replace(" 'm", "'m") .replace(" 's", "'s") .replace(" 've", "'ve") .replace(" 're", "'re") ) return out_string
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, dstfile, arcfile, **kwargs)
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, **kwargs)
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) elif not isinstance(vcode1seed, int): raise TypeError('globalkey_read() first argument must be an int, str, or bytes-like object, not {0.__class__.__name__}'.format(vcode1seed)) bf = Blowfish(struct.pack('<I', vcode1seed)) file.seek(0, 2) length = file.tell() file.seek(0, 0) globalkeys = [] for i in range(length // 0x30): name, key = struct.unpack('<32s 16s', file.read(0x30)) name = name.rstrip(b'\x00').decode('cp932') md5hash = bf.decrypt(key) globalkeys.append(globalentry(name, md5hash)) return globalkeys
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 isinstance(vcode1seed, int): raise TypeError('globalkey_read() first argument must be an int, str, or bytes-like object, not {0.__class__.__name__}'.format(vcode1seed)) bf = Blowfish(struct.pack('<I', vcode1seed)) file.seek(0, 2) length = file.tell() file.seek(0, 0) globalkeys = [] for i in range(length // 0x30): name, key = struct.unpack('<32s 16s', file.read(0x30)) name = name.rstrip(b'\x00').decode('cp932') md5hash = bf.decrypt(key) globalkeys.append(globalentry(name, md5hash)) return globalkeys
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__} seed() argument \'seed\' must be an 32-bit unsigned integer, not {1!r}'.format(self, seed)) state, N, F = self._state, self._N, self._F self._index = N+1 for i in range(N): state[i] = (seed & 0xffff0000) seed = (F * seed + 1) & 0xffffffff state[i] |= (seed & 0xffff0000) >> 16 seed = (F * seed + 1) & 0xffffffff self._index = N
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() argument \'seed\' must be an 32-bit unsigned integer, not {1!r}'.format(self, seed)) state, N, F = self._state, self._N, self._F self._index = N+1 for i in range(N): state[i] = (seed & 0xffff0000) seed = (F * seed + 1) & 0xffffffff state[i] |= (seed & 0xffff0000) >> 16 seed = (F * seed + 1) & 0xffffffff self._index = N
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) state[kk] = state[kk+M] ^ (y >> 1) ^ mag01[y & 0x1] for kk in range(N-M, N-1): y = (state[kk] & 0x80000000) | (state[kk+1] & 0x7fffffff) state[kk] = state[kk-(N-M)] ^ (y >> 1) ^ mag01[y & 0x1] y = (state[N-1] & 0x80000000) | (state[0] & 0x7fffffff) state[N-1] ^= state[M-1] ^ (y >> 1) ^ mag01[y & 0x1] self._index = 0
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) state[kk] = state[kk+M] ^ (y >> 1) ^ mag01[y & 0x1] for kk in range(N-M, N-1): y = (state[kk] & 0x80000000) | (state[kk+1] & 0x7fffffff) state[kk] = state[kk-(N-M)] ^ (y >> 1) ^ mag01[y & 0x1] y = (state[N-1] & 0x80000000) | (state[0] & 0x7fffffff) state[N-1] ^= state[M-1] ^ (y >> 1) ^ mag01[y & 0x1] self._index = 0
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 {0!r}'.format(seed)) cls = MersenneTwister M, F = cls._M, cls._F mag01 = (0, cls._MATRIX_A) y = (seed & 0x80000000) , 0xffff0000 & UPPER_MASK seed = (F * seed + 1) & 0xffffffff seed = (F * seed + 1) & 0xffffffff y |= (seed & 0x7fff0000) , 0xffff0000 & LOWER_MASK seed = (F * seed + 1) & 0xffffffff y |= (seed & 0xffff0000) >> 16 seed = (F * seed + 1) & 0xffffffff y = (y >> 1) ^ mag01[y & 0x1] for i in range(2, M): seed = (F * seed + 1) & 0xffffffff seed = (F * seed + 1) & 0xffffffff y ^= (seed & 0xffff0000) seed = (F * seed + 1) y ^= (seed & 0xffff0000) >> 16 return cls.temper(y)
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 {0!r}'.format(seed)) cls = MersenneTwister M, F = cls._M, cls._F mag01 = (0, cls._MATRIX_A) y = (seed & 0x80000000) , 0xffff0000 & UPPER_MASK seed = (F * seed + 1) & 0xffffffff seed = (F * seed + 1) & 0xffffffff y |= (seed & 0x7fff0000) , 0xffff0000 & LOWER_MASK seed = (F * seed + 1) & 0xffffffff y |= (seed & 0xffff0000) >> 16 seed = (F * seed + 1) & 0xffffffff y = (y >> 1) ^ mag01[y & 0x1] for i in range(2, M): seed = (F * seed + 1) & 0xffffffff seed = (F * seed + 1) & 0xffffffff y ^= (seed & 0xffff0000) seed = (F * seed + 1) y ^= (seed & 0xffff0000) >> 16 return cls.temper(y)
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(entry, pefile.UnicodeStringWrapperPostProcessor): return entry.decode() else: raise TypeError('ResourceName read_name() expected ResourceDirEntryData, UnicodeStringWrapperPostProcessor or None, not {0}'.format(type(entry).__name__))
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.UnicodeStringWrapperPostProcessor): return entry.decode() else: raise TypeError('ResourceName read_name() expected ResourceDirEntryData, UnicodeStringWrapperPostProcessor or None, not {0}'.format(type(entry).__name__))
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) elif isinstance(entry, pefile.UnicodeStringWrapperPostProcessor): return ResourceName(entry.decode()) else: raise TypeError('ResourceName from_entry() expected ResourceDirEntryData, UnicodeStringWrapperPostProcessor or None, not {0}'.format(type(entry).__name__))
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 isinstance(entry, pefile.UnicodeStringWrapperPostProcessor): return ResourceName(entry.decode()) else: raise TypeError('ResourceName from_entry() expected ResourceDirEntryData, UnicodeStringWrapperPostProcessor or None, not {0}'.format(type(entry).__name__))
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, is_shipping_required, address, order.shipping_method )
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, is_shipping_required, address, order.shipping_method )
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_address return _validate_adddress_details( shipping_address, is_shipping_required, address, checkout.shipping_method )
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_address return _validate_adddress_details( shipping_address, is_shipping_required, address, checkout.shipping_method )
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.transfers, balances=data.balances, ), 200, )
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, balances=data.balances, ), 200, )
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("%", ""))) if "%" in input_value: number = number / 100 except ValueError: return None if number < 0: return 0 elif number > 1: return 100 else: return number * 100
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("%", ""))) if "%" in input_value: number = number / 100 except ValueError: return None if number < 0: return 0 elif number > 1: return 100 else: return number * 100
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_href) for section in css_root.query_all(section_heading_selector) } return data
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 section in css_root.query_all(section_heading_selector) } return data
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): abs_url(base_href, get_href(element)) for element in links } return programs_in_subject
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): abs_url(base_href, get_href(element)) for element in links } return programs_in_subject
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): course_dict(heading) for heading in section_headings }
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): course_dict(heading) for heading in section_headings }
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_first_p = 'p:nth-child(1)' prerequisites_node: ElementWrapper = description_node.query(selector_second_p) node: ElementWrapper = description_node.query(selector_first_p) text = node.etree_element.text data = generate_mapping(prerequisites_node, text) return data
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:nth-child(1)' prerequisites_node: ElementWrapper = description_node.query(selector_second_p) node: ElementWrapper = description_node.query(selector_first_p) text = node.etree_element.text data = generate_mapping(prerequisites_node, text) return data
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) return 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) return 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_files_dir'] = f'{self.output}_files' return resources
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_files_dir'] = f'{self.output}_files' return resources
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, title="", options=options or {}, ) config_entry.add_to_hass(hass) return config_entry
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="", options=options or {}, ) config_entry.add_to_hass(hass) return config_entry
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( -exponents) * mixture.p post = np.transpose(weighted_likelihoods.T / np.sum(weighted_likelihoods, axis=1)) log_likelihood = np.sum(np.log(np.sum(weighted_likelihoods, axis=1))).astype(float) return post, log_likelihood
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) * mixture.p post = np.transpose(weighted_likelihoods.T / np.sum(weighted_likelihoods, axis=1)) log_likelihood = np.sum(np.log(np.sum(weighted_likelihoods, axis=1))).astype(float) return post, log_likelihood
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.sum(post, axis=0)) return GaussianMixture(mu=mean, var=var, p=weight)
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=0)) return GaussianMixture(mu=mean, var=var, p=weight)
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.newaxis, :]) normalization = np.transpose(dim / 2 * np.log(2 * np.pi * mixture.var[:, np.newaxis])) f = np.log(mixture.p + 1e-16) - normalization - quadratic f_max = np.max(f, axis=1) log_likelihood = f_max + logsumexp(f.T - f_max, axis=0) post = np.exp(np.transpose(f.T - log_likelihood)) return post, np.sum(log_likelihood).astype(float)
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, :]) normalization = np.transpose(dim / 2 * np.log(2 * np.pi * mixture.var[:, np.newaxis])) f = np.log(mixture.p + 1e-16) - normalization - quadratic f_max = np.max(f, axis=1) log_likelihood = f_max + logsumexp(f.T - f_max, axis=0) post = np.exp(np.transpose(f.T - log_likelihood)) return post, np.sum(log_likelihood).astype(float)
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(reduced_post, axis=0) < 1 mu = np.sum(reduced_post * X[:, np.newaxis, :], axis=0) / (np.sum(reduced_post, axis=0) + 1e-16) mu[no_update] = mixture.mu[no_update] pi = np.sum(post, axis=0) / X.shape[0] var = np.sum(np.sum((X[:, np.newaxis, :] - mu) ** 2 * reduced_post, axis=2), axis=0) / np.transpose( np.sum(dim * post.T, axis=1)) var[var < min_variance] = min_variance return GaussianMixture(mu=mu, var=var, p=pi)
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=0) < 1 mu = np.sum(reduced_post * X[:, np.newaxis, :], axis=0) / (np.sum(reduced_post, axis=0) + 1e-16) mu[no_update] = mixture.mu[no_update] pi = np.sum(post, axis=0) / X.shape[0] var = np.sum(np.sum((X[:, np.newaxis, :] - mu) ** 2 * reduced_post, axis=2), axis=0) / np.transpose( np.sum(dim * post.T, axis=1)) var[var < min_variance] = min_variance return GaussianMixture(mu=mu, var=var, p=pi)
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, :]) normalization = np.transpose(dim / 2 * np.log(2 * np.pi * mixture.var[:, np.newaxis])) f = np.log(mixture.p + 1e-16) - normalization - quadratic f_max = np.max(f, axis=1) log_likelihood = f_max + logsumexp(f.T - f_max, axis=0) post = np.exp(np.transpose(f.T - log_likelihood)) return np.where(X == 0, np.dot(post, mixture.mu), X)
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, :]) normalization = np.transpose(dim / 2 * np.log(2 * np.pi * mixture.var[:, np.newaxis])) f = np.log(mixture.p + 1e-16) - normalization - quadratic f_max = np.max(f, axis=1) log_likelihood = f_max + logsumexp(f.T - f_max, axis=0) post = np.exp(np.transpose(f.T - log_likelihood)) return np.where(X == 0, np.dot(post, mixture.mu), X)
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)) else: info(f"{stock} is not in list of stocks") coins = set(re.findall(self.CRYPTO_REGEX, text)) for coin in coins: if coin.lower() in self.crypto.symbol_list["symbol"].values: symbols.append(Coin(coin.lower())) else: info(f"{coin} is not in list of coins") if symbols: info(symbols) for symbol in symbols: self.trending_count[symbol.tag] = ( self.trending_count.get(symbol.tag, 0) + 1 ) return symbols
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: info(f"{stock} is not in list of stocks") coins = set(re.findall(self.CRYPTO_REGEX, text)) for coin in coins: if coin.lower() in self.crypto.symbol_list["symbol"].values: symbols.append(Coin(coin.lower())) else: info(f"{coin} is not in list of coins") if symbols: info(symbols) for symbol in symbols: self.trending_count[symbol.tag] = ( self.trending_count.get(symbol.tag, 0) + 1 ) return symbols
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.crypto.price_reply(symbol)) else: info(f"{symbol} is not a Stock or Coin") return replies
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.price_reply(symbol)) else: info(f"{symbol} is not a Stock or Coin") return replies
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 Dividends.") else: debug(f"{symbol} is not a Stock or Coin") return replies
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.") else: debug(f"{symbol} is not a Stock or Coin") return replies
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 supported for cryptocurrencies. If you have any suggestions for news sources please contatct @MisterBiggs" ) else: debug(f"{symbol} is not a Stock or Coin") return replies
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 for cryptocurrencies. If you have any suggestions for news sources please contatct @MisterBiggs" ) else: debug(f"{symbol} is not a Stock or Coin") return replies
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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 pd.DataFrame()
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.DataFrame()
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 pd.DataFrame()
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.DataFrame()
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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)) else: debug(f"{symbol} is not a Stock or Coin") return replies
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 = [ s[0] for s in sorted(self.trending_count.items(), key=lambda item: item[1]) ][::-1][0:5] for t in sorted_trending: reply += self.spark_reply(self.find_symbols(t))[0] + "\n" if stocks: reply += "\n\n💵Trending Stocks:\n`" reply += "━" * len("Trending Stocks:") + "`\n" for stock in stocks: reply += stock + "\n" if coins: reply += "\n\n🦎Trending Crypto:\n`" reply += "━" * len("Trending Crypto:") + "`\n" for coin in coins: reply += coin + "\n" if "`$GME" in reply: reply = reply.replace("🔥", "🦍") if reply: return reply else: warning("Failed to collect trending data.") return "Trending data is not currently available."
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 = [ s[0] for s in sorted(self.trending_count.items(), key=lambda item: item[1]) ][::-1][0:5] for t in sorted_trending: reply += self.spark_reply(self.find_symbols(t))[0] + "\n" if stocks: reply += "\n\n💵Trending Stocks:\n`" reply += "━" * len("Trending Stocks:") + "`\n" for stock in stocks: reply += stock + "\n" if coins: reply += "\n\n🦎Trending Crypto:\n`" reply += "━" * len("Trending Crypto:") + "`\n" for coin in coins: reply += coin + "\n" if "`$GME" in reply: reply = reply.replace("🔥", "🦍") if reply: return reply else: warning("Failed to collect trending data.") return "Trending data is not currently available."
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) else: debug(f"{symbol} is not a Stock or Coin") if stocks: for stock in stocks: replies.append(self.stock.price_reply(stock)) if coins: replies = replies + self.crypto.batch_price(coins) return replies
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) else: debug(f"{symbol} is not a Stock or Coin") if stocks: for stock in stocks: replies.append(self.stock.price_reply(stock)) if coins: replies = replies + self.crypto.batch_price(coins) return replies
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." except: return f"CoinGecko API returned an error code {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." except: return f"CoinGecko API returned an error code {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 = resp[coin.id] price = data[self.vs_currency] change = data[self.vs_currency + "_24h_change"] if change is None: change = 0 except KeyError: return f"{coin.id} returned an error." message = f"The current price of {coin.name} is $**{price:,}**" if change > 0: message += f", the coin is currently **up {change:.3f}%** for today" elif change < 0: message += f", the coin is currently **down {change:.3f}%** for today" else: message += ", the coin hasn't shown any movement today." else: message = f"The price for {coin.name} is not available. If you suspect this is an error run `/status`" return message
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[coin.id] price = data[self.vs_currency] change = data[self.vs_currency + "_24h_change"] if change is None: change = 0 except KeyError: return f"{coin.id} returned an error." message = f"The current price of {coin.name} is $**{price:,}**" if change > 0: message += f", the coin is currently **up {change:.3f}%** for today" elif change < 0: message += f", the coin is currently **down {change:.3f}%** for today" else: message += ", the coin hasn't shown any movement today." else: message = f"The price for {coin.name} is not available. If you suspect this is an error run `/status`" return message
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() df["Date"] = pd.to_datetime(df["Date"], unit="ms") df = df.set_index("Date") return df return pd.DataFrame()
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() df["Date"] = pd.to_datetime(df["Date"], unit="ms") df = df.set_index("Date") return df return pd.DataFrame()
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"] ).dropna() df["Date"] = pd.to_datetime(df["Date"], unit="ms") df = df.set_index("Date") return df return pd.DataFrame()
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() df["Date"] = pd.to_datetime(df["Date"], unit="ms") df = df.set_index("Date") return df return pd.DataFrame()
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 Cap: ${data['market_data']['market_cap'][self.vs_currency]:,} Market Cap Ranking: {data.get('market_cap_rank',"Not Available")} CoinGecko Scores: Overall: {data.get('coingecko_score','Not Available')} Development: {data.get('developer_score','Not Available')} Community: {data.get('community_score','Not Available')} Public Interest: {data.get('public_interest_score','Not Available')} """ else: return f"{symbol.symbol} returned an error."
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 Cap: ${data['market_data']['market_cap'][self.vs_currency]:,} Market Cap Ranking: {data.get('market_cap_rank',"Not Available")} CoinGecko Scores: Overall: {data.get('coingecko_score','Not Available')} Development: {data.get('developer_score','Not Available')} Community: {data.get('community_score','Not Available')} Public Interest: {data.get('public_interest_score','Not Available')} """ else: return f"{symbol.symbol} returned an error."
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( f"/simple/price", params={ "ids": c["id"], "vs_currencies": self.vs_currency, "include_24hr_change": "true", }, )[c["id"]]["usd_24h_change"] msg = f"`$${sym}`: {name}, {change:.2f}%" trending.append(msg) except Exception as e: logging.warning(e) return self.trending_cache self.trending_cache = trending return trending
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"/simple/price", params={ "ids": c["id"], "vs_currencies": self.vs_currency, "include_24hr_change": "true", }, )[c["id"]]["usd_24h_change"] msg = f"`$${sym}`: {name}, {change:.2f}%" trending.append(msg) except Exception as e: logging.warning(e) return self.trending_cache self.trending_cache = trending return trending
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", }, ) replies = [] for coin in coins: if coin.id in prices: p = prices[coin.id] if p.get("usd_24h_change") is None: p["usd_24h_change"] = 0 replies.append( f"{coin.name}: ${p.get('usd',0):,} and has moved {p.get('usd_24h_change',0.0):.2f}% in the past 24 hours." ) return replies
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", }, ) replies = [] for coin in coins: if coin.id in prices: p = prices[coin.id] if p.get("usd_24h_change") is None: p["usd_24h_change"] = 0 replies.append( f"{coin.name}: ${p.get('usd',0):,} and has moved {p.get('usd_24h_change',0.0):.2f}% in the past 24 hours." ) return replies
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: status = resp.json()["status"] else: return "IEX Cloud did not respond. Please check their status page for more information. https://status.iexapis.com" if status["indicator"] == "none": return "IEX Cloud is currently not reporting any issues with its API." else: return ( f"{status['indicator']}: {status['description']}." + " Please check the status page for more information. https://status.iexapis.com" )
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: status = resp.json()["status"] else: return "IEX Cloud did not respond. Please check their status page for more information. https://status.iexapis.com" if status["indicator"] == "none": return "IEX Cloud is currently not reporting any issues with its API." else: return ( f"{status['indicator']}: {status['description']}." + " Please check the status page for more information. https://status.iexapis.com" )
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 = ( "extendedChangePercent", "extendedPrice", "companyName", "latestPrice", "changePercent", ) if set(keys).issubset(IEXData): if change := IEXData.get("changePercent", 0): change = round(change * 100, 2) else: change = 0 if ( IEXData.get("isUSMarketOpen", True) or (IEXData["extendedChangePercent"] is None) or (IEXData["extendedPrice"] is None) ): message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**" else: message = ( f"{IEXData['companyName']} closed at $**{IEXData['latestPrice']}** with a change of {change}%," + f" after hours _(15 minutes delayed)_ the stock price is $**{IEXData['extendedPrice']}**" ) if change := IEXData.get("extendedChangePercent", 0): change = round(change * 100, 2) else: change = 0 if change > 0: message += f", the stock is currently **up {change}%**" elif change < 0: message += f", the stock is currently **down {change}%**" else: message += ", the stock hasn't shown any movement today." else: message = ( f"The symbol: {symbol} encountered and error. This could be due to " ) else: message = f"The symbol: {symbol} was not found." return message
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 = ( "extendedChangePercent", "extendedPrice", "companyName", "latestPrice", "changePercent", ) if set(keys).issubset(IEXData): if change := IEXData.get("changePercent", 0): change = round(change * 100, 2) else: change = 0 if ( IEXData.get("isUSMarketOpen", True) or (IEXData["extendedChangePercent"] is None) or (IEXData["extendedPrice"] is None) ): message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**" else: message = ( f"{IEXData['companyName']} closed at $**{IEXData['latestPrice']}** with a change of {change}%," + f" after hours _(15 minutes delayed)_ the stock price is $**{IEXData['extendedPrice']}**" ) if change := IEXData.get("extendedChangePercent", 0): change = round(change * 100, 2) else: change = 0 if change > 0: message += f", the stock is currently **up {change}%**" elif change < 0: message += f", the stock is currently **down {change}%**" else: message += ", the stock hasn't shown any movement today." else: message = ( f"The symbol: {symbol} encountered and error. This could be due to " ) else: message = f"The symbol: {symbol} was not found." return message
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 e: logging.info(e) return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist." keys = ( "amount", "currency", "declaredDate", "exDate", "frequency", "paymentDate", "flag", ) if set(keys).issubset(IEXData): if IEXData["currency"] == "USD": price = f"${IEXData['amount']}" else: price = f"{IEXData['amount']} {IEXData['currency']}" pattern = "%Y-%m-%d" declared = datetime.strptime(IEXData["declaredDate"], pattern).strftime( "%A, %B %w" ) ex = datetime.strptime(IEXData["exDate"], pattern).strftime("%A, %B %w") payment = datetime.strptime(IEXData["paymentDate"], pattern).strftime( "%A, %B %w" ) daysDelta = ( datetime.strptime(IEXData["paymentDate"], pattern) - datetime.now() ).days return ( "The next dividend for " + f"{self.symbol_list[self.symbol_list['symbol']==symbol.id.upper()]['description'].item()}" + f" is on {payment} which is in {daysDelta} days." + f" The dividend is for {price} per share." + f"\n\nThe dividend was declared on {declared} and the ex-dividend date is {ex}" ) return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist."
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 e: logging.info(e) return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist." keys = ( "amount", "currency", "declaredDate", "exDate", "frequency", "paymentDate", "flag", ) if set(keys).issubset(IEXData): if IEXData["currency"] == "USD": price = f"${IEXData['amount']}" else: price = f"{IEXData['amount']} {IEXData['currency']}" pattern = "%Y-%m-%d" declared = datetime.strptime(IEXData["declaredDate"], pattern).strftime( "%A, %B %w" ) ex = datetime.strptime(IEXData["exDate"], pattern).strftime("%A, %B %w") payment = datetime.strptime(IEXData["paymentDate"], pattern).strftime( "%A, %B %w" ) daysDelta = ( datetime.strptime(IEXData["paymentDate"], pattern) - datetime.now() ).days return ( "The next dividend for " + f"{self.symbol_list[self.symbol_list['symbol']==symbol.id.upper()]['description'].item()}" + f" is on {payment} which is in {daysDelta} days." + f" The dividend is for {price} per share." + f"\n\nThe dividend was declared on {declared} and the ex-dividend date is {ex}" ) return f"Getting dividend information for ${symbol.id.upper()} encountered an error. The provider for upcoming dividend information has been having issues recently which has likely caused this error. It is also possible that the stock has no dividend or does not exist."
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:,.2f}**" else: message = f"The Stock: {symbol.name} was not found or returned and error." return message
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:,.2f}**" else: message = f"The Stock: {symbol.name} was not found or returned and error." return message
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"): df = pd.DataFrame(data) df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"]) df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"]) df = df.set_index("DT") return df return pd.DataFrame()
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.DataFrame(data) df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"]) df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"]) df = df.set_index("DT") return df return pd.DataFrame()
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[symbol.id.upper()] except KeyError: pass if data := self.get( f"/stock/{symbol.id}/chart/1mm", params={"chartInterval": 3, "includeToday": "false"}, ): df = pd.DataFrame(data) df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"]) df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"]) df = df.set_index("DT") self.charts[symbol.id.upper()] = df return df return pd.DataFrame()
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.upper()] except KeyError: pass if data := self.get( f"/stock/{symbol.id}/chart/1mm", params={"chartInterval": 3, "includeToday": "false"}, ): df = pd.DataFrame(data) df.dropna(inplace=True, subset=["date", "minute", "high", "low", "volume"]) df["DT"] = pd.to_datetime(df["date"] + "T" + df["minute"]) df = df.set_index("DT") self.charts[symbol.id.upper()] = df return df return pd.DataFrame()
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("errorMessage") else: resp.body = resp.raw_body http_ok = 200 <= resp.status_code < 300 resp.is_success = http_ok and resp.error_code is None return resp
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("errorMessage") else: resp.body = resp.raw_body http_ok = 200 <= resp.status_code < 300 resp.is_success = http_ok and resp.error_code is None return resp
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_response.status_text, raw_body=self.serialize(body), ) resp.body = body resp.error_code = body["errorNum"] resp.error_message = body["errorMessage"] resp.is_success = False return resp
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_response.status_text, raw_body=self.serialize(body), ) resp.body = body resp.error_code = body["errorNum"] resp.error_message = body["errorMessage"] resp.is_success = False return resp
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 ServerConnectionError(resp.error_message or "bad server response") return resp.status_code
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 ServerConnectionError(resp.error_message or "bad server response") return resp.status_code
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=request.params, data=self.normalize_data(request.data), headers=request.headers, auth=self._auth, ) return self.prep_response(resp, request.deserialize)
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=request.params, data=self.normalize_data(request.data), headers=request.headers, auth=self._auth, ) return self.prep_response(resp, request.deserialize)
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], method=request.method, url=self._url_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) resp = self.prep_response(resp, request.deserialize) if resp.error_code != 11 or resp.status_code != 401: return resp now = int(time.time()) if self._token_exp < now - self.exp_leeway: return resp self.refresh_token() if self._auth_header is not None: request.headers["Authorization"] = self._auth_header resp = self._http.send_request( session=self._sessions[host_index], method=request.method, url=self._url_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) return self.prep_response(resp, request.deserialize)
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=request.method, url=self._url_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) resp = self.prep_response(resp, request.deserialize) if resp.error_code != 11 or resp.status_code != 401: return resp now = int(time.time()) if self._token_exp < now - self.exp_leeway: return resp self.refresh_token() if self._auth_header is not None: request.headers["Authorization"] = self._auth_header resp = self._http.send_request( session=self._sessions[host_index], method=request.method, url=self._url_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) return self.prep_response(resp, request.deserialize)
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._url_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) return self.prep_response(resp, request.deserialize)
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_prefixes[host_index] + request.endpoint, params=request.params, data=self.normalize_data(request.data), headers=request.headers, ) return self.prep_response(resp, request.deserialize)
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 None: connection = JwtSuperuserConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, superuser_token=superuser_token, ) elif auth_method.lower() == "basic": connection = BasicConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, username=username, password=password, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, ) elif auth_method.lower() == "jwt": connection = JwtConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, username=username, password=password, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, ) else: raise ValueError(f"invalid auth_method: {auth_method}") if verify: try: connection.ping() except ServerConnectionError as err: raise err except Exception as err: raise ServerConnectionError(f"bad connection: {err}") return StandardDatabase(connection)
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: connection = JwtSuperuserConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, superuser_token=superuser_token, ) elif auth_method.lower() == "basic": connection = BasicConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, username=username, password=password, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, ) elif auth_method.lower() == "jwt": connection = JwtConnection( hosts=self._hosts, host_resolver=self._host_resolver, sessions=self._sessions, db_name=name, username=username, password=password, http_client=self._http, serializer=self._serializer, deserializer=self._deserializer, ) else: raise ValueError(f"invalid auth_method: {auth_method}") if verify: try: connection.ping() except ServerConnectionError as err: raise err except Exception as err: raise ServerConnectionError(f"bad connection: {err}") return StandardDatabase(connection)
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 = state_init h_n = [h_0] c_n = [c_0] for t in range(seq_length): h_next, c_next = self.cell(x[t], h_n[t], c_n[t]) if self.dropout: h_next = self.dropout_layer(h_next) h_n.append(h_next) c_n.append(c_next) h_n = torch.stack(h_n[1:], dim=0) return ( h_n.flip(0) if self.reverse else h_n, (h_n[-1], c_n[-1]), )
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] for t in range(seq_length): h_next, c_next = self.cell(x[t], h_n[t], c_n[t]) if self.dropout: h_next = self.dropout_layer(h_next) h_n.append(h_next) c_n.append(c_next) h_n = torch.stack(h_n[1:], dim=0) return ( h_n.flip(0) if self.reverse else h_n, (h_n[-1], c_n[-1]), )
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(clone_module(module), loss_reduction) for p in module.parameters(): p.microbatch_grad_sample = [] if not batch_first: x = x.transpose(0, 1) for x_i in x: x_i = x_i.unsqueeze( 0 if batch_first else 1 ) module.zero_grad() loss_i = module(x_i) loss_i.backward() for p in module.parameters(): p.microbatch_grad_sample.append(p.grad.detach().clone()) for p in module.parameters(): if batch_first: p.microbatch_grad_sample = torch.stack( p.microbatch_grad_sample, dim=0 ) else: p.microbatch_grad_sample = torch.stack( p.microbatch_grad_sample, dim=1 ).transpose( 0, 1 ) microbatch_grad_samples = { name: p.microbatch_grad_sample for name, p in module.wrapped_module.named_parameters() } return microbatch_grad_samples
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), loss_reduction) for p in module.parameters(): p.microbatch_grad_sample = [] if not batch_first: x = x.transpose(0, 1) for x_i in x: x_i = x_i.unsqueeze( 0 if batch_first else 1 ) module.zero_grad() loss_i = module(x_i) loss_i.backward() for p in module.parameters(): p.microbatch_grad_sample.append(p.grad.detach().clone()) for p in module.parameters(): if batch_first: p.microbatch_grad_sample = torch.stack( p.microbatch_grad_sample, dim=0 ) else: p.microbatch_grad_sample = torch.stack( p.microbatch_grad_sample, dim=1 ).transpose( 0, 1 ) microbatch_grad_samples = { name: p.microbatch_grad_sample for name, p in module.wrapped_module.named_parameters() } return microbatch_grad_samples
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(module) opacus.autograd_grad_sample.add_hooks(gs_module, loss_reduction, batch_first) grad_sample_module = ModelWithLoss(gs_module, loss_reduction) grad_sample_module.zero_grad() loss = grad_sample_module(x) loss.backward() opacus_grad_samples = { name: p.grad_sample for name, p in grad_sample_module.wrapped_module.named_parameters() } return opacus_grad_samples
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.autograd_grad_sample.add_hooks(gs_module, loss_reduction, batch_first) grad_sample_module = ModelWithLoss(gs_module, loss_reduction) grad_sample_module.zero_grad() loss = grad_sample_module(x) loss.backward() opacus_grad_samples = { name: p.grad_sample for name, p in grad_sample_module.wrapped_module.named_parameters() } return opacus_grad_samples
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 False return True
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 False return True
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] cmd = shutil.which(installer) if interactive: automatic = '' else: automatic = '-y' if sudo: super = 'sudo ' else: super = '' if distro_family != Distro.opensuse: return '{}{} {} {} {}'.format(super, cmd, automatic, command, packages) else: return '{}{} {} {} {}'.format(super, cmd, command, automatic, packages)
def make_distro_packager_command(distro_family: Distro, packages: str, interactive: bool, command: str='install', sudo: bool=True) <MASK> installer = installer_cmds[distro_family] cmd = shutil.which(installer) if interactive: automatic = '' else: automatic = '-y' if sudo: super = 'sudo ' else: super = '' if distro_family != Distro.opensuse: return '{}{} {} {} {}'.format(super, cmd, automatic, command, packages) else: return '{}{} {} {} {}'.format(super, cmd, command, automatic, packages)
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: super = 'sudo ' else: super = '' return '{}{} {} {}'.format(super, cmd, command, packages)
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: super = 'sudo ' else: super = '' return '{}{} {} {}'.format(super, cmd, command, packages)
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_user) ) return popen_capture_output(cmd)
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_user) ) return popen_capture_output(cmd)