_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q255600
TDependentProperty.load_all_methods
validation
def load_all_methods(self): r'''Method to load all data, and set all_methods based on the available data and properties. Demo function for testing only; must be implemented according to the methods available for each individual method. ''' methods = [] Tmins, Tmaxs = [], [] if self.CASRN in ['7732-18-5', '67-56-1', '64-17-5']: methods.append(TEST_METHOD_1) self.TEST_METHOD_1_Tmin = 200. self.TEST_METHOD_1_Tmax = 350 self.TEST_METHOD_1_coeffs = [1, .002] Tmins.append(self.TEST_METHOD_1_Tmin); Tmaxs.append(self.TEST_METHOD_1_Tmax) if self.CASRN in ['67-56-1']:
python
{ "resource": "" }
q255601
TDependentProperty.calculate
validation
def calculate(self, T, method): r'''Method to calculate a property with a specified method, with no validity checking or error handling. Demo function for testing only; must be implemented according to the methods available for each individual method. Include the interpolation call here. Parameters ---------- T : float Temperature at which to calculate the property, [K] method : str Method name to use Returns -------
python
{ "resource": "" }
q255602
TPDependentProperty.set_user_methods_P
validation
def set_user_methods_P(self, user_methods_P, forced_P=False): r'''Method to set the pressure-dependent property methods desired for consideration by the user. Can be used to exclude certain methods which might have unacceptable accuracy. As a side effect, the previously selected method is removed when this method is called to ensure user methods are tried in the desired order. Parameters ---------- user_methods_P : str or list Methods by name to be considered or preferred for pressure effect. forced : bool, optional If True, only the user specified methods will ever be considered; if False other methods will be considered if no user methods suceed. ''' # Accept either a string or a list of methods, and whether # or not to only consider the false methods if isinstance(user_methods_P, str): user_methods_P = [user_methods_P] # The user's order matters and is retained for use by select_valid_methods self.user_methods_P = user_methods_P
python
{ "resource": "" }
q255603
TPDependentProperty.select_valid_methods_P
validation
def select_valid_methods_P(self, T, P): r'''Method to obtain a sorted list methods which are valid at `T` according to `test_method_validity`. Considers either only user methods if forced is True, or all methods. User methods are first tested according to their listed order, and unless forced is True, then all methods are tested and sorted by their order in `ranked_methods`. Parameters ---------- T : float Temperature at which to test methods, [K] P : float Pressure at which to test methods, [Pa] Returns ------- sorted_valid_methods_P : list Sorted lists of methods valid at T and P according to `test_method_validity` ''' # Same as select_valid_methods but with _P added to variables if self.forced_P: considered_methods = list(self.user_methods_P) else: considered_methods = list(self.all_methods_P) if self.user_methods_P: [considered_methods.remove(i) for i in self.user_methods_P]
python
{ "resource": "" }
q255604
TPDependentProperty.TP_dependent_property
validation
def TP_dependent_property(self, T, P): r'''Method to calculate the property with sanity checking and without specifying a specific method. `select_valid_methods_P` is used to obtain a sorted list of methods to try. Methods are then tried in order until one succeeds. The methods are allowed to fail, and their results are checked with `test_property_validity`. On success, the used method is stored in the variable `method_P`. If `method_P` is set, this method is first checked for validity with `test_method_validity_P` for the specified temperature, and if it is valid, it is then used to calculate the property. The result is checked for validity, and returned if it is valid. If either of the checks fail, the function retrieves a full list of valid methods with `select_valid_methods_P` and attempts them as described above. If no methods are found which succeed, returns None.
python
{ "resource": "" }
q255605
TPDependentProperty.interpolate_P
validation
def interpolate_P(self, T, P, name): r'''Method to perform interpolation on a given tabular data set previously added via `set_tabular_data_P`. This method will create the interpolators the first time it is used on a property set, and store them for quick future use. Interpolation is cubic-spline based if 5 or more points are available, and linearly interpolated if not. Extrapolation is always performed linearly. This function uses the transforms `interpolation_T`, `interpolation_P`, `interpolation_property`, and `interpolation_property_inv` if set. If any of these are changed after the interpolators were first created, new interpolators are created with the new transforms. All interpolation is performed via the `interp2d` function. Parameters ---------- T : float Temperature at which to interpolate the property, [K] T : float Pressure at which to interpolate the property, [Pa] name : str The name assigned to the tabular data set Returns ------- prop : float Calculated property, [`units`] ''' key = (name, self.interpolation_T, self.interpolation_P, self.interpolation_property, self.interpolation_property_inv) # If the interpolator and extrapolator has already been created, load it if key in self.tabular_data_interpolators: extrapolator, spline = self.tabular_data_interpolators[key] else: Ts, Ps, properties = self.tabular_data[name] if self.interpolation_T: # Transform ths Ts with interpolation_T if set Ts2 = [self.interpolation_T(T2) for T2 in Ts] else: Ts2 = Ts if self.interpolation_P: # Transform ths Ts with interpolation_T if set Ps2 = [self.interpolation_P(P2) for P2 in Ps] else: Ps2 = Ps if self.interpolation_property: # Transform ths props with interpolation_property if set properties2 = [self.interpolation_property(p) for p in properties] else:
python
{ "resource": "" }
q255606
TPDependentProperty.TP_dependent_property_derivative_T
validation
def TP_dependent_property_derivative_T(self, T, P, order=1): r'''Method to calculate a derivative of a temperature and pressure dependent property with respect to temperature at constant pressure, of a given order. Methods found valid by `select_valid_methods_P` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_T` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d T}|_{P} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] order : int Order of the derivative, >= 1 Returns
python
{ "resource": "" }
q255607
TPDependentProperty.TP_dependent_property_derivative_P
validation
def TP_dependent_property_derivative_P(self, T, P, order=1): r'''Method to calculate a derivative of a temperature and pressure dependent property with respect to pressure at constant temperature, of a given order. Methods found valid by `select_valid_methods_P` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_P` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d P}|_{T} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] order : int Order of the derivative, >= 1 Returns
python
{ "resource": "" }
q255608
MixtureProperty.set_user_method
validation
def set_user_method(self, user_methods, forced=False): r'''Method to set the T, P, and composition dependent property methods desired for consideration by the user. Can be used to exclude certain methods which might have unacceptable accuracy. As a side effect, the previously selected method is removed when this method is called to ensure user methods are tried in the desired order. Parameters ---------- user_methods : str or list Methods by name to be considered for calculation of the mixture property, ordered by preference. forced : bool, optional If True, only the user specified methods will ever be considered; if False, other methods will be considered if no user methods suceed. ''' # Accept either a string or a list of methods, and whether # or not to only consider the false methods if isinstance(user_methods, str): user_methods = [user_methods] # The user's order matters and is retained for use by select_valid_methods self.user_methods = user_methods
python
{ "resource": "" }
q255609
MixtureProperty.property_derivative_T
validation
def property_derivative_T(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to temperature at constant pressure and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_T` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d T}|_{P, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-]
python
{ "resource": "" }
q255610
MixtureProperty.property_derivative_P
validation
def property_derivative_P(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_P` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d P}|_{T, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-]
python
{ "resource": "" }
q255611
refractive_index
validation
def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None, full_info=True): r'''This function handles the retrieval of a chemical's refractive index. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Function has data for approximately 4500 chemicals. Parameters ---------- CASRN : string CASRN [-] Returns ------- RI : float Refractive Index on the Na D line, [-] T : float, only returned if full_info == True Temperature at which refractive index reading was made methods : list, only returned if AvailableMethods == True List of methods which can be used to obtain RI with the given inputs Other Parameters ---------------- Method : string, optional A string for the method name to use, as defined by constants in RI_methods AvailableMethods : bool, optional If True, function will determine which methods can be used to obtain RI for the desired chemical, and will return methods instead of RI full_info : bool, optional If True, function will return the temperature at which the refractive index reading was made Notes ----- Only one source is available in this function. It is: * 'CRC', a compillation of Organic RI data in [1]_.
python
{ "resource": "" }
q255612
GCEOSMIX.solve_T
validation
def solve_T(self, P, V, quick=True): r'''Generic method to calculate `T` from a specified `P` and `V`. Provides SciPy's `newton` solver, and iterates to solve the general equation for `P`, recalculating `a_alpha` as a function of temperature using `a_alpha_and_derivatives` each iteration. Parameters ---------- P : float Pressure, [Pa] V : float Molar volume, [m^3/mol] quick : bool, optional
python
{ "resource": "" }
q255613
PRMIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by
python
{ "resource": "" }
q255614
SRKMIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `m`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by
python
{ "resource": "" }
q255615
PRSVMIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' if not hasattr(self, 'kappas'): self.kappas = [kappa0 + kappa1*(1 + (T/Tc)**0.5)*(0.7 - (T/Tc))
python
{ "resource": "" }
q255616
PRSV2MIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' if not hasattr(self, 'kappas'): self.kappas = [] for Tc, kappa0, kappa1, kappa2, kappa3 in zip(self.Tcs, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s): Tr = T/Tc
python
{ "resource": "" }
q255617
TWUPRMIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `omega`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by
python
{ "resource": "" }
q255618
APISRKMIX.setup_a_alpha_and_derivatives
validation
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives`
python
{ "resource": "" }
q255619
Bahadori_liquid
validation
def Bahadori_liquid(T, M): r'''Estimates the thermal conductivity of parafin liquid hydrocarbons. Fits their data well, and is useful as only MW is required. X is the Molecular weight, and Y the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 b = A_2 + B_2 X + C_2 X^2 + D_2 X^3 c = A_3 + B_3 X + C_3 X^2 + D_3 X^3 d = A_4 + B_4 X + C_4 X^2 + D_4 X^3 Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Returns ------- kl : float
python
{ "resource": "" }
q255620
Bahadori_gas
validation
def Bahadori_gas(T, MW): r'''Estimates the thermal conductivity of hydrocarbons gases at low P. Fits their data well, and is useful as only MW is required. Y is the Molecular weight, and X the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 b = A_2 + B_2 X + C_2 X^2 + D_2 X^3 c = A_3 + B_3 X + C_3 X^2 + D_3 X^3 d = A_4 + B_4 X + C_4 X^2 + D_4 X^3 Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- The accuracy of this equation has not been reviewed. Examples -------- >>> Bahadori_gas(40+273.15, 20) # Point from article 0.031968165337873326 References ---------- .. [1] Bahadori, Alireza, and Saeid
python
{ "resource": "" }
q255621
ThermalConductivityLiquid.calculate
validation
def calculate(self, T, method): r'''Method to calculate low-pressure liquid thermal conductivity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the liquid, [K] method : str Name of the method to use Returns ------- kl : float Thermal conductivity of the liquid at T and a low pressure, [W/m/K] ''' if method == SHEFFY_JOHNSON: kl = Sheffy_Johnson(T, self.MW, self.Tm) elif method == SATO_RIEDEL:
python
{ "resource": "" }
q255622
ThermalConductivityLiquid.calculate_P
validation
def calculate_P(self, T, P, method): r'''Method to calculate pressure-dependent liquid thermal conductivity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate liquid thermal conductivity, [K] P : float Pressure at which to calculate liquid thermal conductivity, [K]
python
{ "resource": "" }
q255623
ThermalConductivityLiquidMixture.calculate
validation
def calculate(self, T, P, zs, ws, method): r'''Method to calculate thermal conductivity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- k : float Thermal conductivity of the liquid mixture, [W/m/K] ''' if method == SIMPLE: ks = [i(T, P) for i in self.ThermalConductivityLiquids]
python
{ "resource": "" }
q255624
ThermalConductivityGas.calculate
validation
def calculate(self, T, method): r'''Method to calculate low-pressure gas thermal conductivity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the gas, [K] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of the gas at T and a low pressure, [W/m/K] ''' if method == GHARAGHEIZI_G: kg = Gharagheizi_gas(T, self.MW, self.Tb, self.Pc, self.omega) elif method == DIPPR_9B: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = DIPPR9B(T, self.MW, Cvgm, mug, self.Tc) elif method == CHUNG: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = Chung(T, self.MW, self.Tc, self.omega, Cvgm, mug) elif method == ELI_HANLEY: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm kg = eli_hanley(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm) elif method == EUCKEN_MOD: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else
python
{ "resource": "" }
q255625
ThermalConductivityGas.calculate_P
validation
def calculate_P(self, T, P, method): r'''Method to calculate pressure-dependent gas thermal conductivity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate gas thermal conductivity, [K] P : float Pressure at which to calculate gas thermal conductivity, [K] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of the gas at T and P, [W/m/K] ''' if method == ELI_HANLEY_DENSE: Vmg =
python
{ "resource": "" }
q255626
ThermalConductivityGasMixture.calculate
validation
def calculate(self, T, P, zs, ws, method): r'''Method to calculate thermal conductivity of a gas mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of gas mixture, [W/m/K] '''
python
{ "resource": "" }
q255627
nested_formula_parser
validation
def nested_formula_parser(formula, check=True): r'''Improved formula parser which handles braces and their multipliers, as well as rational element counts. Strips charges from the end of a formula first. Accepts repeated chemical units. Performs no sanity checking that elements are actually elements. As it uses regular expressions for matching, errors are mostly just ignored. Parameters ---------- formula : str Formula string, very simply formats only. check : bool If `check` is True, a simple check will be performed to determine if a formula is not a formula and an exception will be raised if it is not, [-] Returns ------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Notes ----- Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/ Examples -------- >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2')) {'H': 12.0003, 'N': 4.0001, 'Pd': 1} ''' formula = formula.replace('[', '').replace(']', '') charge_splits = bracketed_charge_re.split(formula) if len(charge_splits) > 1: formula = charge_splits[0] else: formula = formula.split('+')[0].split('-')[0] stack = [[]] last = stack[0] tokens = formula_token_matcher_rational.findall(formula) # The set of letters in the tokens should match the set of letters if check: token_letters = set([j for i in tokens for j in i if j in letter_set]) formula_letters = set(i for
python
{ "resource": "" }
q255628
charge_from_formula
validation
def charge_from_formula(formula): r'''Basic formula parser to determine the charge from a formula - given that the charge is already specified as one element of the formula. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula string, very simply formats only, ending in one of '+x', '-x', n*'+', or n*'-' or any of them surrounded by brackets but always at the end of a formula. Returns ------- charge : int Charge of the molecule, [faraday] Notes ----- Examples -------- >>> charge_from_formula('Br3-') -1 >>> charge_from_formula('Br3(-)') -1 ''' negative = '-' in formula positive = '+' in formula if positive and negative: raise
python
{ "resource": "" }
q255629
serialize_formula
validation
def serialize_formula(formula): r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula string as parseable by the method nested_formula_parser, [-] Returns ------- formula : str A consistently formatted formula to describe a molecular formula, [-] Notes ----- Examples -------- >>> serialize_formula('Pd(NH3)4+3') 'H12N4Pd+3' ''' charge =
python
{ "resource": "" }
q255630
Client.connect
validation
async def connect(self): """Establish a connection to the chat server. Returns when an error has occurred, or :func:`disconnect` has been called. """ proxy = os.environ.get('HTTP_PROXY') self._session = http_utils.Session(self._cookies, proxy=proxy) try: self._channel = channel.Channel( self._session, self._max_retries, self._retry_backoff_base ) # Forward the Channel events to the Client events. self._channel.on_connect.add_observer(self.on_connect.fire) self._channel.on_reconnect.add_observer(self.on_reconnect.fire)
python
{ "resource": "" }
q255631
Client.get_request_header
validation
def get_request_header(self): """Return ``request_header`` for use when constructing requests. Returns: Populated request header. """ # resource is allowed to be null if it's not available yet (the Chrome # client does this for the first getentitybyid call)
python
{ "resource": "" }
q255632
Client.set_active
validation
async def set_active(self): """Set this client as active. While a client is active, no other clients will raise notifications. Call this method whenever there is an indication the user is interacting with this client. This method may be called very frequently, and it will only make a request when necessary. """ is_active = (self._active_client_state == hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE) timed_out = (time.time() - self._last_active_secs > SETACTIVECLIENT_LIMIT_SECS) if not is_active or timed_out: # Update these immediately so if the function is called again # before the API request finishes, we don't start extra requests. self._active_client_state = ( hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE ) self._last_active_secs = time.time() # The first time this is called, we need to retrieve the user's # email address. if self._email is None: try: get_self_info_request = hangouts_pb2.GetSelfInfoRequest( request_header=self.get_request_header(), ) get_self_info_response = await self.get_self_info( get_self_info_request ) except exceptions.NetworkError as e: logger.warning('Failed to find email address: {}' .format(e)) return self._email = (
python
{ "resource": "" }
q255633
Client.upload_image
validation
async def upload_image(self, image_file, filename=None, *, return_uploaded_image=False): """Upload an image that can be later attached to a chat message. Args: image_file: A file-like object containing an image. filename (str): (optional) Custom name for the uploaded file. return_uploaded_image (bool): (optional) If True, return :class:`.UploadedImage` instead of image ID. Defaults to False. Raises: hangups.NetworkError: If the upload request failed. Returns: :class:`.UploadedImage` instance, or ID of the uploaded image. """ image_filename = filename or os.path.basename(image_file.name) image_data = image_file.read() # request an upload URL res = await self._base_request( IMAGE_UPLOAD_URL, 'application/x-www-form-urlencoded;charset=UTF-8', 'json', json.dumps({ "protocolVersion": "0.8", "createSessionRequest": { "fields": [{ "external": { "name": "file", "filename": image_filename, "put": {}, "size": len(image_data) } }] } }) ) try:
python
{ "resource": "" }
q255634
Client._get_upload_session_status
validation
def _get_upload_session_status(res): """Parse the image upload response to obtain status. Args: res: http_utils.FetchResponse instance, the upload response Returns: dict, sessionStatus of the response Raises: hangups.NetworkError: If the upload request failed. """ response = json.loads(res.body.decode()) if 'sessionStatus' not in response: try: info = ( response['errorMessage']['additionalInfo']
python
{ "resource": "" }
q255635
Client._on_receive_array
validation
async def _on_receive_array(self, array): """Parse channel array and call the appropriate events.""" if array[0] == 'noop': pass # This is just a keep-alive, ignore it. else: wrapper = json.loads(array[0]['p']) # Wrapper appears to be a Protocol Buffer message, but encoded via # field numbers as dictionary keys. Since we don't have a parser # for that, parse it ad-hoc here. if '3' in wrapper: # This is a new client_id. self._client_id = wrapper['3']['2'] logger.info('Received new client_id: %r', self._client_id) # Once client_id is received, the channel is ready to have # services added. await self._add_channel_services() if '2' in wrapper: pblite_message = json.loads(wrapper['2']['2']) if pblite_message[0] == 'cbu': # This is a (Client)BatchUpdate containing StateUpdate
python
{ "resource": "" }
q255636
Client._add_channel_services
validation
async def _add_channel_services(self): """Add services to the channel. The services we add to the channel determine what kind of data we will receive on it. The "babel" service includes what we need for Hangouts. If this fails for some reason, hangups will never receive any events. The "babel_presence_last_seen" service is also required to receive presence notifications. This needs to be re-called whenever we open a new channel (when there's a new SID and client_id. """ logger.info('Adding channel services...') # Based on what Hangouts for Chrome does over 2
python
{ "resource": "" }
q255637
Client._pb_request
validation
async def _pb_request(self, endpoint, request_pb, response_pb): """Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Protocol Buffer message. Raises: NetworkError: If the request fails. """ logger.debug('Sending Protocol Buffer request %s:\n%s', endpoint, request_pb) res = await self._base_request( 'https://clients6.google.com/chat/v1/{}'.format(endpoint), 'application/x-protobuf', # Request body is Protocol Buffer. 'proto', # Response body is Protocol Buffer. request_pb.SerializeToString() ) try: response_pb.ParseFromString(base64.b64decode(res.body)) except binascii.Error as e: raise exceptions.NetworkError( 'Failed to decode base64 response: {}'.format(e) ) except google.protobuf.message.DecodeError as e:
python
{ "resource": "" }
q255638
Client._base_request
validation
async def _base_request(self, url, content_type, response_type, data): """Send a generic authenticated POST request. Args: url (str): URL of request. content_type (str): Request content type. response_type (str): The desired response format. Valid options are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary Protocol Buffer). 'proto' requires manually setting an extra header 'X-Goog-Encode-Response-If-Executable: base64'. data (str): Request body data. Returns: FetchResponse: Response containing HTTP code, cookies, and body. Raises: NetworkError: If the request fails. """ headers = { 'content-type': content_type, # This header is required for Protocol Buffer responses. It causes # them to be base64 encoded: 'X-Goog-Encode-Response-If-Executable': 'base64',
python
{ "resource": "" }
q255639
Client.add_user
validation
async def add_user(self, add_user_request): """Invite users to join an existing group conversation.""" response = hangouts_pb2.AddUserResponse()
python
{ "resource": "" }
q255640
Client.create_conversation
validation
async def create_conversation(self, create_conversation_request): """Create a new conversation.""" response = hangouts_pb2.CreateConversationResponse() await
python
{ "resource": "" }
q255641
Client.delete_conversation
validation
async def delete_conversation(self, delete_conversation_request): """Leave a one-to-one conversation. One-to-one conversations are "sticky"; they can't actually be deleted. This API clears the event history of the specified conversation up to ``delete_upper_bound_timestamp``, hiding it if no events remain. """
python
{ "resource": "" }
q255642
Client.easter_egg
validation
async def easter_egg(self, easter_egg_request): """Send an easter egg event to a conversation.""" response = hangouts_pb2.EasterEggResponse()
python
{ "resource": "" }
q255643
Client.get_conversation
validation
async def get_conversation(self, get_conversation_request): """Return conversation info and recent events.""" response = hangouts_pb2.GetConversationResponse()
python
{ "resource": "" }
q255644
Client.get_entity_by_id
validation
async def get_entity_by_id(self, get_entity_by_id_request): """Return one or more user entities. Searching by phone number only finds entities when their phone number is in your contacts (and not always even then), and can't be used to find Google Voice contacts. """
python
{ "resource": "" }
q255645
Client.get_group_conversation_url
validation
async def get_group_conversation_url(self, get_group_conversation_url_request): """Get URL to allow others to join a group conversation.""" response = hangouts_pb2.GetGroupConversationUrlResponse()
python
{ "resource": "" }
q255646
Client.get_self_info
validation
async def get_self_info(self, get_self_info_request): """Return info about the current user.""" response = hangouts_pb2.GetSelfInfoResponse()
python
{ "resource": "" }
q255647
Client.get_suggested_entities
validation
async def get_suggested_entities(self, get_suggested_entities_request): """Return suggested contacts.""" response = hangouts_pb2.GetSuggestedEntitiesResponse() await
python
{ "resource": "" }
q255648
Client.query_presence
validation
async def query_presence(self, query_presence_request): """Return presence status for a list of users.""" response = hangouts_pb2.QueryPresenceResponse()
python
{ "resource": "" }
q255649
Client.remove_user
validation
async def remove_user(self, remove_user_request): """Remove a participant from a group conversation.""" response = hangouts_pb2.RemoveUserResponse()
python
{ "resource": "" }
q255650
Client.rename_conversation
validation
async def rename_conversation(self, rename_conversation_request): """Rename a conversation. Both group and one-to-one conversations may be renamed, but the official Hangouts clients have mixed support for one-to-one conversations with custom names. """ response =
python
{ "resource": "" }
q255651
Client.search_entities
validation
async def search_entities(self, search_entities_request): """Return user entities based on a query.""" response = hangouts_pb2.SearchEntitiesResponse()
python
{ "resource": "" }
q255652
Client.send_chat_message
validation
async def send_chat_message(self, send_chat_message_request): """Send a chat message to a conversation.""" response = hangouts_pb2.SendChatMessageResponse()
python
{ "resource": "" }
q255653
Client.modify_otr_status
validation
async def modify_otr_status(self, modify_otr_status_request): """Enable or disable message history in a conversation.""" response = hangouts_pb2.ModifyOTRStatusResponse()
python
{ "resource": "" }
q255654
Client.send_offnetwork_invitation
validation
async def send_offnetwork_invitation( self, send_offnetwork_invitation_request ): """Send an email to invite a non-Google contact to Hangouts."""
python
{ "resource": "" }
q255655
Client.set_active_client
validation
async def set_active_client(self, set_active_client_request): """Set the active client.""" response = hangouts_pb2.SetActiveClientResponse() await
python
{ "resource": "" }
q255656
Client.set_conversation_notification_level
validation
async def set_conversation_notification_level( self, set_conversation_notification_level_request ): """Set the notification level of a conversation."""
python
{ "resource": "" }
q255657
Client.set_focus
validation
async def set_focus(self, set_focus_request): """Set focus to a conversation.""" response = hangouts_pb2.SetFocusResponse() await
python
{ "resource": "" }
q255658
Client.set_group_link_sharing_enabled
validation
async def set_group_link_sharing_enabled( self, set_group_link_sharing_enabled_request ): """Set whether group link sharing is enabled for a conversation."""
python
{ "resource": "" }
q255659
Client.set_presence
validation
async def set_presence(self, set_presence_request): """Set the presence status.""" response = hangouts_pb2.SetPresenceResponse() await
python
{ "resource": "" }
q255660
Client.set_typing
validation
async def set_typing(self, set_typing_request): """Set the typing status of a conversation.""" response = hangouts_pb2.SetTypingResponse()
python
{ "resource": "" }
q255661
Client.sync_all_new_events
validation
async def sync_all_new_events(self, sync_all_new_events_request): """List all events occurring at or after a timestamp.""" response = hangouts_pb2.SyncAllNewEventsResponse()
python
{ "resource": "" }
q255662
Client.sync_recent_conversations
validation
async def sync_recent_conversations( self, sync_recent_conversations_request ): """Return info on recent conversations and their events.""" response = hangouts_pb2.SyncRecentConversationsResponse()
python
{ "resource": "" }
q255663
from_timestamp
validation
def from_timestamp(microsecond_timestamp): """Convert a microsecond timestamp to a UTC datetime instance.""" # Create datetime without losing precision from floating point (yes, this # is actually needed): return
python
{ "resource": "" }
q255664
from_participantid
validation
def from_participantid(participant_id): """Convert hangouts_pb2.ParticipantId to
python
{ "resource": "" }
q255665
to_participantid
validation
def to_participantid(user_id): """Convert UserID to hangouts_pb2.ParticipantId.""" return hangouts_pb2.ParticipantId(
python
{ "resource": "" }
q255666
parse_typing_status_message
validation
def parse_typing_status_message(p): """Return TypingStatusMessage from hangouts_pb2.SetTypingNotification. The same status may be sent multiple times consecutively, and when a
python
{ "resource": "" }
q255667
parse_watermark_notification
validation
def parse_watermark_notification(p): """Return WatermarkNotification from hangouts_pb2.WatermarkNotification.""" return WatermarkNotification(
python
{ "resource": "" }
q255668
_get_authorization_headers
validation
def _get_authorization_headers(sapisid_cookie): """Return authorization headers for API request.""" # It doesn't seem to matter what the url and time are as long as they are # consistent. time_msec = int(time.time() * 1000) auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL) auth_hash
python
{ "resource": "" }
q255669
Session.fetch
validation
async def fetch(self, method, url, params=None, headers=None, data=None): """Make an HTTP request. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Failures will be retried MAX_RETRIES times before raising NetworkError. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: FetchResponse: Response data. Raises: NetworkError: If the request fails. """ logger.debug('Sending request %s %s:\n%r', method, url, data) for retry_num in range(MAX_RETRIES): try: async with self.fetch_raw(method, url, params=params,
python
{ "resource": "" }
q255670
Session.fetch_raw
validation
def fetch_raw(self, method, url, params=None, headers=None, data=None): """Make an HTTP request using aiohttp directly. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: aiohttp._RequestContextManager: ContextManager for a HTTP response. Raises: See ``aiohttp.ClientSession.request``. """
python
{ "resource": "" }
q255671
lookup_entities
validation
async def lookup_entities(client, args): """Search for entities by phone number, email, or gaia_id.""" lookup_spec = _get_lookup_spec(args.entity_identifier) request = hangups.hangouts_pb2.GetEntityByIdRequest(
python
{ "resource": "" }
q255672
_get_lookup_spec
validation
def _get_lookup_spec(identifier): """Return EntityLookupSpec from phone number, email address, or gaia ID.""" if identifier.startswith('+'): return hangups.hangouts_pb2.EntityLookupSpec( phone=identifier, create_offnetwork_gaia=True ) elif '@' in identifier:
python
{ "resource": "" }
q255673
get_conv_name
validation
def get_conv_name(conv, truncate=False, show_unread=False): """Return a readable name for a conversation. If the conversation has a custom name, use the custom name. Otherwise, for one-to-one conversations, the name is the full name of the other user. For group conversations, the name is a comma-separated list of first names. If the group conversation is empty, the name is "Empty Conversation". If truncate is true, only show up to two names in a group conversation. If show_unread is True, if there are unread chat messages, show the number of unread chat messages in parentheses after the conversation name. """ num_unread = len([conv_event for conv_event in conv.unread_events if isinstance(conv_event, hangups.ChatMessageEvent) and not conv.get_user(conv_event.user_id).is_self]) if show_unread and num_unread > 0: postfix = ' ({})'.format(num_unread) else: postfix = '' if conv.name is not None: return conv.name + postfix else: participants = sorted( (user
python
{ "resource": "" }
q255674
add_color_to_scheme
validation
def add_color_to_scheme(scheme, name, foreground, background, palette_colors): """Add foreground and background colours to a color scheme""" if foreground is None and background is None: return scheme new_scheme = [] for item in scheme: if item[0] == name: if foreground is None: foreground = item[1] if background is None: background = item[2]
python
{ "resource": "" }
q255675
_sync_all_conversations
validation
async def _sync_all_conversations(client): """Sync all conversations by making paginated requests. Conversations are ordered by ascending sort timestamp. Args: client (Client): Connected client. Raises: NetworkError: If the requests fail. Returns: tuple of list of ``ConversationState`` messages and sync timestamp """ conv_states = [] sync_timestamp = None request = hangouts_pb2.SyncRecentConversationsRequest( request_header=client.get_request_header(), max_conversations=CONVERSATIONS_PER_REQUEST, max_events_per_conversation=1, sync_filter=[ hangouts_pb2.SYNC_FILTER_INBOX, hangouts_pb2.SYNC_FILTER_ARCHIVED, ] ) for _ in range(MAX_CONVERSATION_PAGES): logger.info( 'Requesting conversations page %s', request.last_event_timestamp ) response = await client.sync_recent_conversations(request) conv_states = list(response.conversation_state) + conv_states sync_timestamp = parsers.from_timestamp( # SyncRecentConversations seems to return a sync_timestamp 4 # minutes before the present. To prevent SyncAllNewEvents later #
python
{ "resource": "" }
q255676
Conversation.unread_events
validation
def unread_events(self): """Loaded events which are unread sorted oldest to newest. Some Hangouts clients don't update the read timestamp for certain event types, such as membership changes, so this may return more unread events than these clients will show. There's also a delay between sending a message and the user's own
python
{ "resource": "" }
q255677
Conversation.is_quiet
validation
def is_quiet(self): """``True`` if notification level for this conversation is quiet.""" level
python
{ "resource": "" }
q255678
Conversation._on_watermark_notification
validation
def _on_watermark_notification(self, notif): """Handle a watermark notification.""" # Update the conversation: if self.get_user(notif.user_id).is_self: logger.info('latest_read_timestamp for {} updated to {}' .format(self.id_, notif.read_timestamp)) self_conversation_state = ( self._conversation.self_conversation_state ) self_conversation_state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(notif.read_timestamp) ) # Update the participants' watermarks: previous_timestamp = self._watermarks.get( notif.user_id,
python
{ "resource": "" }
q255679
Conversation.update_conversation
validation
def update_conversation(self, conversation): """Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message. """ # StateUpdate.conversation is actually a delta; fields that aren't # specified are assumed to be unchanged. Until this class is # refactored, hide this by saving and restoring previous values where # necessary. new_state = conversation.self_conversation_state old_state = self._conversation.self_conversation_state
python
{ "resource": "" }
q255680
Conversation._wrap_event
validation
def _wrap_event(event_): """Wrap hangouts_pb2.Event in ConversationEvent subclass.""" cls = conversation_event.ConversationEvent if event_.HasField('chat_message'): cls = conversation_event.ChatMessageEvent elif event_.HasField('otr_modification'): cls = conversation_event.OTREvent elif event_.HasField('conversation_rename'): cls = conversation_event.RenameEvent elif event_.HasField('membership_change'):
python
{ "resource": "" }
q255681
Conversation.add_event
validation
def add_event(self, event_): """Add an event to the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: event_: ``Event`` message. Returns: :class:`.ConversationEvent` representing the event.
python
{ "resource": "" }
q255682
Conversation._get_default_delivery_medium
validation
def _get_default_delivery_medium(self): """Return default DeliveryMedium to use for sending messages. Use the first option, or an option that's marked as the current default. """ medium_options = ( self._conversation.self_conversation_state.delivery_medium_option ) try: default_medium = medium_options[0].delivery_medium except IndexError: logger.warning('Conversation %r has no delivery medium', self.id_) default_medium = hangouts_pb2.DeliveryMedium(
python
{ "resource": "" }
q255683
Conversation._get_event_request_header
validation
def _get_event_request_header(self): """Return EventRequestHeader for conversation.""" otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD if self.is_off_the_record else
python
{ "resource": "" }
q255684
Conversation.send_message
validation
async def send_message(self, segments, image_file=None, image_id=None, image_user_id=None): """Send a message to this conversation. A per-conversation lock is acquired to ensure that messages are sent in the correct order when this method is called multiple times asynchronously. Args: segments: List of :class:`.ChatMessageSegment` objects to include in the message. image_file: (optional) File-like object containing an image to be attached to the message. image_id: (optional) ID of an Picasa photo to be attached to the message. If you specify both ``image_file`` and ``image_id`` together, ``image_file`` takes precedence and ``image_id`` will be ignored. image_user_id: (optional) Picasa user ID, required only if ``image_id`` refers to an image from a different Picasa user, such as Google's sticker user. Raises: .NetworkError: If the message cannot be sent. """ async with self._send_message_lock: if image_file: try: uploaded_image = await self._client.upload_image( image_file, return_uploaded_image=True ) except exceptions.NetworkError as e: logger.warning('Failed to upload image: {}'.format(e)) raise image_id = uploaded_image.image_id try: request = hangouts_pb2.SendChatMessageRequest(
python
{ "resource": "" }
q255685
Conversation.leave
validation
async def leave(self): """Leave this conversation. Raises: .NetworkError: If conversation cannot be left. """ is_group_conversation = (self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP) try: if is_group_conversation: await self._client.remove_user( hangouts_pb2.RemoveUserRequest( request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), ) ) else: await self._client.delete_conversation( hangouts_pb2.DeleteConversationRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(
python
{ "resource": "" }
q255686
Conversation.rename
validation
async def rename(self, name): """Rename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args:
python
{ "resource": "" }
q255687
Conversation.set_notification_level
validation
async def set_notification_level(self, level): """Set the notification level of this conversation. Args: level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or ``NOTIFICATION_LEVEL_RING`` to enable them. Raises: .NetworkError: If the request fails. """
python
{ "resource": "" }
q255688
Conversation.set_typing
validation
async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED): """Set your typing status in this conversation. Args: typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``, or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing, respectively. Defaults to ``TYPING_TYPE_STARTED``. Raises: .NetworkError: If typing status cannot be set. """ # TODO: Add rate-limiting to avoid unnecessary requests. try: await self._client.set_typing(
python
{ "resource": "" }
q255689
Conversation.update_read_timestamp
validation
async def update_read_timestamp(self, read_timestamp=None): """Update the timestamp of the latest event which has been read. This method will avoid making an API request if it will have no effect. Args: read_timestamp (datetime.datetime): (optional) Timestamp to set. Defaults to the timestamp of the newest event. Raises: .NetworkError: If the timestamp cannot be updated. """ if read_timestamp is None: read_timestamp = (self.events[-1].timestamp if self.events else datetime.datetime.now(datetime.timezone.utc)) if read_timestamp > self.latest_read_timestamp: logger.info( 'Setting {} latest_read_timestamp from {} to {}' .format(self.id_, self.latest_read_timestamp, read_timestamp) ) # Prevent duplicate requests by updating the conversation now. state = self._conversation.self_conversation_state state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(read_timestamp) )
python
{ "resource": "" }
q255690
Conversation.get_events
validation
async def get_events(self, event_id=None, max_events=50): """Get events from this conversation. Makes a request to load historical events if necessary. Args: event_id (str): (optional) If provided, return events preceding this event, otherwise return the newest events. max_events (int): Maximum number of events to return. Defaults to 50. Returns: List of :class:`.ConversationEvent` instances, ordered newest-first. Raises: KeyError: If ``event_id`` does not correspond to a known event. .NetworkError: If the events could not be requested. """ if event_id is None: # If no event_id is provided, return the newest events in this # conversation. conv_events = self._events[-1 * max_events:] else: # If event_id is provided, return the events we have that are # older, or request older events if event_id corresponds to the # oldest event we have. conv_event = self.get_event(event_id) if self._events[0].id_ != event_id: conv_events = self._events[self._events.index(conv_event) + 1:] else: logger.info('Loading events for conversation {} before {}' .format(self.id_, conv_event.timestamp)) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=self.id_ ) ), include_event=True, max_events_per_conversation=max_events, event_continuation_token=self._event_cont_token ) )
python
{ "resource": "" }
q255691
Conversation.next_event
validation
def next_event(self, event_id, prev=False): """Get the event following another event in this conversation. Args: event_id (str): ID of the event. prev (bool): If ``True``, return the previous event rather than the next event. Defaults to ``False``. Raises: KeyError: If no such :class:`.ConversationEvent` is known. Returns: :class:`.ConversationEvent` or ``None`` if there is no following event.
python
{ "resource": "" }
q255692
ConversationList.get_all
validation
def get_all(self, include_archived=False): """Get all the conversations. Args: include_archived (bool): (optional) Whether to include archived conversations. Defaults to ``False``. Returns:
python
{ "resource": "" }
q255693
ConversationList.leave_conversation
validation
async def leave_conversation(self, conv_id): """Leave a conversation. Args: conv_id (str): ID of conversation to leave. """
python
{ "resource": "" }
q255694
ConversationList._add_conversation
validation
def _add_conversation(self, conversation, events=[], event_cont_token=None): """Add new conversation from hangouts_pb2.Conversation""" # pylint: disable=dangerous-default-value
python
{ "resource": "" }
q255695
ConversationList._on_state_update
validation
async def _on_state_update(self, state_update): """Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance """ # The state update will include some type of notification: notification_type = state_update.WhichOneof('state_update') # If conversation fields have been updated, the state update will have # a conversation containing changed fields. Handle updating the # conversation from this delta: if state_update.HasField('conversation'): try: await self._handle_conversation_delta( state_update.conversation ) except exceptions.NetworkError: logger.warning( 'Discarding %s for %s: Failed to fetch conversation', notification_type.replace('_', ' '), state_update.conversation.conversation_id.id
python
{ "resource": "" }
q255696
ConversationList._get_or_fetch_conversation
validation
async def _get_or_fetch_conversation(self, conv_id): """Get a cached conversation or fetch a missing conversation. Args: conv_id: string, conversation identifier Raises: NetworkError: If the request to fetch the conversation fails. Returns: :class:`.Conversation` with matching ID. """ conv = self._conv_dict.get(conv_id, None) if conv is None: logger.info('Fetching unknown conversation %s', conv_id) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=conv_id )
python
{ "resource": "" }
q255697
ConversationList._on_event
validation
async def _on_event(self, event_): """Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance """ conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for event notification: %s', conv_id )
python
{ "resource": "" }
q255698
ConversationList._handle_conversation_delta
validation
async def _handle_conversation_delta(self, conversation): """Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed.
python
{ "resource": "" }
q255699
ConversationList._handle_set_typing_notification
validation
async def _handle_set_typing_notification(self, set_typing_notification): """Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance """ conv_id = set_typing_notification.conversation_id.id res = parsers.parse_typing_status_message(set_typing_notification) await self.on_typing.fire(res) try:
python
{ "resource": "" }