body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
aba23d841f320c3b586a7bcb72414cdd546443792923101496945d3d9fa4548a
def test_detailed_aquarium_update(self): 'Test changing the values of aquarium data' aquarium = sample_aquarium(user=self.user) payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True} url = detail_url(aquarium.id) self.client.put(url, payload) aquarium.refresh_from_db() self.assertEqual(aquarium.name, payload['name']) self.assertEqual(aquarium.water_type, payload['water_type']) self.assertEqual(aquarium.volume_liter, payload['volume_liter']) self.assertEqual(aquarium.length_cm, payload['length_cm']) self.assertEqual(aquarium.width_cm, payload['width_cm']) self.assertEqual(aquarium.height_cm, payload['height_cm']) self.assertEqual(aquarium.description, payload['description']) self.assertEqual(aquarium.is_planted, payload['is_planted'])
Test changing the values of aquarium data
aqua_track/aquarium/tests/test_aquarium_api.py
test_detailed_aquarium_update
nick-rc/aqua_track
0
python
def test_detailed_aquarium_update(self): aquarium = sample_aquarium(user=self.user) payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True} url = detail_url(aquarium.id) self.client.put(url, payload) aquarium.refresh_from_db() self.assertEqual(aquarium.name, payload['name']) self.assertEqual(aquarium.water_type, payload['water_type']) self.assertEqual(aquarium.volume_liter, payload['volume_liter']) self.assertEqual(aquarium.length_cm, payload['length_cm']) self.assertEqual(aquarium.width_cm, payload['width_cm']) self.assertEqual(aquarium.height_cm, payload['height_cm']) self.assertEqual(aquarium.description, payload['description']) self.assertEqual(aquarium.is_planted, payload['is_planted'])
def test_detailed_aquarium_update(self): aquarium = sample_aquarium(user=self.user) payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True} url = detail_url(aquarium.id) self.client.put(url, payload) aquarium.refresh_from_db() self.assertEqual(aquarium.name, payload['name']) self.assertEqual(aquarium.water_type, payload['water_type']) self.assertEqual(aquarium.volume_liter, payload['volume_liter']) self.assertEqual(aquarium.length_cm, payload['length_cm']) self.assertEqual(aquarium.width_cm, payload['width_cm']) self.assertEqual(aquarium.height_cm, payload['height_cm']) self.assertEqual(aquarium.description, payload['description']) self.assertEqual(aquarium.is_planted, payload['is_planted'])<|docstring|>Test changing the values of aquarium data<|endoftext|>
89173a9ef360ccd53ee61a27e1acb4eb8c46e45a1b697274996ceb4150db4dd1
def __init__(self, device=None): 'Initialize ToTensor object.' self.device = device
Initialize ToTensor object.
datasets/robotics/ToTensor.py
__init__
arav-agarwal2/MultiBench
0
python
def __init__(self, device=None): self.device = device
def __init__(self, device=None): self.device = device<|docstring|>Initialize ToTensor object.<|endoftext|>
52b20d46fc81d285baecf015caa46f1dcb6076897ea71d49eb70f20763ab31ab
def __call__(self, sample): 'Convert sample argument from ndarray with H,W,C dimensions to a tensor with C,H,W dimensions.' for k in sample.keys(): if k.startswith('flow'): sample[k] = sample[k].transpose((2, 0, 1)) new_dict = dict() for (k, v) in sample.items(): if (self.device is None): new_dict[k] = torch.FloatTensor(v) else: new_dict[k] = torch.from_numpy(v).float() return new_dict
Convert sample argument from ndarray with H,W,C dimensions to a tensor with C,H,W dimensions.
datasets/robotics/ToTensor.py
__call__
arav-agarwal2/MultiBench
0
python
def __call__(self, sample): for k in sample.keys(): if k.startswith('flow'): sample[k] = sample[k].transpose((2, 0, 1)) new_dict = dict() for (k, v) in sample.items(): if (self.device is None): new_dict[k] = torch.FloatTensor(v) else: new_dict[k] = torch.from_numpy(v).float() return new_dict
def __call__(self, sample): for k in sample.keys(): if k.startswith('flow'): sample[k] = sample[k].transpose((2, 0, 1)) new_dict = dict() for (k, v) in sample.items(): if (self.device is None): new_dict[k] = torch.FloatTensor(v) else: new_dict[k] = torch.from_numpy(v).float() return new_dict<|docstring|>Convert sample argument from ndarray with H,W,C dimensions to a tensor with C,H,W dimensions.<|endoftext|>
f9b2495f1cb4dc53bd4ed9509869dead7930b15f236a4eed0e610a4f00181455
def SchwarzschildMetric(symbolstr='t r theta phi'): "\n Returns Metric Tensor of symbols of Schwarzschild Metric.\n\n Parameters\n ----------\n symbolstr : string\n symbols to be used to define schwarzschild space, defaults to 't r theta phi'\n\n Returns\n -------\n ~einsteinpy.symbolic.metric.MetricTensor\n Metric Tensor for Schwarzschild space-time\n " raise_warning(PendingDeprecationWarning, 'SchwarzschildMetric class would be deprecated with v0.3.0 !') list2d = [[0 for i in range(4)] for i in range(4)] syms = sympy.symbols(symbolstr) (c, a) = sympy.symbols('c a') list2d[0][0] = (1 - (a / syms[1])) list2d[1][1] = ((- 1) / ((1 - (a / syms[1])) * (c ** 2))) list2d[2][2] = (((- 1) * (syms[1] ** 2)) / (c ** 2)) list2d[3][3] = ((((- 1) * (syms[1] ** 2)) * (sympy.sin(syms[2]) ** 2)) / (c ** 2)) return MetricTensor(list2d, syms, name='SchwarzschildMetric')
Returns Metric Tensor of symbols of Schwarzschild Metric. Parameters ---------- symbolstr : string symbols to be used to define schwarzschild space, defaults to 't r theta phi' Returns ------- ~einsteinpy.symbolic.metric.MetricTensor Metric Tensor for Schwarzschild space-time
src/einsteinpy/symbolic/vacuum_metrics.py
SchwarzschildMetric
anish29292/einsteinpy
2
python
def SchwarzschildMetric(symbolstr='t r theta phi'): "\n Returns Metric Tensor of symbols of Schwarzschild Metric.\n\n Parameters\n ----------\n symbolstr : string\n symbols to be used to define schwarzschild space, defaults to 't r theta phi'\n\n Returns\n -------\n ~einsteinpy.symbolic.metric.MetricTensor\n Metric Tensor for Schwarzschild space-time\n " raise_warning(PendingDeprecationWarning, 'SchwarzschildMetric class would be deprecated with v0.3.0 !') list2d = [[0 for i in range(4)] for i in range(4)] syms = sympy.symbols(symbolstr) (c, a) = sympy.symbols('c a') list2d[0][0] = (1 - (a / syms[1])) list2d[1][1] = ((- 1) / ((1 - (a / syms[1])) * (c ** 2))) list2d[2][2] = (((- 1) * (syms[1] ** 2)) / (c ** 2)) list2d[3][3] = ((((- 1) * (syms[1] ** 2)) * (sympy.sin(syms[2]) ** 2)) / (c ** 2)) return MetricTensor(list2d, syms, name='SchwarzschildMetric')
def SchwarzschildMetric(symbolstr='t r theta phi'): "\n Returns Metric Tensor of symbols of Schwarzschild Metric.\n\n Parameters\n ----------\n symbolstr : string\n symbols to be used to define schwarzschild space, defaults to 't r theta phi'\n\n Returns\n -------\n ~einsteinpy.symbolic.metric.MetricTensor\n Metric Tensor for Schwarzschild space-time\n " raise_warning(PendingDeprecationWarning, 'SchwarzschildMetric class would be deprecated with v0.3.0 !') list2d = [[0 for i in range(4)] for i in range(4)] syms = sympy.symbols(symbolstr) (c, a) = sympy.symbols('c a') list2d[0][0] = (1 - (a / syms[1])) list2d[1][1] = ((- 1) / ((1 - (a / syms[1])) * (c ** 2))) list2d[2][2] = (((- 1) * (syms[1] ** 2)) / (c ** 2)) list2d[3][3] = ((((- 1) * (syms[1] ** 2)) * (sympy.sin(syms[2]) ** 2)) / (c ** 2)) return MetricTensor(list2d, syms, name='SchwarzschildMetric')<|docstring|>Returns Metric Tensor of symbols of Schwarzschild Metric. Parameters ---------- symbolstr : string symbols to be used to define schwarzschild space, defaults to 't r theta phi' Returns ------- ~einsteinpy.symbolic.metric.MetricTensor Metric Tensor for Schwarzschild space-time<|endoftext|>
858a7cff948665cb16177534d47ca57bfee2a6c7dd9e5f9b4532e5705109f75a
def __init__(self, path_to_keyfile: str) -> None: '\n Initializes the push service\n Args:\n path_to_keyfile: Path to json keyfile with firebase credentials\n ' cred = credentials.Certificate(path_to_keyfile) self._app = firebase_admin.initialize_app(cred)
Initializes the push service Args: path_to_keyfile: Path to json keyfile with firebase credentials
relay/pushservice/pushservice.py
__init__
weilbith/relay
0
python
def __init__(self, path_to_keyfile: str) -> None: '\n Initializes the push service\n Args:\n path_to_keyfile: Path to json keyfile with firebase credentials\n ' cred = credentials.Certificate(path_to_keyfile) self._app = firebase_admin.initialize_app(cred)
def __init__(self, path_to_keyfile: str) -> None: '\n Initializes the push service\n Args:\n path_to_keyfile: Path to json keyfile with firebase credentials\n ' cred = credentials.Certificate(path_to_keyfile) self._app = firebase_admin.initialize_app(cred)<|docstring|>Initializes the push service Args: path_to_keyfile: Path to json keyfile with firebase credentials<|endoftext|>
10827587a05fb73ca82425486f6103907ebf230305bf69b159372225700be79a
def check_client_token(self, client_token: str) -> bool: '\n Check if the client_token is valid by sending a test message with the dry_run flag being set\n Args:\n client_token: The client token to check\n\n Returns: True if the client token is valid, false otherwise\n\n ' test_message = messaging.Message(token=client_token) try: messaging.send(test_message, app=self._app, dry_run=True) except ValueError: return False except messaging.ApiCallError as e: if (e.code in INVALID_CLIENT_TOKEN_ERRORS): logger.debug(f'Invalid client token {client_token}: {e.code}') return False else: raise return True
Check if the client_token is valid by sending a test message with the dry_run flag being set Args: client_token: The client token to check Returns: True if the client token is valid, false otherwise
relay/pushservice/pushservice.py
check_client_token
weilbith/relay
0
python
def check_client_token(self, client_token: str) -> bool: '\n Check if the client_token is valid by sending a test message with the dry_run flag being set\n Args:\n client_token: The client token to check\n\n Returns: True if the client token is valid, false otherwise\n\n ' test_message = messaging.Message(token=client_token) try: messaging.send(test_message, app=self._app, dry_run=True) except ValueError: return False except messaging.ApiCallError as e: if (e.code in INVALID_CLIENT_TOKEN_ERRORS): logger.debug(f'Invalid client token {client_token}: {e.code}') return False else: raise return True
def check_client_token(self, client_token: str) -> bool: '\n Check if the client_token is valid by sending a test message with the dry_run flag being set\n Args:\n client_token: The client token to check\n\n Returns: True if the client token is valid, false otherwise\n\n ' test_message = messaging.Message(token=client_token) try: messaging.send(test_message, app=self._app, dry_run=True) except ValueError: return False except messaging.ApiCallError as e: if (e.code in INVALID_CLIENT_TOKEN_ERRORS): logger.debug(f'Invalid client token {client_token}: {e.code}') return False else: raise return True<|docstring|>Check if the client_token is valid by sending a test message with the dry_run flag being set Args: client_token: The client token to check Returns: True if the client token is valid, false otherwise<|endoftext|>
6419407f95fcc72189adc7f930441ce38cce3f4012b01aa4c4c5b13aa8c2f30c
def __init__(self, client_token_db: ClientTokenDB, firebaseRawPushService: FirebaseRawPushService) -> None: '\n Args:\n client_token_db: Database to map ethereum address to client token\n firebaseRawPushService: Initialized firebase service to send push notifications\n ' self._firebaseRawPushService = firebaseRawPushService self._client_token_db = client_token_db
Args: client_token_db: Database to map ethereum address to client token firebaseRawPushService: Initialized firebase service to send push notifications
relay/pushservice/pushservice.py
__init__
weilbith/relay
0
python
def __init__(self, client_token_db: ClientTokenDB, firebaseRawPushService: FirebaseRawPushService) -> None: '\n Args:\n client_token_db: Database to map ethereum address to client token\n firebaseRawPushService: Initialized firebase service to send push notifications\n ' self._firebaseRawPushService = firebaseRawPushService self._client_token_db = client_token_db
def __init__(self, client_token_db: ClientTokenDB, firebaseRawPushService: FirebaseRawPushService) -> None: '\n Args:\n client_token_db: Database to map ethereum address to client token\n firebaseRawPushService: Initialized firebase service to send push notifications\n ' self._firebaseRawPushService = firebaseRawPushService self._client_token_db = client_token_db<|docstring|>Args: client_token_db: Database to map ethereum address to client token firebaseRawPushService: Initialized firebase service to send push notifications<|endoftext|>
c237c3ac86d1991cf7ea3fdb827c70494b9d356e2c067d1adb10c770b16a8325
def send_event(self, user_address: str, event: Event) -> None: '\n Sends an event to a user. The client to push the notification to is taken from the database\n ' for client_token in list(self._client_token_db.get_client_tokens(user_address)): try: logger.debug(f'Sending pushnotification of {event.type} to {user_address} with client token {client_token}') self._firebaseRawPushService.send_event(client_token, event) except InvalidClientTokenException: logger.debug(f'Removing invalid token {client_token} for {user_address}') self._client_token_db.delete_client_token(user_address, client_token)
Sends an event to a user. The client to push the notification to is taken from the database
relay/pushservice/pushservice.py
send_event
weilbith/relay
0
python
def send_event(self, user_address: str, event: Event) -> None: '\n \n ' for client_token in list(self._client_token_db.get_client_tokens(user_address)): try: logger.debug(f'Sending pushnotification of {event.type} to {user_address} with client token {client_token}') self._firebaseRawPushService.send_event(client_token, event) except InvalidClientTokenException: logger.debug(f'Removing invalid token {client_token} for {user_address}') self._client_token_db.delete_client_token(user_address, client_token)
def send_event(self, user_address: str, event: Event) -> None: '\n \n ' for client_token in list(self._client_token_db.get_client_tokens(user_address)): try: logger.debug(f'Sending pushnotification of {event.type} to {user_address} with client token {client_token}') self._firebaseRawPushService.send_event(client_token, event) except InvalidClientTokenException: logger.debug(f'Removing invalid token {client_token} for {user_address}') self._client_token_db.delete_client_token(user_address, client_token)<|docstring|>Sends an event to a user. The client to push the notification to is taken from the database<|endoftext|>
10e7688f87bd9acc5d781027edee7c86c81c1807fd0b8f7fd51dc0466fbd709f
@classmethod def setup_class(cls): ' Set up an agave mock server\n\n Listen and serve mock api as a daemon.\n ' MockServer.serve.__func__(cls, MockServerListingsEndpoints)
Set up an agave mock server Listen and serve mock api as a daemon.
tests/files-pems_test.py
setup_class
jchuahtacc/agavepy
0
python
@classmethod def setup_class(cls): ' Set up an agave mock server\n\n Listen and serve mock api as a daemon.\n ' MockServer.serve.__func__(cls, MockServerListingsEndpoints)
@classmethod def setup_class(cls): ' Set up an agave mock server\n\n Listen and serve mock api as a daemon.\n ' MockServer.serve.__func__(cls, MockServerListingsEndpoints)<|docstring|>Set up an agave mock server Listen and serve mock api as a daemon.<|endoftext|>
7b0130e7fbd1878900220aaaec5a7b521a077c1ce376286941939eade2eb1dac
def test_files_pems_list(self, capfd): ' Test permissions listings\n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_list('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('username' in out) assert ('yes' in out) assert ('200' in err)
Test permissions listings
tests/files-pems_test.py
test_files_pems_list
jchuahtacc/agavepy
0
python
def test_files_pems_list(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_list('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('username' in out) assert ('yes' in out) assert ('200' in err)
def test_files_pems_list(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_list('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('username' in out) assert ('yes' in out) assert ('200' in err)<|docstring|>Test permissions listings<|endoftext|>
b49ade9b45a091a9802aca8832c9f0c9f6df25381d7fca2b61da36b5134b496e
def test_files_pems_delete(self, capfd): ' Test permissions deletion\n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_delete('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('200' in err)
Test permissions deletion
tests/files-pems_test.py
test_files_pems_delete
jchuahtacc/agavepy
0
python
def test_files_pems_delete(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_delete('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('200' in err)
def test_files_pems_delete(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_delete('tacc-globalfs-username/') (out, err) = capfd.readouterr() assert ('200' in err)<|docstring|>Test permissions deletion<|endoftext|>
6bb2e4b73b799a3b1b8b77408984ebc4be26275c20e5a1a692fc49135fee8ad0
def test_files_pems_update(self, capfd): ' Test permissions updates\n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_update('tacc-globalfs-username/', 'collaborator', 'ALL') (out, err) = capfd.readouterr() assert ('200' in err)
Test permissions updates
tests/files-pems_test.py
test_files_pems_update
jchuahtacc/agavepy
0
python
def test_files_pems_update(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_update('tacc-globalfs-username/', 'collaborator', 'ALL') (out, err) = capfd.readouterr() assert ('200' in err)
def test_files_pems_update(self, capfd): ' \n ' local_uri = 'http://localhost:{port}/'.format(port=self.mock_server_port) agave = Agave(api_server=local_uri) agave.token = 'mock-access-token' agave.created_at = str(int(time.time())) agave.expires_in = str(14400) agave.files_pems_update('tacc-globalfs-username/', 'collaborator', 'ALL') (out, err) = capfd.readouterr() assert ('200' in err)<|docstring|>Test permissions updates<|endoftext|>
be7c170a8f20de8e8b5cc08e14df590a5f8e42bbf045f9b83217c76508fbb1bc
def __init__(self, defaults={}, data=None): 'Initialize the instance, by default from the default\n parameters given in the class' super().__init__(defaults={**TableParameters.parameters, **defaults}, data=data)
Initialize the instance, by default from the default parameters given in the class
table_step/table_parameters.py
__init__
MolSSI/table_step
0
python
def __init__(self, defaults={}, data=None): 'Initialize the instance, by default from the default\n parameters given in the class' super().__init__(defaults={**TableParameters.parameters, **defaults}, data=data)
def __init__(self, defaults={}, data=None): 'Initialize the instance, by default from the default\n parameters given in the class' super().__init__(defaults={**TableParameters.parameters, **defaults}, data=data)<|docstring|>Initialize the instance, by default from the default parameters given in the class<|endoftext|>
4a1743438424247b57de6abe347e8ecec971f9d825a2615ce4516bb831d578d7
def get_farther_atom_num(no_defect_poscar, one_defect_poscar): '\n Return:\n 1: atom number of the farther atom in defect system\n 2: atom number of the farther atom in defect-free system\n ' all_basis = generate_all_basis(1, 1, 1) no_defect = read_vasp(no_defect_poscar) one_defect = read_vasp(one_defect_poscar) no_def_pos = no_defect.positions one_def_pos = one_defect.positions c = no_defect.lattice no_def_pos = np.dot(no_def_pos, c) one_def_pos = np.dot(one_def_pos, c) (ii, d) = get_delete_atom_num(no_defect_poscar, one_defect_poscar) defect_atom = no_def_pos[ii] extend_S = [] (d, idx) = (np.zeros((no_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((no_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_no_def = np.argmax(np.min(d, axis=1)) (d, idx) = (np.zeros((one_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((one_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_one_def = np.argmax(np.min(d, axis=1)) return ((max_idx_one_def + 1), (max_idx_no_def + 1))
Return: 1: atom number of the farther atom in defect system 2: atom number of the farther atom in defect-free system
pyvaspflow/utils.py
get_farther_atom_num
ChangChunHe/VASP-calculation-process
13
python
def get_farther_atom_num(no_defect_poscar, one_defect_poscar): '\n Return:\n 1: atom number of the farther atom in defect system\n 2: atom number of the farther atom in defect-free system\n ' all_basis = generate_all_basis(1, 1, 1) no_defect = read_vasp(no_defect_poscar) one_defect = read_vasp(one_defect_poscar) no_def_pos = no_defect.positions one_def_pos = one_defect.positions c = no_defect.lattice no_def_pos = np.dot(no_def_pos, c) one_def_pos = np.dot(one_def_pos, c) (ii, d) = get_delete_atom_num(no_defect_poscar, one_defect_poscar) defect_atom = no_def_pos[ii] extend_S = [] (d, idx) = (np.zeros((no_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((no_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_no_def = np.argmax(np.min(d, axis=1)) (d, idx) = (np.zeros((one_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((one_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_one_def = np.argmax(np.min(d, axis=1)) return ((max_idx_one_def + 1), (max_idx_no_def + 1))
def get_farther_atom_num(no_defect_poscar, one_defect_poscar): '\n Return:\n 1: atom number of the farther atom in defect system\n 2: atom number of the farther atom in defect-free system\n ' all_basis = generate_all_basis(1, 1, 1) no_defect = read_vasp(no_defect_poscar) one_defect = read_vasp(one_defect_poscar) no_def_pos = no_defect.positions one_def_pos = one_defect.positions c = no_defect.lattice no_def_pos = np.dot(no_def_pos, c) one_def_pos = np.dot(one_def_pos, c) (ii, d) = get_delete_atom_num(no_defect_poscar, one_defect_poscar) defect_atom = no_def_pos[ii] extend_S = [] (d, idx) = (np.zeros((no_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((no_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_no_def = np.argmax(np.min(d, axis=1)) (d, idx) = (np.zeros((one_def_pos.shape[0], 27)), 0) for basis in all_basis: (i, j, k) = basis d[(:, idx)] = np.linalg.norm((defect_atom - (((one_def_pos + (i * c[0])) + (j * c[1])) + (k * c[2]))), axis=1) idx += 1 max_idx_one_def = np.argmax(np.min(d, axis=1)) return ((max_idx_one_def + 1), (max_idx_no_def + 1))<|docstring|>Return: 1: atom number of the farther atom in defect system 2: atom number of the farther atom in defect-free system<|endoftext|>
f1ed89aae6efa8a4dc13a7df13b00a4b7ad7964ad0ea519fe5690502c96cc3cd
def str_delimited(results, header=None, delimiter='\t'): '\n Given a tuple of tuples, generate a delimited string form.\n >>> results = [["a","b","c"],["d","e","f"],[1,2,3]]\n >>> print(str_delimited(results,delimiter=","))\n a,b,c\n d,e,f\n 1,2,3\n Args:\n result: 2d sequence of arbitrary types.\n header: optional header\n Returns:\n Aligned string output in a table-like format.\n ' returnstr = '' if (header is not None): returnstr += (delimiter.join(header) + '\n') return (returnstr + '\n'.join([delimiter.join([str(m) for m in result]) for result in results]))
Given a tuple of tuples, generate a delimited string form. >>> results = [["a","b","c"],["d","e","f"],[1,2,3]] >>> print(str_delimited(results,delimiter=",")) a,b,c d,e,f 1,2,3 Args: result: 2d sequence of arbitrary types. header: optional header Returns: Aligned string output in a table-like format.
pyvaspflow/utils.py
str_delimited
ChangChunHe/VASP-calculation-process
13
python
def str_delimited(results, header=None, delimiter='\t'): '\n Given a tuple of tuples, generate a delimited string form.\n >>> results = [["a","b","c"],["d","e","f"],[1,2,3]]\n >>> print(str_delimited(results,delimiter=","))\n a,b,c\n d,e,f\n 1,2,3\n Args:\n result: 2d sequence of arbitrary types.\n header: optional header\n Returns:\n Aligned string output in a table-like format.\n ' returnstr = if (header is not None): returnstr += (delimiter.join(header) + '\n') return (returnstr + '\n'.join([delimiter.join([str(m) for m in result]) for result in results]))
def str_delimited(results, header=None, delimiter='\t'): '\n Given a tuple of tuples, generate a delimited string form.\n >>> results = [["a","b","c"],["d","e","f"],[1,2,3]]\n >>> print(str_delimited(results,delimiter=","))\n a,b,c\n d,e,f\n 1,2,3\n Args:\n result: 2d sequence of arbitrary types.\n header: optional header\n Returns:\n Aligned string output in a table-like format.\n ' returnstr = if (header is not None): returnstr += (delimiter.join(header) + '\n') return (returnstr + '\n'.join([delimiter.join([str(m) for m in result]) for result in results]))<|docstring|>Given a tuple of tuples, generate a delimited string form. >>> results = [["a","b","c"],["d","e","f"],[1,2,3]] >>> print(str_delimited(results,delimiter=",")) a,b,c d,e,f 1,2,3 Args: result: 2d sequence of arbitrary types. header: optional header Returns: Aligned string output in a table-like format.<|endoftext|>
4ef55c48279ff7e105ee6740a33a0696c50ffbfc19af2bfcf957583ae765e59f
def unlzw(data): "\n This function was adapted for Python from Mark Adler's C implementation\n https://github.com/umeat/unlzw\n Decompress compressed data generated by the Unix compress utility (LZW\n compression, files with .Z suffix). Input can be given as any type which\n can be 'converted' to a bytearray (e.g. string, or bytearray). Returns\n decompressed data as string, or raises error.\n Written by Brandon Owen, May 2016, example@example.com\n Adapted from original work by Mark Adler - orginal copyright notice below\n Copyright (C) 2014, 2015 Mark Adler\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the authors be held liable for any damages\n arising from the use of this software.\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n Mark Adler\n example@example.com\n " try: ba_in = bytearray(data) except ValueError: raise TypeError('Unable to convert inputted data to bytearray') inlen = len(ba_in) prefix = ([None] * 65536) suffix = ([None] * 65536) if (inlen < 3): raise ValueError('Invalid Input: Length of input too short for processing') if ((ba_in[0] != 31) or (ba_in[1] != 157)): raise ValueError('Invalid Header Flags Byte: Incorrect magic bytes') flags = ba_in[2] if (flags & 96): raise ValueError('Invalid Header Flags Byte: Flag byte contains invalid data') max_ = (flags & 31) if ((max_ < 9) or (max_ > 16)): raise ValueError('Invalid Header Flags Byte: Max code size bits out of range') if (max_ == 9): max_ = 10 flags &= 128 bits = 9 mask = 511 end = (256 if flags else 255) if (inlen == 3): return 0 if (inlen == 4): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf = ba_in[3] buf += (ba_in[4] << 8) final = prev = (buf & mask) buf >>= bits left = (16 - bits) if (prev > 255): raise ValueError('Invalid Data: First code must be a literal') put = [final] mark = 3 nxt = 5 while (nxt < inlen): if ((end >= mask) and (bits < max_)): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem >= (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits += 1 mask <<= 1 mask += 1 buf += (ba_in[nxt] << left) nxt += 1 left += 8 if (left < bits): if (nxt == inlen): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf += (ba_in[nxt] << left) nxt += 1 left += 8 code = (buf & mask) buf >>= bits left -= bits if ((code == 256) and flags): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem > (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits = 9 mask = 511 end = 255 continue temp = code stack = [] if (code > end): if ((code != (end + 1)) or (prev > end)): raise ValueError('Invalid Data: Invalid code detected') stack.append(final) code = prev while (code >= 256): stack.append(suffix[code]) code = prefix[code] stack.append(code) final = code if (end < mask): end += 1 prefix[end] = prev suffix[end] = final prev = temp put += stack[::(- 1)] return bytes(bytearray(put))
This function was adapted for Python from Mark Adler's C implementation https://github.com/umeat/unlzw Decompress compressed data generated by the Unix compress utility (LZW compression, files with .Z suffix). Input can be given as any type which can be 'converted' to a bytearray (e.g. string, or bytearray). Returns decompressed data as string, or raises error. Written by Brandon Owen, May 2016, example@example.com Adapted from original work by Mark Adler - orginal copyright notice below Copyright (C) 2014, 2015 Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Mark Adler example@example.com
pyvaspflow/utils.py
unlzw
ChangChunHe/VASP-calculation-process
13
python
def unlzw(data): "\n This function was adapted for Python from Mark Adler's C implementation\n https://github.com/umeat/unlzw\n Decompress compressed data generated by the Unix compress utility (LZW\n compression, files with .Z suffix). Input can be given as any type which\n can be 'converted' to a bytearray (e.g. string, or bytearray). Returns\n decompressed data as string, or raises error.\n Written by Brandon Owen, May 2016, example@example.com\n Adapted from original work by Mark Adler - orginal copyright notice below\n Copyright (C) 2014, 2015 Mark Adler\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the authors be held liable for any damages\n arising from the use of this software.\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n Mark Adler\n example@example.com\n " try: ba_in = bytearray(data) except ValueError: raise TypeError('Unable to convert inputted data to bytearray') inlen = len(ba_in) prefix = ([None] * 65536) suffix = ([None] * 65536) if (inlen < 3): raise ValueError('Invalid Input: Length of input too short for processing') if ((ba_in[0] != 31) or (ba_in[1] != 157)): raise ValueError('Invalid Header Flags Byte: Incorrect magic bytes') flags = ba_in[2] if (flags & 96): raise ValueError('Invalid Header Flags Byte: Flag byte contains invalid data') max_ = (flags & 31) if ((max_ < 9) or (max_ > 16)): raise ValueError('Invalid Header Flags Byte: Max code size bits out of range') if (max_ == 9): max_ = 10 flags &= 128 bits = 9 mask = 511 end = (256 if flags else 255) if (inlen == 3): return 0 if (inlen == 4): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf = ba_in[3] buf += (ba_in[4] << 8) final = prev = (buf & mask) buf >>= bits left = (16 - bits) if (prev > 255): raise ValueError('Invalid Data: First code must be a literal') put = [final] mark = 3 nxt = 5 while (nxt < inlen): if ((end >= mask) and (bits < max_)): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem >= (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits += 1 mask <<= 1 mask += 1 buf += (ba_in[nxt] << left) nxt += 1 left += 8 if (left < bits): if (nxt == inlen): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf += (ba_in[nxt] << left) nxt += 1 left += 8 code = (buf & mask) buf >>= bits left -= bits if ((code == 256) and flags): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem > (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits = 9 mask = 511 end = 255 continue temp = code stack = [] if (code > end): if ((code != (end + 1)) or (prev > end)): raise ValueError('Invalid Data: Invalid code detected') stack.append(final) code = prev while (code >= 256): stack.append(suffix[code]) code = prefix[code] stack.append(code) final = code if (end < mask): end += 1 prefix[end] = prev suffix[end] = final prev = temp put += stack[::(- 1)] return bytes(bytearray(put))
def unlzw(data): "\n This function was adapted for Python from Mark Adler's C implementation\n https://github.com/umeat/unlzw\n Decompress compressed data generated by the Unix compress utility (LZW\n compression, files with .Z suffix). Input can be given as any type which\n can be 'converted' to a bytearray (e.g. string, or bytearray). Returns\n decompressed data as string, or raises error.\n Written by Brandon Owen, May 2016, example@example.com\n Adapted from original work by Mark Adler - orginal copyright notice below\n Copyright (C) 2014, 2015 Mark Adler\n This software is provided 'as-is', without any express or implied\n warranty. In no event will the authors be held liable for any damages\n arising from the use of this software.\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n 1. The origin of this software must not be misrepresented; you must not\n claim that you wrote the original software. If you use this software\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n 3. This notice may not be removed or altered from any source distribution.\n Mark Adler\n example@example.com\n " try: ba_in = bytearray(data) except ValueError: raise TypeError('Unable to convert inputted data to bytearray') inlen = len(ba_in) prefix = ([None] * 65536) suffix = ([None] * 65536) if (inlen < 3): raise ValueError('Invalid Input: Length of input too short for processing') if ((ba_in[0] != 31) or (ba_in[1] != 157)): raise ValueError('Invalid Header Flags Byte: Incorrect magic bytes') flags = ba_in[2] if (flags & 96): raise ValueError('Invalid Header Flags Byte: Flag byte contains invalid data') max_ = (flags & 31) if ((max_ < 9) or (max_ > 16)): raise ValueError('Invalid Header Flags Byte: Max code size bits out of range') if (max_ == 9): max_ = 10 flags &= 128 bits = 9 mask = 511 end = (256 if flags else 255) if (inlen == 3): return 0 if (inlen == 4): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf = ba_in[3] buf += (ba_in[4] << 8) final = prev = (buf & mask) buf >>= bits left = (16 - bits) if (prev > 255): raise ValueError('Invalid Data: First code must be a literal') put = [final] mark = 3 nxt = 5 while (nxt < inlen): if ((end >= mask) and (bits < max_)): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem >= (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits += 1 mask <<= 1 mask += 1 buf += (ba_in[nxt] << left) nxt += 1 left += 8 if (left < bits): if (nxt == inlen): raise ValueError('Invalid Data: Stream ended in the middle of a code') buf += (ba_in[nxt] << left) nxt += 1 left += 8 code = (buf & mask) buf >>= bits left -= bits if ((code == 256) and flags): rem = ((nxt - mark) % bits) if rem: rem = (bits - rem) if (rem > (inlen - nxt)): break nxt += rem buf = 0 left = 0 mark = nxt bits = 9 mask = 511 end = 255 continue temp = code stack = [] if (code > end): if ((code != (end + 1)) or (prev > end)): raise ValueError('Invalid Data: Invalid code detected') stack.append(final) code = prev while (code >= 256): stack.append(suffix[code]) code = prefix[code] stack.append(code) final = code if (end < mask): end += 1 prefix[end] = prev suffix[end] = final prev = temp put += stack[::(- 1)] return bytes(bytearray(put))<|docstring|>This function was adapted for Python from Mark Adler's C implementation https://github.com/umeat/unlzw Decompress compressed data generated by the Unix compress utility (LZW compression, files with .Z suffix). Input can be given as any type which can be 'converted' to a bytearray (e.g. string, or bytearray). Returns decompressed data as string, or raises error. Written by Brandon Owen, May 2016, example@example.com Adapted from original work by Mark Adler - orginal copyright notice below Copyright (C) 2014, 2015 Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Mark Adler example@example.com<|endoftext|>
b33d437e6df581b1306783152f2826bbcc2149204cb2b047f361131ee31da395
def next(self): 'For Python 2 compatibility' return self.__next__()
For Python 2 compatibility
platformio/clients/http.py
next
Dim0N22/platformio-core
4,744
python
def next(self): return self.__next__()
def next(self): return self.__next__()<|docstring|>For Python 2 compatibility<|endoftext|>
90aec17ae0e712ef42fe712138927f956ba42f79b0bbad05318b8aea6b93baf5
def transpose(x): 'Implementation of `transpose`.' shape = F.shape(x) length = F.tuple_len(shape) perm = F.make_range(0, length) revert_perm = F.tuple_reversed(perm) out = trans(x, revert_perm) return out
Implementation of `transpose`.
mindspore/_extends/parse/standard_method.py
transpose
ezphlow/mindspore
1
python
def transpose(x): shape = F.shape(x) length = F.tuple_len(shape) perm = F.make_range(0, length) revert_perm = F.tuple_reversed(perm) out = trans(x, revert_perm) return out
def transpose(x): shape = F.shape(x) length = F.tuple_len(shape) perm = F.make_range(0, length) revert_perm = F.tuple_reversed(perm) out = trans(x, revert_perm) return out<|docstring|>Implementation of `transpose`.<|endoftext|>
0b7b7dec2f1f9ef4d03def76d530059d7ccd5ccc5eab68a58f176a071fe2d8db
def getitem(data, item): 'Implementation of `getitem`.' return data.__getitem__(item)
Implementation of `getitem`.
mindspore/_extends/parse/standard_method.py
getitem
ezphlow/mindspore
1
python
def getitem(data, item): return data.__getitem__(item)
def getitem(data, item): return data.__getitem__(item)<|docstring|>Implementation of `getitem`.<|endoftext|>
60a917949415cf6001af6f02afb88331eec17142c699474b8272e9fcaa703ea8
def setitem(data, item, value): 'Implementation of `setitem`.' return data.__setitem__(item, value)
Implementation of `setitem`.
mindspore/_extends/parse/standard_method.py
setitem
ezphlow/mindspore
1
python
def setitem(data, item, value): return data.__setitem__(item, value)
def setitem(data, item, value): return data.__setitem__(item, value)<|docstring|>Implementation of `setitem`.<|endoftext|>
7919b9d0e24a46cfe9d16601bff5fa27486b78f205b4c5301fbcbf7ac7781001
def ms_iter(xs): 'Implementation of `iter`.' return xs.__ms_iter__()
Implementation of `iter`.
mindspore/_extends/parse/standard_method.py
ms_iter
ezphlow/mindspore
1
python
def ms_iter(xs): return xs.__ms_iter__()
def ms_iter(xs): return xs.__ms_iter__()<|docstring|>Implementation of `iter`.<|endoftext|>
73b49bb844b89c9e1818e59203162a5d3efe417a4ab261423ffedd8f5b6976bf
def ms_next(it): 'Implementation of `next`.' return it.__ms_next__()
Implementation of `next`.
mindspore/_extends/parse/standard_method.py
ms_next
ezphlow/mindspore
1
python
def ms_next(it): return it.__ms_next__()
def ms_next(it): return it.__ms_next__()<|docstring|>Implementation of `next`.<|endoftext|>
84a2076c29405711f9cd87da3594448581e5218f0594a473702256dd47857fd8
def hasnext(it): 'Implementation of `hasnext`.' return it.__ms_hasnext__()
Implementation of `hasnext`.
mindspore/_extends/parse/standard_method.py
hasnext
ezphlow/mindspore
1
python
def hasnext(it): return it.__ms_hasnext__()
def hasnext(it): return it.__ms_hasnext__()<|docstring|>Implementation of `hasnext`.<|endoftext|>
021754ab11a23f1abd43dc878a5a097b3ecd2cf7f32ff643972b2bae50a2512a
def ms_len(data): 'Implementation of `len`.' return data.__len__()
Implementation of `len`.
mindspore/_extends/parse/standard_method.py
ms_len
ezphlow/mindspore
1
python
def ms_len(data): return data.__len__()
def ms_len(data): return data.__len__()<|docstring|>Implementation of `len`.<|endoftext|>
f2acc5b434ab719dcfd97e87f1d7a39d019cd7832e924705239526a2206aa1ec
def floor(x): 'Implementation of `floor`.' return x.__floor__()
Implementation of `floor`.
mindspore/_extends/parse/standard_method.py
floor
ezphlow/mindspore
1
python
def floor(x): return x.__floor__()
def floor(x): return x.__floor__()<|docstring|>Implementation of `floor`.<|endoftext|>
9dde6e4f0ae2b83f3a62db61add120440651079cbd2b3a6c22620ac2d826f74e
def trunc(x): 'Implementation of `trunc`.' return x.__trunc__()
Implementation of `trunc`.
mindspore/_extends/parse/standard_method.py
trunc
ezphlow/mindspore
1
python
def trunc(x): return x.__trunc__()
def trunc(x): return x.__trunc__()<|docstring|>Implementation of `trunc`.<|endoftext|>
26a7aca06d23c5ba5dd05023f03e6151820b6503af1a9981831331e52648fb03
def uadd(x): 'Implementation of `uadd`.' return x.__pos__()
Implementation of `uadd`.
mindspore/_extends/parse/standard_method.py
uadd
ezphlow/mindspore
1
python
def uadd(x): return x.__pos__()
def uadd(x): return x.__pos__()<|docstring|>Implementation of `uadd`.<|endoftext|>
5b57ac64ce73b1d7e115b7ffbd2acaa17db7e2bca1f87e32a628baeba6e9721c
def usub(x): 'Implementation of `usub`.' return x.__neg__()
Implementation of `usub`.
mindspore/_extends/parse/standard_method.py
usub
ezphlow/mindspore
1
python
def usub(x): return x.__neg__()
def usub(x): return x.__neg__()<|docstring|>Implementation of `usub`.<|endoftext|>
6638c5ce21980beb8f0ac998840de90dad9a7d65dfa6a7bec7867410cf85dbd4
def scalar_truediv(x, y): 'Implementation of `scalar_truediv`.' return x.__truediv__(y)
Implementation of `scalar_truediv`.
mindspore/_extends/parse/standard_method.py
scalar_truediv
ezphlow/mindspore
1
python
def scalar_truediv(x, y): return x.__truediv__(y)
def scalar_truediv(x, y): return x.__truediv__(y)<|docstring|>Implementation of `scalar_truediv`.<|endoftext|>
63bf6827fb185d62ebae939e02104c24e20aafac323bc30fc760b96b90afcd28
def scalar_floordiv(x, y): 'Implementation of `scalar_floordiv`.' return x.__floordiv__(y)
Implementation of `scalar_floordiv`.
mindspore/_extends/parse/standard_method.py
scalar_floordiv
ezphlow/mindspore
1
python
def scalar_floordiv(x, y): return x.__floordiv__(y)
def scalar_floordiv(x, y): return x.__floordiv__(y)<|docstring|>Implementation of `scalar_floordiv`.<|endoftext|>
3f0cbcbe4028b564623d068b2636e206cc12240e46c7de6ae936c71f3d20a878
def bool_(x): 'Implementation of `bool`.' return x.__bool__()
Implementation of `bool`.
mindspore/_extends/parse/standard_method.py
bool_
ezphlow/mindspore
1
python
def bool_(x): return x.__bool__()
def bool_(x): return x.__bool__()<|docstring|>Implementation of `bool`.<|endoftext|>
6b93eb7b1a6d2fd01db4863b10dac89ceb50693ba551af9ffb82324b88e7b980
def while_cond(x): 'For while condtion, if the condition is a tensor, the loop will not be unrolled' if F.issubclass_(F.typeof(x), F.typeof(mstype.tensor)): is_cond = check_is_tensor_bool_cond(F.shape(x)) if is_cond: return F.cast(x, mstype.bool_) return x
For while condtion, if the condition is a tensor, the loop will not be unrolled
mindspore/_extends/parse/standard_method.py
while_cond
ezphlow/mindspore
1
python
def while_cond(x): if F.issubclass_(F.typeof(x), F.typeof(mstype.tensor)): is_cond = check_is_tensor_bool_cond(F.shape(x)) if is_cond: return F.cast(x, mstype.bool_) return x
def while_cond(x): if F.issubclass_(F.typeof(x), F.typeof(mstype.tensor)): is_cond = check_is_tensor_bool_cond(F.shape(x)) if is_cond: return F.cast(x, mstype.bool_) return x<|docstring|>For while condtion, if the condition is a tensor, the loop will not be unrolled<|endoftext|>
86b0ffff152f467ed0053cacc98c488e43d8566b4bcab4afa36f0c882278f48f
@constexpr def check_is_tensor_bool_cond(shp): 'check if tensor is a bool condition' if (shp in ((), (1,))): return True raise ValueError('tensor as bool condition, its shape should be () or (1,), but got ', shp)
check if tensor is a bool condition
mindspore/_extends/parse/standard_method.py
check_is_tensor_bool_cond
ezphlow/mindspore
1
python
@constexpr def check_is_tensor_bool_cond(shp): if (shp in ((), (1,))): return True raise ValueError('tensor as bool condition, its shape should be () or (1,), but got ', shp)
@constexpr def check_is_tensor_bool_cond(shp): if (shp in ((), (1,))): return True raise ValueError('tensor as bool condition, its shape should be () or (1,), but got ', shp)<|docstring|>check if tensor is a bool condition<|endoftext|>
f555eb328aa2ff87ddc6c6e4e137617fec4701fe27858d8a14dd40c2b54f9e62
@constexpr def const_tensor_to_bool(x): 'convert bool tensor to bool condition' if (x is None): raise ValueError('Only constant tensor bool can be converted to bool') x = x.asnumpy() if (x.shape not in ((), (1,))): raise ValueError('Tensor to bool should input shape () or (1), but got ', x.shape) if (x.shape == ()): value = bool(x) else: value = bool(x[0]) return value
convert bool tensor to bool condition
mindspore/_extends/parse/standard_method.py
const_tensor_to_bool
ezphlow/mindspore
1
python
@constexpr def const_tensor_to_bool(x): if (x is None): raise ValueError('Only constant tensor bool can be converted to bool') x = x.asnumpy() if (x.shape not in ((), (1,))): raise ValueError('Tensor to bool should input shape () or (1), but got ', x.shape) if (x.shape == ()): value = bool(x) else: value = bool(x[0]) return value
@constexpr def const_tensor_to_bool(x): if (x is None): raise ValueError('Only constant tensor bool can be converted to bool') x = x.asnumpy() if (x.shape not in ((), (1,))): raise ValueError('Tensor to bool should input shape () or (1), but got ', x.shape) if (x.shape == ()): value = bool(x) else: value = bool(x[0]) return value<|docstring|>convert bool tensor to bool condition<|endoftext|>
34c8a29e02bd3647be56183c8975ab4d7344a8c1e6185397bf673b5b4eb4fe83
def tensor_bool(x): 'tensor as conditon, if is constant, return immediate bool value' is_cond = check_is_tensor_bool_cond(F.shape(x)) if (is_cond and F.isconstant(x)): return const_tensor_to_bool(x) return F.cast(x, mstype.bool_)
tensor as conditon, if is constant, return immediate bool value
mindspore/_extends/parse/standard_method.py
tensor_bool
ezphlow/mindspore
1
python
def tensor_bool(x): is_cond = check_is_tensor_bool_cond(F.shape(x)) if (is_cond and F.isconstant(x)): return const_tensor_to_bool(x) return F.cast(x, mstype.bool_)
def tensor_bool(x): is_cond = check_is_tensor_bool_cond(F.shape(x)) if (is_cond and F.isconstant(x)): return const_tensor_to_bool(x) return F.cast(x, mstype.bool_)<|docstring|>tensor as conditon, if is constant, return immediate bool value<|endoftext|>
d58091814810e52fe269581963b50b5d38d54bf27c75a1e43c6d634942ea8605
def and_(x, y): 'Implementation of `and` (`&`).' return x.__and__(y)
Implementation of `and` (`&`).
mindspore/_extends/parse/standard_method.py
and_
ezphlow/mindspore
1
python
def and_(x, y): return x.__and__(y)
def and_(x, y): return x.__and__(y)<|docstring|>Implementation of `and` (`&`).<|endoftext|>
0f11189540419d50b9d94fcacea2a6ab7d66795189462ce8a732a4a26150d996
def or_(x, y): 'Implementation of `or` (`|`).' return x.__or__(y)
Implementation of `or` (`|`).
mindspore/_extends/parse/standard_method.py
or_
ezphlow/mindspore
1
python
def or_(x, y): return x.__or__(y)
def or_(x, y): return x.__or__(y)<|docstring|>Implementation of `or` (`|`).<|endoftext|>
44183c7c6d8f8cef9a7acd1191f7ab8993fd9625b7c1ed48f744fb7a0d836f57
def matmul(x, y): 'Implementation of `matmul` (`@`).' return x.__matmul__(y)
Implementation of `matmul` (`@`).
mindspore/_extends/parse/standard_method.py
matmul
ezphlow/mindspore
1
python
def matmul(x, y): return x.__matmul__(y)
def matmul(x, y): return x.__matmul__(y)<|docstring|>Implementation of `matmul` (`@`).<|endoftext|>
8b3513220543c311d943ab1abc5d29579c3cf61e185e3ed021144a9243707029
def float_bool(x): 'Implementation of `float_bool`.' return (x != 0.0)
Implementation of `float_bool`.
mindspore/_extends/parse/standard_method.py
float_bool
ezphlow/mindspore
1
python
def float_bool(x): return (x != 0.0)
def float_bool(x): return (x != 0.0)<|docstring|>Implementation of `float_bool`.<|endoftext|>
d6b5c20d1b82368f9a67234b73c79a2e549ecadb0d0a88ebde57ddf81656b067
def int_bool(x): 'Implementation of `int_bool`.' return (x != 0)
Implementation of `int_bool`.
mindspore/_extends/parse/standard_method.py
int_bool
ezphlow/mindspore
1
python
def int_bool(x): return (x != 0)
def int_bool(x): return (x != 0)<|docstring|>Implementation of `int_bool`.<|endoftext|>
139418c091fcd7e746b838fae10d19da992f82168b0c968d7e09f0672420ed3c
def str_bool(x): 'Implementation of `str_bool`.' if (x == ''): return False return True
Implementation of `str_bool`.
mindspore/_extends/parse/standard_method.py
str_bool
ezphlow/mindspore
1
python
def str_bool(x): if (x == ): return False return True
def str_bool(x): if (x == ): return False return True<|docstring|>Implementation of `str_bool`.<|endoftext|>
c20fc6b3be7b790f0e6b70dd7c629119eaf6d19ae9850bfab1b2192b577e6776
def list_bool(x): 'Implementation of `tuple_bool`.' return (len(x) != 0)
Implementation of `tuple_bool`.
mindspore/_extends/parse/standard_method.py
list_bool
ezphlow/mindspore
1
python
def list_bool(x): return (len(x) != 0)
def list_bool(x): return (len(x) != 0)<|docstring|>Implementation of `tuple_bool`.<|endoftext|>
0aafcb18aa9fffd84cdee9153e5b329d56132c7ab3bb6a080b43dc9cc9c2f5e1
def tuple_bool(x): 'Implementation of `tuple_bool`.' return (len(x) != 0)
Implementation of `tuple_bool`.
mindspore/_extends/parse/standard_method.py
tuple_bool
ezphlow/mindspore
1
python
def tuple_bool(x): return (len(x) != 0)
def tuple_bool(x): return (len(x) != 0)<|docstring|>Implementation of `tuple_bool`.<|endoftext|>
c613bcebfdb74e2d0e1f2b374a946a1be61b530b7332f7a07b11d714b0b1d799
def dict_bool(x): 'Implementation of `dict_bool`.' return (len(x) != 0)
Implementation of `dict_bool`.
mindspore/_extends/parse/standard_method.py
dict_bool
ezphlow/mindspore
1
python
def dict_bool(x): return (len(x) != 0)
def dict_bool(x): return (len(x) != 0)<|docstring|>Implementation of `dict_bool`.<|endoftext|>
a9839405165c1b57a972493932f463f3eabd99e1c32b106c6a3f0816960e1243
def none_bool(x): 'Implementation of `none_bool`.' return False
Implementation of `none_bool`.
mindspore/_extends/parse/standard_method.py
none_bool
ezphlow/mindspore
1
python
def none_bool(x): return False
def none_bool(x): return False<|docstring|>Implementation of `none_bool`.<|endoftext|>
0cb7ba399b5984e907918007130e64b852fa0db63a54055729f21c8c30d20074
def float_floordiv(x, y): 'Implementation of `float_floordiv`.' return floor((x / y))
Implementation of `float_floordiv`.
mindspore/_extends/parse/standard_method.py
float_floordiv
ezphlow/mindspore
1
python
def float_floordiv(x, y): return floor((x / y))
def float_floordiv(x, y): return floor((x / y))<|docstring|>Implementation of `float_floordiv`.<|endoftext|>
7242fe70a7623d2395b6280a013da0de6b773e33ff219a9c58fb27e53105f401
def list_iter(xs): 'Iterator for List.' return SequenceIterator(0, xs)
Iterator for List.
mindspore/_extends/parse/standard_method.py
list_iter
ezphlow/mindspore
1
python
def list_iter(xs): return SequenceIterator(0, xs)
def list_iter(xs): return SequenceIterator(0, xs)<|docstring|>Iterator for List.<|endoftext|>
712a975898a6ef7efd640595c4823f14788f7eea72e669aefe4c74d9048bbba7
def array_iter(xs): 'Iterator for Array.' return SequenceIterator(0, xs)
Iterator for Array.
mindspore/_extends/parse/standard_method.py
array_iter
ezphlow/mindspore
1
python
def array_iter(xs): return SequenceIterator(0, xs)
def array_iter(xs): return SequenceIterator(0, xs)<|docstring|>Iterator for Array.<|endoftext|>
8093b2ce48711282474d354428c53f7d1422cb248d3bac5952fee1366ea55348
def tuple_next(xs): 'Next tuple.' return (xs[0], tail(xs))
Next tuple.
mindspore/_extends/parse/standard_method.py
tuple_next
ezphlow/mindspore
1
python
def tuple_next(xs): return (xs[0], tail(xs))
def tuple_next(xs): return (xs[0], tail(xs))<|docstring|>Next tuple.<|endoftext|>
6c2e67b23b593f4ecdd55eb38531b04aceefe25e659108a5f7d773c03c9621d6
def tuple_hasnext(xs): 'Whether the tuple is empty or not.' return (len(xs) > 0)
Whether the tuple is empty or not.
mindspore/_extends/parse/standard_method.py
tuple_hasnext
ezphlow/mindspore
1
python
def tuple_hasnext(xs): return (len(xs) > 0)
def tuple_hasnext(xs): return (len(xs) > 0)<|docstring|>Whether the tuple is empty or not.<|endoftext|>
f06a409fa4c1d044cd1cd7742292c89b1f69ff8885a2eb738b7ce62aa6180b7e
def list_next(xs): 'Next list.' return (xs[0], tail(xs))
Next list.
mindspore/_extends/parse/standard_method.py
list_next
ezphlow/mindspore
1
python
def list_next(xs): return (xs[0], tail(xs))
def list_next(xs): return (xs[0], tail(xs))<|docstring|>Next list.<|endoftext|>
0fb7311d470d9f05cba411f8d6527ff63bcaaab39c8b31c23401864c90f7da6d
def list_hasnext(xs): 'Whether the list is empty or not.' return (len(xs) > 0)
Whether the list is empty or not.
mindspore/_extends/parse/standard_method.py
list_hasnext
ezphlow/mindspore
1
python
def list_hasnext(xs): return (len(xs) > 0)
def list_hasnext(xs): return (len(xs) > 0)<|docstring|>Whether the list is empty or not.<|endoftext|>
d694340783990d63805294494599ab6bbee92cd054658331e4edda9dacb6d59f
def to_array(x): 'Implementation of `to_array`.' return x.__ms_to_array__()
Implementation of `to_array`.
mindspore/_extends/parse/standard_method.py
to_array
ezphlow/mindspore
1
python
def to_array(x): return x.__ms_to_array__()
def to_array(x): return x.__ms_to_array__()<|docstring|>Implementation of `to_array`.<|endoftext|>
e15b0152d0be2828d480e91d176ed6da0d7276189bf2e3a4bb4a44041c102825
@core(ignore_values=True) def __ms_hasnext__(self): 'Whether the index is past the length of the sequence.' return (self.idx < ms_len(self.seq))
Whether the index is past the length of the sequence.
mindspore/_extends/parse/standard_method.py
__ms_hasnext__
ezphlow/mindspore
1
python
@core(ignore_values=True) def __ms_hasnext__(self): return (self.idx < ms_len(self.seq))
@core(ignore_values=True) def __ms_hasnext__(self): return (self.idx < ms_len(self.seq))<|docstring|>Whether the index is past the length of the sequence.<|endoftext|>
0d8f15eb64860277d15de990d113b396cc14186bbdb0af4fff261833bbcb2bc1
@core(ignore_values=True) def __ms_next__(self): 'Return the next element and a new iterator.' return (self.seq[self.idx], SequenceIterator((self.idx + 1), self.seq))
Return the next element and a new iterator.
mindspore/_extends/parse/standard_method.py
__ms_next__
ezphlow/mindspore
1
python
@core(ignore_values=True) def __ms_next__(self): return (self.seq[self.idx], SequenceIterator((self.idx + 1), self.seq))
@core(ignore_values=True) def __ms_next__(self): return (self.seq[self.idx], SequenceIterator((self.idx + 1), self.seq))<|docstring|>Return the next element and a new iterator.<|endoftext|>
ca769e478eac20f023d7cae23d65f757444e21cd154e30ad85722bdcdc809fa6
@classmethod @abstractmethod def from_uri(cls, uri: str) -> BaseBrokerURI: '\n Return a instance created from a URI\n '
Return a instance created from a URI
eventbusk/brokers/base.py
from_uri
Airbase/eventbusk
0
python
@classmethod @abstractmethod def from_uri(cls, uri: str) -> BaseBrokerURI: '\n \n '
@classmethod @abstractmethod def from_uri(cls, uri: str) -> BaseBrokerURI: '\n \n '<|docstring|>Return a instance created from a URI<|endoftext|>
6ac2409c422f43bb155f61c81ff303784013692cbc286c2fd05cc1b6399402c8
@abstractmethod def poll(self, timeout: int) -> Optional[MessageT]: '\n Poll for a specified time in seconds for new messages\n '
Poll for a specified time in seconds for new messages
eventbusk/brokers/base.py
poll
Airbase/eventbusk
0
python
@abstractmethod def poll(self, timeout: int) -> Optional[MessageT]: '\n \n '
@abstractmethod def poll(self, timeout: int) -> Optional[MessageT]: '\n \n '<|docstring|>Poll for a specified time in seconds for new messages<|endoftext|>
937f69593e6273074ea5a5fbae5d710159a09c40e1f4c7e60d93132c958c2e7e
@abstractmethod def ack(self, message: str) -> None: '\n Acknowledge successful consumption of a message.\n '
Acknowledge successful consumption of a message.
eventbusk/brokers/base.py
ack
Airbase/eventbusk
0
python
@abstractmethod def ack(self, message: str) -> None: '\n \n '
@abstractmethod def ack(self, message: str) -> None: '\n \n '<|docstring|>Acknowledge successful consumption of a message.<|endoftext|>
e84a97b523d64abce8e26dfa2942927bab34e466f248f78065ff34c4bbe2e5fc
@abstractmethod def produce(self, topic: str, value: MessageT, flush: bool=True, on_delivery: DeliveryCallBackT=None, fail_silently: bool=False) -> None: '\n Send a message on the specific topic.\n\n Arguments\n ----------\n topic:\n The name of the topic\n value:\n Serialized message to send.\n on_delivery:\n Callback function on delivery of a message.\n flush:\n Flush any pending messages after every send.\n Useful for brokers like Kafka which do batches.\n fail_silently:\n If True, ignore all delivery errors.\n '
Send a message on the specific topic. Arguments ---------- topic: The name of the topic value: Serialized message to send. on_delivery: Callback function on delivery of a message. flush: Flush any pending messages after every send. Useful for brokers like Kafka which do batches. fail_silently: If True, ignore all delivery errors.
eventbusk/brokers/base.py
produce
Airbase/eventbusk
0
python
@abstractmethod def produce(self, topic: str, value: MessageT, flush: bool=True, on_delivery: DeliveryCallBackT=None, fail_silently: bool=False) -> None: '\n Send a message on the specific topic.\n\n Arguments\n ----------\n topic:\n The name of the topic\n value:\n Serialized message to send.\n on_delivery:\n Callback function on delivery of a message.\n flush:\n Flush any pending messages after every send.\n Useful for brokers like Kafka which do batches.\n fail_silently:\n If True, ignore all delivery errors.\n '
@abstractmethod def produce(self, topic: str, value: MessageT, flush: bool=True, on_delivery: DeliveryCallBackT=None, fail_silently: bool=False) -> None: '\n Send a message on the specific topic.\n\n Arguments\n ----------\n topic:\n The name of the topic\n value:\n Serialized message to send.\n on_delivery:\n Callback function on delivery of a message.\n flush:\n Flush any pending messages after every send.\n Useful for brokers like Kafka which do batches.\n fail_silently:\n If True, ignore all delivery errors.\n '<|docstring|>Send a message on the specific topic. Arguments ---------- topic: The name of the topic value: Serialized message to send. on_delivery: Callback function on delivery of a message. flush: Flush any pending messages after every send. Useful for brokers like Kafka which do batches. fail_silently: If True, ignore all delivery errors.<|endoftext|>
cabfed13d5b0babff836f048d40704693a1ddc95facb50ab4886a16c2b2679bd
def format_description(description): '\n Get rid of empty lines and unindent multiline text until\n the leftmost indented line has no whitespaces on the left.\n\n In:\n\n (assume dots represent whitespace)\n\n ....Hello world\n ......Foo bar\n <EMPTY-LINE>\n ....1 2 3 4\n\n Out:\n\n Hello World\n ..Foo bar\n 1 2 3 4\n ' lines = [line for line in description.split(os.linesep) if line.strip()] matches = [_DESCRIPTION_CUTOFF_REGEX.match(line) for line in lines] if matches: min_offset = min(((match.end() if (match is not None) else 0) for match in matches)) return os.linesep.join([line[min_offset:] for line in lines]) return ''
Get rid of empty lines and unindent multiline text until the leftmost indented line has no whitespaces on the left. In: (assume dots represent whitespace) ....Hello world ......Foo bar <EMPTY-LINE> ....1 2 3 4 Out: Hello World ..Foo bar 1 2 3 4
testplan/common/utils/strings.py
format_description
kelliott55/testplan
0
python
def format_description(description): '\n Get rid of empty lines and unindent multiline text until\n the leftmost indented line has no whitespaces on the left.\n\n In:\n\n (assume dots represent whitespace)\n\n ....Hello world\n ......Foo bar\n <EMPTY-LINE>\n ....1 2 3 4\n\n Out:\n\n Hello World\n ..Foo bar\n 1 2 3 4\n ' lines = [line for line in description.split(os.linesep) if line.strip()] matches = [_DESCRIPTION_CUTOFF_REGEX.match(line) for line in lines] if matches: min_offset = min(((match.end() if (match is not None) else 0) for match in matches)) return os.linesep.join([line[min_offset:] for line in lines]) return
def format_description(description): '\n Get rid of empty lines and unindent multiline text until\n the leftmost indented line has no whitespaces on the left.\n\n In:\n\n (assume dots represent whitespace)\n\n ....Hello world\n ......Foo bar\n <EMPTY-LINE>\n ....1 2 3 4\n\n Out:\n\n Hello World\n ..Foo bar\n 1 2 3 4\n ' lines = [line for line in description.split(os.linesep) if line.strip()] matches = [_DESCRIPTION_CUTOFF_REGEX.match(line) for line in lines] if matches: min_offset = min(((match.end() if (match is not None) else 0) for match in matches)) return os.linesep.join([line[min_offset:] for line in lines]) return <|docstring|>Get rid of empty lines and unindent multiline text until the leftmost indented line has no whitespaces on the left. In: (assume dots represent whitespace) ....Hello world ......Foo bar <EMPTY-LINE> ....1 2 3 4 Out: Hello World ..Foo bar 1 2 3 4<|endoftext|>
04d9b28a2c1c9ddafe78d4021f2d352084c7677d84872f88b2cb23e35c896618
def slugify(value): '\n Normalizes string, converts to lowercase, removes non-alpha characters,\n and converts spaces to hyphens.\n\n :param value: string value to slugify\n :type value: ``str``\n\n :return: slugified string value, suitable as a directory or filename\n :rtype: ``str``\n ' if (sys.hexversion >= 50529264): value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = re.sub(b'[^\\w\\s-]', b'', value).strip().lower() return re.sub(b'[-\\s]+', b'-', value).decode('ascii') else: value = unicodedata.normalize('NFKD', six.text_type(value)).encode('ascii', 'ignore') value = six.text_type(re.sub('[^\\w\\s-]', '', value).strip().lower()) return str(re.sub('[-\\s]+', '-', value))
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. :param value: string value to slugify :type value: ``str`` :return: slugified string value, suitable as a directory or filename :rtype: ``str``
testplan/common/utils/strings.py
slugify
kelliott55/testplan
0
python
def slugify(value): '\n Normalizes string, converts to lowercase, removes non-alpha characters,\n and converts spaces to hyphens.\n\n :param value: string value to slugify\n :type value: ``str``\n\n :return: slugified string value, suitable as a directory or filename\n :rtype: ``str``\n ' if (sys.hexversion >= 50529264): value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = re.sub(b'[^\\w\\s-]', b, value).strip().lower() return re.sub(b'[-\\s]+', b'-', value).decode('ascii') else: value = unicodedata.normalize('NFKD', six.text_type(value)).encode('ascii', 'ignore') value = six.text_type(re.sub('[^\\w\\s-]', , value).strip().lower()) return str(re.sub('[-\\s]+', '-', value))
def slugify(value): '\n Normalizes string, converts to lowercase, removes non-alpha characters,\n and converts spaces to hyphens.\n\n :param value: string value to slugify\n :type value: ``str``\n\n :return: slugified string value, suitable as a directory or filename\n :rtype: ``str``\n ' if (sys.hexversion >= 50529264): value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = re.sub(b'[^\\w\\s-]', b, value).strip().lower() return re.sub(b'[-\\s]+', b'-', value).decode('ascii') else: value = unicodedata.normalize('NFKD', six.text_type(value)).encode('ascii', 'ignore') value = six.text_type(re.sub('[^\\w\\s-]', , value).strip().lower()) return str(re.sub('[-\\s]+', '-', value))<|docstring|>Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. :param value: string value to slugify :type value: ``str`` :return: slugified string value, suitable as a directory or filename :rtype: ``str``<|endoftext|>
913e77d0473e4632550acff6b69ff95ab0690a52cc74bc62fc3ad7c384711bbf
def uuid4(): '\n Generate a globally unique id.\n\n :return: A string complied with `uuid.uuid4` format\n :rtype: ``str``\n ' return str(uuid.uuid4())
Generate a globally unique id. :return: A string complied with `uuid.uuid4` format :rtype: ``str``
testplan/common/utils/strings.py
uuid4
kelliott55/testplan
0
python
def uuid4(): '\n Generate a globally unique id.\n\n :return: A string complied with `uuid.uuid4` format\n :rtype: ``str``\n ' return str(uuid.uuid4())
def uuid4(): '\n Generate a globally unique id.\n\n :return: A string complied with `uuid.uuid4` format\n :rtype: ``str``\n ' return str(uuid.uuid4())<|docstring|>Generate a globally unique id. :return: A string complied with `uuid.uuid4` format :rtype: ``str``<|endoftext|>
f9d0153b1a2dfac72cae855afac3ba6345f1b48d672fb6bf6e7294fb1fdcab2d
def wrap(text, width=150): '\n Wraps `text` within given `width` limit, keeping initial indentation of\n each line (and generated lines). Useful for wrapping exception messages.\n\n :param text: Text to be wrapped.\n :param width: Maximum character limit for each line.\n :return: Wrapped text\n ' wrapper = textwrap.TextWrapper(width=width, replace_whitespace=False) text_ctx = [wrapper.wrap(t) for t in text.splitlines()] result = [] for line_list in text_ctx: if (not line_list): return text (first, rest) = (line_list[0], line_list[1:]) indent_match = INDENT_REGEX.match(first) if indent_match: prefix = (' ' * (indent_match.end() - indent_match.start())) result.extend(([first] + ['{}{}'.format(prefix, line) for line in rest])) else: result.extend(line_list) return os.linesep.join(result)
Wraps `text` within given `width` limit, keeping initial indentation of each line (and generated lines). Useful for wrapping exception messages. :param text: Text to be wrapped. :param width: Maximum character limit for each line. :return: Wrapped text
testplan/common/utils/strings.py
wrap
kelliott55/testplan
0
python
def wrap(text, width=150): '\n Wraps `text` within given `width` limit, keeping initial indentation of\n each line (and generated lines). Useful for wrapping exception messages.\n\n :param text: Text to be wrapped.\n :param width: Maximum character limit for each line.\n :return: Wrapped text\n ' wrapper = textwrap.TextWrapper(width=width, replace_whitespace=False) text_ctx = [wrapper.wrap(t) for t in text.splitlines()] result = [] for line_list in text_ctx: if (not line_list): return text (first, rest) = (line_list[0], line_list[1:]) indent_match = INDENT_REGEX.match(first) if indent_match: prefix = (' ' * (indent_match.end() - indent_match.start())) result.extend(([first] + ['{}{}'.format(prefix, line) for line in rest])) else: result.extend(line_list) return os.linesep.join(result)
def wrap(text, width=150): '\n Wraps `text` within given `width` limit, keeping initial indentation of\n each line (and generated lines). Useful for wrapping exception messages.\n\n :param text: Text to be wrapped.\n :param width: Maximum character limit for each line.\n :return: Wrapped text\n ' wrapper = textwrap.TextWrapper(width=width, replace_whitespace=False) text_ctx = [wrapper.wrap(t) for t in text.splitlines()] result = [] for line_list in text_ctx: if (not line_list): return text (first, rest) = (line_list[0], line_list[1:]) indent_match = INDENT_REGEX.match(first) if indent_match: prefix = (' ' * (indent_match.end() - indent_match.start())) result.extend(([first] + ['{}{}'.format(prefix, line) for line in rest])) else: result.extend(line_list) return os.linesep.join(result)<|docstring|>Wraps `text` within given `width` limit, keeping initial indentation of each line (and generated lines). Useful for wrapping exception messages. :param text: Text to be wrapped. :param width: Maximum character limit for each line. :return: Wrapped text<|endoftext|>
f431ed8b4210ba2b27e315fecc8212c481c5956e725d70451987ac22bab85ddc
def split_line(line, max_width, get_width_func=None): '\n Split `line` into multi-lines if width exceeds `max_width`.\n\n :param line: Line to be split.\n :param max_width: Maximum length of each line (unit: px).\n :param get_width_func: A function which computes width of string\n according to font and font size.\n :return: list of lines\n ' result = [] total_width = 0 tmp_str = '' get_text_width = (get_width_func if get_width_func else (lambda text: stringWidth(text, 'Helvetica', 9))) for ch in line: char_width = get_text_width(ch) if (((total_width + char_width) <= max_width) or (not tmp_str)): tmp_str += ch total_width += char_width else: result.append(tmp_str) tmp_str = ch total_width = char_width if tmp_str: result.append(tmp_str) return result
Split `line` into multi-lines if width exceeds `max_width`. :param line: Line to be split. :param max_width: Maximum length of each line (unit: px). :param get_width_func: A function which computes width of string according to font and font size. :return: list of lines
testplan/common/utils/strings.py
split_line
kelliott55/testplan
0
python
def split_line(line, max_width, get_width_func=None): '\n Split `line` into multi-lines if width exceeds `max_width`.\n\n :param line: Line to be split.\n :param max_width: Maximum length of each line (unit: px).\n :param get_width_func: A function which computes width of string\n according to font and font size.\n :return: list of lines\n ' result = [] total_width = 0 tmp_str = get_text_width = (get_width_func if get_width_func else (lambda text: stringWidth(text, 'Helvetica', 9))) for ch in line: char_width = get_text_width(ch) if (((total_width + char_width) <= max_width) or (not tmp_str)): tmp_str += ch total_width += char_width else: result.append(tmp_str) tmp_str = ch total_width = char_width if tmp_str: result.append(tmp_str) return result
def split_line(line, max_width, get_width_func=None): '\n Split `line` into multi-lines if width exceeds `max_width`.\n\n :param line: Line to be split.\n :param max_width: Maximum length of each line (unit: px).\n :param get_width_func: A function which computes width of string\n according to font and font size.\n :return: list of lines\n ' result = [] total_width = 0 tmp_str = get_text_width = (get_width_func if get_width_func else (lambda text: stringWidth(text, 'Helvetica', 9))) for ch in line: char_width = get_text_width(ch) if (((total_width + char_width) <= max_width) or (not tmp_str)): tmp_str += ch total_width += char_width else: result.append(tmp_str) tmp_str = ch total_width = char_width if tmp_str: result.append(tmp_str) return result<|docstring|>Split `line` into multi-lines if width exceeds `max_width`. :param line: Line to be split. :param max_width: Maximum length of each line (unit: px). :param get_width_func: A function which computes width of string according to font and font size. :return: list of lines<|endoftext|>
04923da2b1b8001a50956b3fd31858da4417f8223ae07635a6527bd91b4a0110
def split_text(text, font_name, font_size, max_width, keep_leading_whitespace=False): '\n Wraps `text` within given `max_width` limit (measured in px), keeping\n initial indentation of each line (and generated lines) if\n `keep_leading_whitespace` is True.\n\n :param text: Text to be split.\n :param font_name: Font name.\n :param font_size: Font size.\n :param max_width: Maximum length of each line (unit: px).\n :param keep_leading_whitespace: each split line keeps the leading\n whitespace.\n :return: list of lines\n ' def get_text_width(text, name=font_name, size=font_size): return stringWidth(text, name, size) result = [] lines = [line for line in re.split('[\\r\\n]+', text) if line] for line in lines: line_list = split_line(line, max_width, get_text_width) if (keep_leading_whitespace and (len(line_list) > 1)): (first, rest) = (line_list[0], line_list[1:]) indent_match = _DESCRIPTION_CUTOFF_REGEX.match(first) if indent_match: prefix = first[indent_match.start():indent_match.end()] line_list = ([first] + ['{}{}'.format(prefix, s) for s in rest]) result.extend(line_list) return os.linesep.join(result)
Wraps `text` within given `max_width` limit (measured in px), keeping initial indentation of each line (and generated lines) if `keep_leading_whitespace` is True. :param text: Text to be split. :param font_name: Font name. :param font_size: Font size. :param max_width: Maximum length of each line (unit: px). :param keep_leading_whitespace: each split line keeps the leading whitespace. :return: list of lines
testplan/common/utils/strings.py
split_text
kelliott55/testplan
0
python
def split_text(text, font_name, font_size, max_width, keep_leading_whitespace=False): '\n Wraps `text` within given `max_width` limit (measured in px), keeping\n initial indentation of each line (and generated lines) if\n `keep_leading_whitespace` is True.\n\n :param text: Text to be split.\n :param font_name: Font name.\n :param font_size: Font size.\n :param max_width: Maximum length of each line (unit: px).\n :param keep_leading_whitespace: each split line keeps the leading\n whitespace.\n :return: list of lines\n ' def get_text_width(text, name=font_name, size=font_size): return stringWidth(text, name, size) result = [] lines = [line for line in re.split('[\\r\\n]+', text) if line] for line in lines: line_list = split_line(line, max_width, get_text_width) if (keep_leading_whitespace and (len(line_list) > 1)): (first, rest) = (line_list[0], line_list[1:]) indent_match = _DESCRIPTION_CUTOFF_REGEX.match(first) if indent_match: prefix = first[indent_match.start():indent_match.end()] line_list = ([first] + ['{}{}'.format(prefix, s) for s in rest]) result.extend(line_list) return os.linesep.join(result)
def split_text(text, font_name, font_size, max_width, keep_leading_whitespace=False): '\n Wraps `text` within given `max_width` limit (measured in px), keeping\n initial indentation of each line (and generated lines) if\n `keep_leading_whitespace` is True.\n\n :param text: Text to be split.\n :param font_name: Font name.\n :param font_size: Font size.\n :param max_width: Maximum length of each line (unit: px).\n :param keep_leading_whitespace: each split line keeps the leading\n whitespace.\n :return: list of lines\n ' def get_text_width(text, name=font_name, size=font_size): return stringWidth(text, name, size) result = [] lines = [line for line in re.split('[\\r\\n]+', text) if line] for line in lines: line_list = split_line(line, max_width, get_text_width) if (keep_leading_whitespace and (len(line_list) > 1)): (first, rest) = (line_list[0], line_list[1:]) indent_match = _DESCRIPTION_CUTOFF_REGEX.match(first) if indent_match: prefix = first[indent_match.start():indent_match.end()] line_list = ([first] + ['{}{}'.format(prefix, s) for s in rest]) result.extend(line_list) return os.linesep.join(result)<|docstring|>Wraps `text` within given `max_width` limit (measured in px), keeping initial indentation of each line (and generated lines) if `keep_leading_whitespace` is True. :param text: Text to be split. :param font_name: Font name. :param font_size: Font size. :param max_width: Maximum length of each line (unit: px). :param keep_leading_whitespace: each split line keeps the leading whitespace. :return: list of lines<|endoftext|>
e934b00719f059670463b68b7cfb4f10bd655e66934cffbcecbef4e09ed4c858
def indent(lines_str, indent_size=2): '\n Indent a multi-line string with a common indent.\n\n :param lines_str: Multi-line string.\n :type lines_str: ``str``\n :param indent_size: Number of spaces to indent by - defaults to 2.\n :type indent_size: ``int``\n :return: New string with extra indent.\n :rtype: ``str``\n ' indent = (' ' * indent_size) return '\n'.join(('{indent}{line}'.format(indent=indent, line=line) for line in lines_str.splitlines()))
Indent a multi-line string with a common indent. :param lines_str: Multi-line string. :type lines_str: ``str`` :param indent_size: Number of spaces to indent by - defaults to 2. :type indent_size: ``int`` :return: New string with extra indent. :rtype: ``str``
testplan/common/utils/strings.py
indent
kelliott55/testplan
0
python
def indent(lines_str, indent_size=2): '\n Indent a multi-line string with a common indent.\n\n :param lines_str: Multi-line string.\n :type lines_str: ``str``\n :param indent_size: Number of spaces to indent by - defaults to 2.\n :type indent_size: ``int``\n :return: New string with extra indent.\n :rtype: ``str``\n ' indent = (' ' * indent_size) return '\n'.join(('{indent}{line}'.format(indent=indent, line=line) for line in lines_str.splitlines()))
def indent(lines_str, indent_size=2): '\n Indent a multi-line string with a common indent.\n\n :param lines_str: Multi-line string.\n :type lines_str: ``str``\n :param indent_size: Number of spaces to indent by - defaults to 2.\n :type indent_size: ``int``\n :return: New string with extra indent.\n :rtype: ``str``\n ' indent = (' ' * indent_size) return '\n'.join(('{indent}{line}'.format(indent=indent, line=line) for line in lines_str.splitlines()))<|docstring|>Indent a multi-line string with a common indent. :param lines_str: Multi-line string. :type lines_str: ``str`` :param indent_size: Number of spaces to indent by - defaults to 2. :type indent_size: ``int`` :return: New string with extra indent. :rtype: ``str``<|endoftext|>
3e7c1d8c88cd99ccf2d017112837333ed004af6521dd2303772f70d0bdeea532
def get_docstring(obj): '\n Get object docstring without leading whitespace.\n :param obj: Object to be extracted docstring.\n :type obj: ``object``\n :return: Docstring of the object.\n :rtype: ``str`` or ``NoneType``\n ' if hasattr(obj, '__doc__'): if obj.__doc__: return inspect.cleandoc(obj.__doc__) return None
Get object docstring without leading whitespace. :param obj: Object to be extracted docstring. :type obj: ``object`` :return: Docstring of the object. :rtype: ``str`` or ``NoneType``
testplan/common/utils/strings.py
get_docstring
kelliott55/testplan
0
python
def get_docstring(obj): '\n Get object docstring without leading whitespace.\n :param obj: Object to be extracted docstring.\n :type obj: ``object``\n :return: Docstring of the object.\n :rtype: ``str`` or ``NoneType``\n ' if hasattr(obj, '__doc__'): if obj.__doc__: return inspect.cleandoc(obj.__doc__) return None
def get_docstring(obj): '\n Get object docstring without leading whitespace.\n :param obj: Object to be extracted docstring.\n :type obj: ``object``\n :return: Docstring of the object.\n :rtype: ``str`` or ``NoneType``\n ' if hasattr(obj, '__doc__'): if obj.__doc__: return inspect.cleandoc(obj.__doc__) return None<|docstring|>Get object docstring without leading whitespace. :param obj: Object to be extracted docstring. :type obj: ``object`` :return: Docstring of the object. :rtype: ``str`` or ``NoneType``<|endoftext|>
d02e86986b6bba9d755903f6ad0bad0cc1caa6425bba50a3d84dd150267ce779
def get_version(): '\n Get the version from version module without importing more than\n necessary.\n ' version_module_path = os.path.join(os.path.dirname(__file__), 'renamer', '_version.py') with open(version_module_path) as version_module: exec(version_module.read()) return locals()['__version__']
Get the version from version module without importing more than necessary.
setup.py
get_version
jonathanj/renamer
0
python
def get_version(): '\n Get the version from version module without importing more than\n necessary.\n ' version_module_path = os.path.join(os.path.dirname(__file__), 'renamer', '_version.py') with open(version_module_path) as version_module: exec(version_module.read()) return locals()['__version__']
def get_version(): '\n Get the version from version module without importing more than\n necessary.\n ' version_module_path = os.path.join(os.path.dirname(__file__), 'renamer', '_version.py') with open(version_module_path) as version_module: exec(version_module.read()) return locals()['__version__']<|docstring|>Get the version from version module without importing more than necessary.<|endoftext|>
f7fe9113f744b00b4eb0598b3507df5a3adc0cda3e40f9c2243f83de70726409
def cnn(self): 'CNN模型' with tf.device('/gpu:0'): embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim]) embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x) with tf.name_scope('cnn'): conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv') gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp') with tf.name_scope('score'): fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1') fc = tf.contrib.layers.dropout(fc, self.keep_prob) fc = tf.nn.relu(fc) self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2') self.softmax_tensor1 = tf.nn.softmax(self.logits) self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1) with tf.name_scope('optimize'): cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y) self.loss = tf.reduce_mean(cross_entropy) self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss) with tf.name_scope('accuracy'): correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls) self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
CNN模型
model/cnn_model.py
cnn
CarryChang/EasyUse_FastApi
9
python
def cnn(self): with tf.device('/gpu:0'): embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim]) embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x) with tf.name_scope('cnn'): conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv') gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp') with tf.name_scope('score'): fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1') fc = tf.contrib.layers.dropout(fc, self.keep_prob) fc = tf.nn.relu(fc) self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2') self.softmax_tensor1 = tf.nn.softmax(self.logits) self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1) with tf.name_scope('optimize'): cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y) self.loss = tf.reduce_mean(cross_entropy) self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss) with tf.name_scope('accuracy'): correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls) self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
def cnn(self): with tf.device('/gpu:0'): embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim]) embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x) with tf.name_scope('cnn'): conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv') gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp') with tf.name_scope('score'): fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1') fc = tf.contrib.layers.dropout(fc, self.keep_prob) fc = tf.nn.relu(fc) self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2') self.softmax_tensor1 = tf.nn.softmax(self.logits) self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1) with tf.name_scope('optimize'): cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.input_y) self.loss = tf.reduce_mean(cross_entropy) self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss) with tf.name_scope('accuracy'): correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls) self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))<|docstring|>CNN模型<|endoftext|>
7b9d129b4f8606f071656c12b27b126478c43de92ea1f2df621aa6f91c40f89f
def get_project_root() -> Path: 'Get project root path.' return Path(__file__).parent.parent
Get project root path.
Module_02/browsing.py
get_project_root
JJSerAnexinet/2021_python_selenium
0
python
def get_project_root() -> Path: return Path(__file__).parent.parent
def get_project_root() -> Path: return Path(__file__).parent.parent<|docstring|>Get project root path.<|endoftext|>
64fc5510879a74442ffe964248277f66de0370f005c51eedfedf11ef7e13ad5f
def get_chrome_path() -> Path: 'Get chrome driver path.' root = get_project_root() return root.joinpath('drivers', 'chromedriver')
Get chrome driver path.
Module_02/browsing.py
get_chrome_path
JJSerAnexinet/2021_python_selenium
0
python
def get_chrome_path() -> Path: root = get_project_root() return root.joinpath('drivers', 'chromedriver')
def get_chrome_path() -> Path: root = get_project_root() return root.joinpath('drivers', 'chromedriver')<|docstring|>Get chrome driver path.<|endoftext|>
f15b3400007e2531dd468952432d11bd2171528d9ef4c560287d58aa286b58c7
def get_firefox_path() -> Path: 'Get Firefox driver path.' root = get_project_root() return root.joinpath('drivers', 'geckodriver')
Get Firefox driver path.
Module_02/browsing.py
get_firefox_path
JJSerAnexinet/2021_python_selenium
0
python
def get_firefox_path() -> Path: root = get_project_root() return root.joinpath('drivers', 'geckodriver')
def get_firefox_path() -> Path: root = get_project_root() return root.joinpath('drivers', 'geckodriver')<|docstring|>Get Firefox driver path.<|endoftext|>
f8d3eb252a3fc0e69215e3537f59f5e385098154732cfd8d1b3dfe8cbbd86e6d
def print_page_details(driver: webdriver.Remote): 'Get page details, title, currentURL, code' print(f'Current title: {driver.title}') print(f'Current url: {driver.current_url}')
Get page details, title, currentURL, code
Module_02/browsing.py
print_page_details
JJSerAnexinet/2021_python_selenium
0
python
def print_page_details(driver: webdriver.Remote): print(f'Current title: {driver.title}') print(f'Current url: {driver.current_url}')
def print_page_details(driver: webdriver.Remote): print(f'Current title: {driver.title}') print(f'Current url: {driver.current_url}')<|docstring|>Get page details, title, currentURL, code<|endoftext|>
15c61a4fe3ffceca328f1292c756bbb8141aeaf4393927de5eff143b49c3da30
def __init__(self, data_dict, user): 'Constructor for Task' super(Tag, self).__init__(data_dict) self.user = user
Constructor for Task
anydo_api/tag.py
__init__
MasteredRed/anydo_api
0
python
def __init__(self, data_dict, user): super(Tag, self).__init__(data_dict) self.user = user
def __init__(self, data_dict, user): super(Tag, self).__init__(data_dict) self.user = user<|docstring|>Constructor for Task<|endoftext|>
5f0210ea8cbacad6be6ddfc3784056d78664a7068a163ef9fcf499c033ba93b9
def session(self): 'Shortcut to retrive user session for requests.' return self.user.session()
Shortcut to retrive user session for requests.
anydo_api/tag.py
session
MasteredRed/anydo_api
0
python
def session(self): return self.user.session()
def session(self): return self.user.session()<|docstring|>Shortcut to retrive user session for requests.<|endoftext|>
e92f9b02eb36882289e52b954dacf0b72a044efa7b8a4a4bf54054122fc4c72b
def tasks(self): 'Return a list of the user tasks that belongs to selected category.' tasks = self.user.tasks() tasks = [task for task in tasks if (task['labels'] is not None)] return [task for task in tasks if (self.id in task['labels'])]
Return a list of the user tasks that belongs to selected category.
anydo_api/tag.py
tasks
MasteredRed/anydo_api
0
python
def tasks(self): tasks = self.user.tasks() tasks = [task for task in tasks if (task['labels'] is not None)] return [task for task in tasks if (self.id in task['labels'])]
def tasks(self): tasks = self.user.tasks() tasks = [task for task in tasks if (task['labels'] is not None)] return [task for task in tasks if (self.id in task['labels'])]<|docstring|>Return a list of the user tasks that belongs to selected category.<|endoftext|>
c1d184329de180c4553037e16bc16378aa7f54c926f6f3f88fc25db711652931
def get_bbg_ids(identifiers): 'Function to parse. Retrieves identification info from bloomberg.\n ' flds = [bf.CUSIP, bf.TICKER, bf.NAME, bf.SECTOR, bf.PARSE_KEY] rtn = get_data_bbg(identifiers, flds) if (len(rtn) == 1): rtn = rtn.values()[0] return rtn
Function to parse. Retrieves identification info from bloomberg.
bbg/bloomberg/misc.py
get_bbg_ids
ychaim/bbg-1
1
python
def get_bbg_ids(identifiers): '\n ' flds = [bf.CUSIP, bf.TICKER, bf.NAME, bf.SECTOR, bf.PARSE_KEY] rtn = get_data_bbg(identifiers, flds) if (len(rtn) == 1): rtn = rtn.values()[0] return rtn
def get_bbg_ids(identifiers): '\n ' flds = [bf.CUSIP, bf.TICKER, bf.NAME, bf.SECTOR, bf.PARSE_KEY] rtn = get_data_bbg(identifiers, flds) if (len(rtn) == 1): rtn = rtn.values()[0] return rtn<|docstring|>Function to parse. Retrieves identification info from bloomberg.<|endoftext|>
ef0b9613091a4b900621b09b65c78b028f7f27f28cffdd8784bce108141bb6c6
@pytest.fixture(params=[True]) def error_monitor_errors(error_monitor_errors): '\n Override error_monitor_errors to capture the messages sent to\n ErrorServiceThread\n ' return error_monitor_errors
Override error_monitor_errors to capture the messages sent to ErrorServiceThread
tests/integration/core/test_error_service.py
error_monitor_errors
tony/scout_apm_python
0
python
@pytest.fixture(params=[True]) def error_monitor_errors(error_monitor_errors): '\n Override error_monitor_errors to capture the messages sent to\n ErrorServiceThread\n ' return error_monitor_errors
@pytest.fixture(params=[True]) def error_monitor_errors(error_monitor_errors): '\n Override error_monitor_errors to capture the messages sent to\n ErrorServiceThread\n ' return error_monitor_errors<|docstring|>Override error_monitor_errors to capture the messages sent to ErrorServiceThread<|endoftext|>
b8598dabf048a597e6a86be1be2cb6b436abf2df049f4ebd9377d0c12686fa03
def __init__(self, number, name, symbol, mass): 'Create a new element.\n\n Parameters\n ----------\n number : int\n The atomic number of the element\n name : string\n The name of the element\n symbol : string\n The chemical symbol of the element\n mass : float\n The atomic mass of the element\n ' self._atomic_number = number self._name = name self._symbol = symbol self._mass = mass s = symbol.strip().upper() Element._elements_by_mass = None if (s in Element._elements_by_symbol): raise ValueError(('Duplicate element symbol %s' % s))
Create a new element. Parameters ---------- number : int The atomic number of the element name : string The name of the element symbol : string The chemical symbol of the element mass : float The atomic mass of the element
foyer/element.py
__init__
justinGilmer/foyer
62
python
def __init__(self, number, name, symbol, mass): 'Create a new element.\n\n Parameters\n ----------\n number : int\n The atomic number of the element\n name : string\n The name of the element\n symbol : string\n The chemical symbol of the element\n mass : float\n The atomic mass of the element\n ' self._atomic_number = number self._name = name self._symbol = symbol self._mass = mass s = symbol.strip().upper() Element._elements_by_mass = None if (s in Element._elements_by_symbol): raise ValueError(('Duplicate element symbol %s' % s))
def __init__(self, number, name, symbol, mass): 'Create a new element.\n\n Parameters\n ----------\n number : int\n The atomic number of the element\n name : string\n The name of the element\n symbol : string\n The chemical symbol of the element\n mass : float\n The atomic mass of the element\n ' self._atomic_number = number self._name = name self._symbol = symbol self._mass = mass s = symbol.strip().upper() Element._elements_by_mass = None if (s in Element._elements_by_symbol): raise ValueError(('Duplicate element symbol %s' % s))<|docstring|>Create a new element. Parameters ---------- number : int The atomic number of the element name : string The name of the element symbol : string The chemical symbol of the element mass : float The atomic mass of the element<|endoftext|>
099ec6154b3fe3168907404d524d97c65c64f5ed04319d421ea608f349b18a21
def reg(name): '\n Activate this register to turn on a minion status tracking register, this\n register keeps the current status beacon data and the time that each beacon\n was last checked in.\n ' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} now = time.time() if ('status' not in __reg__): __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): idata = {'recv_time': now} for key in event['data']['data']: if (key in ('id', 'recv_time')): continue idata[key] = event['data']['data'][key] __reg__['status']['val'][event['data']['id']] = idata ret['changes'][event['data']['id']] = True return ret
Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in.
salt/thorium/status.py
reg
Flowdalic/salt
9,425
python
def reg(name): '\n Activate this register to turn on a minion status tracking register, this\n register keeps the current status beacon data and the time that each beacon\n was last checked in.\n ' ret = {'name': name, 'changes': {}, 'comment': , 'result': True} now = time.time() if ('status' not in __reg__): __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): idata = {'recv_time': now} for key in event['data']['data']: if (key in ('id', 'recv_time')): continue idata[key] = event['data']['data'][key] __reg__['status']['val'][event['data']['id']] = idata ret['changes'][event['data']['id']] = True return ret
def reg(name): '\n Activate this register to turn on a minion status tracking register, this\n register keeps the current status beacon data and the time that each beacon\n was last checked in.\n ' ret = {'name': name, 'changes': {}, 'comment': , 'result': True} now = time.time() if ('status' not in __reg__): __reg__['status'] = {} __reg__['status']['val'] = {} for event in __events__: if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'): idata = {'recv_time': now} for key in event['data']['data']: if (key in ('id', 'recv_time')): continue idata[key] = event['data']['data'][key] __reg__['status']['val'][event['data']['id']] = idata ret['changes'][event['data']['id']] = True return ret<|docstring|>Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in.<|endoftext|>
3786ea8bc35282c56c360c9c2d92225ae132fb0c33c98a0f99bdec874f89f6af
@staticmethod def get_logger() -> logging.Logger: "return the 'dlk' logger if initialized otherwise init and return it\n\n Returns: \n Logger.global_logger\n\n " if (Logger.global_logger is None): Logger.init_global_logger() Logger.global_logger.warning("You didn't init the logger, so we use the default logger setting to output to terminal, you can always set the file logger by yourself.") return Logger.global_logger
return the 'dlk' logger if initialized otherwise init and return it Returns: Logger.global_logger
dlk/utils/_logger.py
get_logger
cstsunfu/dlkit
0
python
@staticmethod def get_logger() -> logging.Logger: "return the 'dlk' logger if initialized otherwise init and return it\n\n Returns: \n Logger.global_logger\n\n " if (Logger.global_logger is None): Logger.init_global_logger() Logger.global_logger.warning("You didn't init the logger, so we use the default logger setting to output to terminal, you can always set the file logger by yourself.") return Logger.global_logger
@staticmethod def get_logger() -> logging.Logger: "return the 'dlk' logger if initialized otherwise init and return it\n\n Returns: \n Logger.global_logger\n\n " if (Logger.global_logger is None): Logger.init_global_logger() Logger.global_logger.warning("You didn't init the logger, so we use the default logger setting to output to terminal, you can always set the file logger by yourself.") return Logger.global_logger<|docstring|>return the 'dlk' logger if initialized otherwise init and return it Returns: Logger.global_logger<|endoftext|>
cc6fe6eb41453d12732d4fc18464f61f78177658acf5e6f51cebc8a45e30d229
@staticmethod def init_file_logger(log_file, base_dir='logs', log_level: str='debug'): "init(if there is not one) or change(if there already is one) the log file\n\n Args:\n log_file: log file path\n base_dir: real log path is '$base_dir/$log_file'\n log_level: 'debug', 'info', etc.\n\n Returns: \n None\n\n " if log_file: log_file = os.path.join(base_dir, log_file) if (log_file and (log_file != Logger.global_log_file)): if (Logger.global_file_handler is not None): Logger.global_logger.removeHandler(Logger.global_file_handler) file_handler = logging.FileHandler(filename=log_file, mode='a', encoding='utf8') file_handler.setLevel(Logger.level_map[log_level]) file_formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S') file_handler.setFormatter(file_formatter) Logger.global_file_handler = file_handler Logger.global_logger.addHandler(file_handler)
init(if there is not one) or change(if there already is one) the log file Args: log_file: log file path base_dir: real log path is '$base_dir/$log_file' log_level: 'debug', 'info', etc. Returns: None
dlk/utils/_logger.py
init_file_logger
cstsunfu/dlkit
0
python
@staticmethod def init_file_logger(log_file, base_dir='logs', log_level: str='debug'): "init(if there is not one) or change(if there already is one) the log file\n\n Args:\n log_file: log file path\n base_dir: real log path is '$base_dir/$log_file'\n log_level: 'debug', 'info', etc.\n\n Returns: \n None\n\n " if log_file: log_file = os.path.join(base_dir, log_file) if (log_file and (log_file != Logger.global_log_file)): if (Logger.global_file_handler is not None): Logger.global_logger.removeHandler(Logger.global_file_handler) file_handler = logging.FileHandler(filename=log_file, mode='a', encoding='utf8') file_handler.setLevel(Logger.level_map[log_level]) file_formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S') file_handler.setFormatter(file_formatter) Logger.global_file_handler = file_handler Logger.global_logger.addHandler(file_handler)
@staticmethod def init_file_logger(log_file, base_dir='logs', log_level: str='debug'): "init(if there is not one) or change(if there already is one) the log file\n\n Args:\n log_file: log file path\n base_dir: real log path is '$base_dir/$log_file'\n log_level: 'debug', 'info', etc.\n\n Returns: \n None\n\n " if log_file: log_file = os.path.join(base_dir, log_file) if (log_file and (log_file != Logger.global_log_file)): if (Logger.global_file_handler is not None): Logger.global_logger.removeHandler(Logger.global_file_handler) file_handler = logging.FileHandler(filename=log_file, mode='a', encoding='utf8') file_handler.setLevel(Logger.level_map[log_level]) file_formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S') file_handler.setFormatter(file_formatter) Logger.global_file_handler = file_handler Logger.global_logger.addHandler(file_handler)<|docstring|>init(if there is not one) or change(if there already is one) the log file Args: log_file: log file path base_dir: real log path is '$base_dir/$log_file' log_level: 'debug', 'info', etc. Returns: None<|endoftext|>
77f77a4a36f3c5a53fba688184511b25c537f305f36e5331305e7e3d1c8eced4
@staticmethod def init_global_logger(log_level: str='debug', log_name: str='dlk'): 'init the global_logger\n\n Args:\n log_level: you can change this to logger to different level\n log_name: change this is not suggested \n\n Returns: \n None\n\n ' if (Logger.global_logger is None): Logger.global_logger = logging.getLogger(log_name) Logger.global_logger.setLevel(Logger.level_map[log_level]) console_handler = logging.StreamHandler() console_handler.setLevel(Logger.level_map[log_level]) console_formatter = colorlog.ColoredFormatter(fmt='%(log_color)s%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', log_colors=Logger.color_config) console_handler.setFormatter(console_formatter) Logger.global_logger.addHandler(console_handler) Logger.global_logger.propagate = False
init the global_logger Args: log_level: you can change this to logger to different level log_name: change this is not suggested Returns: None
dlk/utils/_logger.py
init_global_logger
cstsunfu/dlkit
0
python
@staticmethod def init_global_logger(log_level: str='debug', log_name: str='dlk'): 'init the global_logger\n\n Args:\n log_level: you can change this to logger to different level\n log_name: change this is not suggested \n\n Returns: \n None\n\n ' if (Logger.global_logger is None): Logger.global_logger = logging.getLogger(log_name) Logger.global_logger.setLevel(Logger.level_map[log_level]) console_handler = logging.StreamHandler() console_handler.setLevel(Logger.level_map[log_level]) console_formatter = colorlog.ColoredFormatter(fmt='%(log_color)s%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', log_colors=Logger.color_config) console_handler.setFormatter(console_formatter) Logger.global_logger.addHandler(console_handler) Logger.global_logger.propagate = False
@staticmethod def init_global_logger(log_level: str='debug', log_name: str='dlk'): 'init the global_logger\n\n Args:\n log_level: you can change this to logger to different level\n log_name: change this is not suggested \n\n Returns: \n None\n\n ' if (Logger.global_logger is None): Logger.global_logger = logging.getLogger(log_name) Logger.global_logger.setLevel(Logger.level_map[log_level]) console_handler = logging.StreamHandler() console_handler.setLevel(Logger.level_map[log_level]) console_formatter = colorlog.ColoredFormatter(fmt='%(log_color)s%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', log_colors=Logger.color_config) console_handler.setFormatter(console_formatter) Logger.global_logger.addHandler(console_handler) Logger.global_logger.propagate = False<|docstring|>init the global_logger Args: log_level: you can change this to logger to different level log_name: change this is not suggested Returns: None<|endoftext|>
69b0b44ef2013d55d20f35b3326cc92ffe4276da98f0ea1310fa7068b49e3e4b
def is_only_embed(maybe_embeds): '\n Checks whether the given value is a `tuple` or `list` containing only `embed-like`-s.\n \n Parameters\n ----------\n maybe_embeds : (`tuple` or `list`) of `EmbedBase` or `Any`\n The value to check whether is a `tuple` or `list` containing only `embed-like`-s.\n \n Returns\n -------\n is_only_embed : `bool`\n ' if (not isinstance(maybe_embeds, (list, tuple))): return False for maybe_embed in maybe_embeds: if (not isinstance(maybe_embed, EmbedBase)): return False return True
Checks whether the given value is a `tuple` or `list` containing only `embed-like`-s. Parameters ---------- maybe_embeds : (`tuple` or `list`) of `EmbedBase` or `Any` The value to check whether is a `tuple` or `list` containing only `embed-like`-s. Returns ------- is_only_embed : `bool`
hata/ext/slash/responding.py
is_only_embed
catzoo/hata
173
python
def is_only_embed(maybe_embeds): '\n Checks whether the given value is a `tuple` or `list` containing only `embed-like`-s.\n \n Parameters\n ----------\n maybe_embeds : (`tuple` or `list`) of `EmbedBase` or `Any`\n The value to check whether is a `tuple` or `list` containing only `embed-like`-s.\n \n Returns\n -------\n is_only_embed : `bool`\n ' if (not isinstance(maybe_embeds, (list, tuple))): return False for maybe_embed in maybe_embeds: if (not isinstance(maybe_embed, EmbedBase)): return False return True
def is_only_embed(maybe_embeds): '\n Checks whether the given value is a `tuple` or `list` containing only `embed-like`-s.\n \n Parameters\n ----------\n maybe_embeds : (`tuple` or `list`) of `EmbedBase` or `Any`\n The value to check whether is a `tuple` or `list` containing only `embed-like`-s.\n \n Returns\n -------\n is_only_embed : `bool`\n ' if (not isinstance(maybe_embeds, (list, tuple))): return False for maybe_embed in maybe_embeds: if (not isinstance(maybe_embed, EmbedBase)): return False return True<|docstring|>Checks whether the given value is a `tuple` or `list` containing only `embed-like`-s. Parameters ---------- maybe_embeds : (`tuple` or `list`) of `EmbedBase` or `Any` The value to check whether is a `tuple` or `list` containing only `embed-like`-s. Returns ------- is_only_embed : `bool`<|endoftext|>
c2ad055683844298b8d9eaf27510cc4f23a934c04c54302793ddec741e0d38e2
async def get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): '\n Gets request coroutine after an output from a command coroutine. Might return `None` if there is nothing to send.\n \n This function is a coroutine generator, which should be ued inside of an async for loop.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n response : `Any`\n Any object yielded or returned by the command coroutine.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' interaction_event_type = interaction_event.type if (response is None): if interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_application_command_acknowledge(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return if (isinstance(response, (str, EmbedBase)) or is_only_embed(response)): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_followup_message_create(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return if is_coroutine_generator(response): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, response)) async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): (yield request_coro) return if isinstance(response, InteractionResponse): for request_coro in response.get_request_coroutines(client, interaction_event, show_for_invoking_user_only, is_return): (yield request_coro) return response = str(response) if (len(response) > 2000): response = response[:2000] if response: if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_response_message_edit(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return elif interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return return
Gets request coroutine after an output from a command coroutine. Might return `None` if there is nothing to send. This function is a coroutine generator, which should be ued inside of an async for loop. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. response : `Any` Any object yielded or returned by the command coroutine. is_return : `bool` Whether the response is used in a return and we do not require response message. Yields ------- request_coro : `None` or `coroutine`
hata/ext/slash/responding.py
get_request_coroutines
catzoo/hata
173
python
async def get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): '\n Gets request coroutine after an output from a command coroutine. Might return `None` if there is nothing to send.\n \n This function is a coroutine generator, which should be ued inside of an async for loop.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n response : `Any`\n Any object yielded or returned by the command coroutine.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' interaction_event_type = interaction_event.type if (response is None): if interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_application_command_acknowledge(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return if (isinstance(response, (str, EmbedBase)) or is_only_embed(response)): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_followup_message_create(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return if is_coroutine_generator(response): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, response)) async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): (yield request_coro) return if isinstance(response, InteractionResponse): for request_coro in response.get_request_coroutines(client, interaction_event, show_for_invoking_user_only, is_return): (yield request_coro) return response = str(response) if (len(response) > 2000): response = response[:2000] if response: if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_response_message_edit(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return elif interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return return
async def get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): '\n Gets request coroutine after an output from a command coroutine. Might return `None` if there is nothing to send.\n \n This function is a coroutine generator, which should be ued inside of an async for loop.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n response : `Any`\n Any object yielded or returned by the command coroutine.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' interaction_event_type = interaction_event.type if (response is None): if interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_application_command_acknowledge(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return if (isinstance(response, (str, EmbedBase)) or is_only_embed(response)): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_followup_message_create(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return if is_coroutine_generator(response): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, response)) async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, is_return): (yield request_coro) return if isinstance(response, InteractionResponse): for request_coro in response.get_request_coroutines(client, interaction_event, show_for_invoking_user_only, is_return): (yield request_coro) return response = str(response) if (len(response) > 2000): response = response[:2000] if response: if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): if interaction_event.is_unanswered(): (yield client.interaction_response_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif interaction_event.is_deferred(): (yield client.interaction_response_message_edit(interaction_event, response)) elif interaction_event.is_responded(): (yield client.interaction_followup_message_create(interaction_event, response, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_message_edit(interaction_event, response)) return elif interaction_event.is_unanswered(): if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) elif (interaction_event_type is INTERACTION_TYPE_MESSAGE_COMPONENT): (yield client.interaction_component_acknowledge(interaction_event)) return return<|docstring|>Gets request coroutine after an output from a command coroutine. Might return `None` if there is nothing to send. This function is a coroutine generator, which should be ued inside of an async for loop. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. response : `Any` Any object yielded or returned by the command coroutine. is_return : `bool` Whether the response is used in a return and we do not require response message. Yields ------- request_coro : `None` or `coroutine`<|endoftext|>
56b585d2d7bd06a61b98cdcfae9b783db1ad1ab422ef9e80e99213c313ffb4c4
async def process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine_generator): '\n Processes a slash command coroutine generator.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine_generator : `CoroutineGenerator`\n A coroutine generator with will send command response.\n \n Returns\n -------\n response : `Any`\n Returned object by the coroutine generator.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine_generator`.\n ' response_message = None response_exception = None while True: if (response_exception is None): step = coroutine_generator.asend(response_message) else: step = coroutine_generator.athrow(response_exception) try: response = (await step) except StopAsyncIteration as err: if ((response_exception is not None) and (response_exception is not err)): raise args = err.args if args: response = args[0] else: response = None break except InteractionAbortedError as err: response = err.response break except BaseException as err: if ((response_exception is None) or (response_exception is not err)): raise if isinstance(err, ConnectionError): return raise else: response_message = None response_exception = None async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, False): try: response_message = (await request_coro) except BaseException as err: response_message = None response_exception = err break return response
Processes a slash command coroutine generator. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. coroutine_generator : `CoroutineGenerator` A coroutine generator with will send command response. Returns ------- response : `Any` Returned object by the coroutine generator. Raises ------ BaseException Any exception raised by `coroutine_generator`.
hata/ext/slash/responding.py
process_command_coroutine_generator
catzoo/hata
173
python
async def process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine_generator): '\n Processes a slash command coroutine generator.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine_generator : `CoroutineGenerator`\n A coroutine generator with will send command response.\n \n Returns\n -------\n response : `Any`\n Returned object by the coroutine generator.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine_generator`.\n ' response_message = None response_exception = None while True: if (response_exception is None): step = coroutine_generator.asend(response_message) else: step = coroutine_generator.athrow(response_exception) try: response = (await step) except StopAsyncIteration as err: if ((response_exception is not None) and (response_exception is not err)): raise args = err.args if args: response = args[0] else: response = None break except InteractionAbortedError as err: response = err.response break except BaseException as err: if ((response_exception is None) or (response_exception is not err)): raise if isinstance(err, ConnectionError): return raise else: response_message = None response_exception = None async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, False): try: response_message = (await request_coro) except BaseException as err: response_message = None response_exception = err break return response
async def process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine_generator): '\n Processes a slash command coroutine generator.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine_generator : `CoroutineGenerator`\n A coroutine generator with will send command response.\n \n Returns\n -------\n response : `Any`\n Returned object by the coroutine generator.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine_generator`.\n ' response_message = None response_exception = None while True: if (response_exception is None): step = coroutine_generator.asend(response_message) else: step = coroutine_generator.athrow(response_exception) try: response = (await step) except StopAsyncIteration as err: if ((response_exception is not None) and (response_exception is not err)): raise args = err.args if args: response = args[0] else: response = None break except InteractionAbortedError as err: response = err.response break except BaseException as err: if ((response_exception is None) or (response_exception is not err)): raise if isinstance(err, ConnectionError): return raise else: response_message = None response_exception = None async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, False): try: response_message = (await request_coro) except BaseException as err: response_message = None response_exception = err break return response<|docstring|>Processes a slash command coroutine generator. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. coroutine_generator : `CoroutineGenerator` A coroutine generator with will send command response. Returns ------- response : `Any` Returned object by the coroutine generator. Raises ------ BaseException Any exception raised by `coroutine_generator`.<|endoftext|>
e9808982a2899e5cb57de3e593fd1185527bcb36ca429452b14af3d3d7f53648
async def process_command_coroutine(client, interaction_event, show_for_invoking_user_only, coroutine): '\n Processes a slasher application command coroutine.\n \n If the coroutine returns or yields a string or an embed like then sends it to the respective channel.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' if is_coroutine_generator(coroutine): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine)) else: try: response = (await coroutine) except InteractionAbortedError as err: response = err.response async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, True): try: (await request_coro) except BaseException as err: if isinstance(err, ConnectionError): return raise
Processes a slasher application command coroutine. If the coroutine returns or yields a string or an embed like then sends it to the respective channel. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. coroutine : `Coroutine` A coroutine which will produce command response. Raises ------ BaseException Any exception raised by `coroutine`.
hata/ext/slash/responding.py
process_command_coroutine
catzoo/hata
173
python
async def process_command_coroutine(client, interaction_event, show_for_invoking_user_only, coroutine): '\n Processes a slasher application command coroutine.\n \n If the coroutine returns or yields a string or an embed like then sends it to the respective channel.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' if is_coroutine_generator(coroutine): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine)) else: try: response = (await coroutine) except InteractionAbortedError as err: response = err.response async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, True): try: (await request_coro) except BaseException as err: if isinstance(err, ConnectionError): return raise
async def process_command_coroutine(client, interaction_event, show_for_invoking_user_only, coroutine): '\n Processes a slasher application command coroutine.\n \n If the coroutine returns or yields a string or an embed like then sends it to the respective channel.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' if is_coroutine_generator(coroutine): response = (await process_command_coroutine_generator(client, interaction_event, show_for_invoking_user_only, coroutine)) else: try: response = (await coroutine) except InteractionAbortedError as err: response = err.response async for request_coro in get_request_coroutines(client, interaction_event, show_for_invoking_user_only, response, True): try: (await request_coro) except BaseException as err: if isinstance(err, ConnectionError): return raise<|docstring|>Processes a slasher application command coroutine. If the coroutine returns or yields a string or an embed like then sends it to the respective channel. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. coroutine : `Coroutine` A coroutine which will produce command response. Raises ------ BaseException Any exception raised by `coroutine`.<|endoftext|>
e1f83b52f4fae71da29b0ee19e604198615ade95924e1e25a1a95938b916742d
def abort(content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Aborts the slash response with sending the passed parameters as a response.\n \n The abortion auto detects `show_for_invoking_user_only` if not given. Not follows the command's preference.\n If only a string `content` is given, `show_for_invoking_user_only` will become `True`, else `False`. The reason of\n becoming `False` at that case is, Discord ignores every other field except string content.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user.\n \n If given as `True`, only the message's content and embeds and components will be processed by Discord.\n \n Raises\n ------\n InteractionAbortedError\n The exception which aborts the interaction, then yields the response.\n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " if (show_for_invoking_user_only is ...): if (file is not ...): show_for_invoking_user_only = False else: show_for_invoking_user_only = True response = InteractionResponse(content, embed=embed, file=file, allowed_mentions=allowed_mentions, components=components, tts=tts, show_for_invoking_user_only=show_for_invoking_user_only, message=message, event=event) response._is_abort = True raise InteractionAbortedError(response)
Aborts the slash response with sending the passed parameters as a response. The abortion auto detects `show_for_invoking_user_only` if not given. Not follows the command's preference. If only a string `content` is given, `show_for_invoking_user_only` will become `True`, else `False`. The reason of becoming `False` at that case is, Discord ignores every other field except string content. Parameters ---------- content : `str`, ``EmbedBase``, `Any`, Optional The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string. If given as ``EmbedBase`` instance, then is sent as the message's embed. embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only) The embedded content of the message. If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised. file : `Any`, Optional (Keyword only) A file to send. Check ``Client._create_file_form`` for details. allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` ) , Optional (Keyword only) Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details. components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only) Components attached to the message. tts : `bool`, Optional (Keyword only) Whether the message is text-to-speech. show_for_invoking_user_only : `bool`, Optional (Keyword only) Whether the sent message should only be shown to the invoking user. If given as `True`, only the message's content and embeds and components will be processed by Discord. Raises ------ InteractionAbortedError The exception which aborts the interaction, then yields the response. message : `None`, ``Message``, Optional (Keyword only) Whether the interaction's message should be edited. event : `None`, ``InteractionEvent``, Optional (Keyword only) A specific event ot answer instead of the command's.
hata/ext/slash/responding.py
abort
catzoo/hata
173
python
def abort(content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Aborts the slash response with sending the passed parameters as a response.\n \n The abortion auto detects `show_for_invoking_user_only` if not given. Not follows the command's preference.\n If only a string `content` is given, `show_for_invoking_user_only` will become `True`, else `False`. The reason of\n becoming `False` at that case is, Discord ignores every other field except string content.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user.\n \n If given as `True`, only the message's content and embeds and components will be processed by Discord.\n \n Raises\n ------\n InteractionAbortedError\n The exception which aborts the interaction, then yields the response.\n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " if (show_for_invoking_user_only is ...): if (file is not ...): show_for_invoking_user_only = False else: show_for_invoking_user_only = True response = InteractionResponse(content, embed=embed, file=file, allowed_mentions=allowed_mentions, components=components, tts=tts, show_for_invoking_user_only=show_for_invoking_user_only, message=message, event=event) response._is_abort = True raise InteractionAbortedError(response)
def abort(content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Aborts the slash response with sending the passed parameters as a response.\n \n The abortion auto detects `show_for_invoking_user_only` if not given. Not follows the command's preference.\n If only a string `content` is given, `show_for_invoking_user_only` will become `True`, else `False`. The reason of\n becoming `False` at that case is, Discord ignores every other field except string content.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user.\n \n If given as `True`, only the message's content and embeds and components will be processed by Discord.\n \n Raises\n ------\n InteractionAbortedError\n The exception which aborts the interaction, then yields the response.\n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " if (show_for_invoking_user_only is ...): if (file is not ...): show_for_invoking_user_only = False else: show_for_invoking_user_only = True response = InteractionResponse(content, embed=embed, file=file, allowed_mentions=allowed_mentions, components=components, tts=tts, show_for_invoking_user_only=show_for_invoking_user_only, message=message, event=event) response._is_abort = True raise InteractionAbortedError(response)<|docstring|>Aborts the slash response with sending the passed parameters as a response. The abortion auto detects `show_for_invoking_user_only` if not given. Not follows the command's preference. If only a string `content` is given, `show_for_invoking_user_only` will become `True`, else `False`. The reason of becoming `False` at that case is, Discord ignores every other field except string content. Parameters ---------- content : `str`, ``EmbedBase``, `Any`, Optional The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string. If given as ``EmbedBase`` instance, then is sent as the message's embed. embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only) The embedded content of the message. If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised. file : `Any`, Optional (Keyword only) A file to send. Check ``Client._create_file_form`` for details. allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` ) , Optional (Keyword only) Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details. components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only) Components attached to the message. tts : `bool`, Optional (Keyword only) Whether the message is text-to-speech. show_for_invoking_user_only : `bool`, Optional (Keyword only) Whether the sent message should only be shown to the invoking user. If given as `True`, only the message's content and embeds and components will be processed by Discord. Raises ------ InteractionAbortedError The exception which aborts the interaction, then yields the response. message : `None`, ``Message``, Optional (Keyword only) Whether the interaction's message should be edited. event : `None`, ``InteractionEvent``, Optional (Keyword only) A specific event ot answer instead of the command's.<|endoftext|>
691bdedd433fcd26fd3007c56701d60bc299969b642daa0affc9d5f5cfa11e7a
async def process_auto_completer_coroutine(client, interaction_event, coroutine): '\n Processes a slasher application command coroutine.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' response = (await coroutine) (await client.interaction_application_command_autocomplete(interaction_event, response))
Processes a slasher application command coroutine. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. coroutine : `Coroutine` A coroutine which will produce command response. Raises ------ BaseException Any exception raised by `coroutine`.
hata/ext/slash/responding.py
process_auto_completer_coroutine
catzoo/hata
173
python
async def process_auto_completer_coroutine(client, interaction_event, coroutine): '\n Processes a slasher application command coroutine.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' response = (await coroutine) (await client.interaction_application_command_autocomplete(interaction_event, response))
async def process_auto_completer_coroutine(client, interaction_event, coroutine): '\n Processes a slasher application command coroutine.\n \n This function is a coroutine.\n \n Parameters\n ----------\n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n coroutine : `Coroutine`\n A coroutine which will produce command response.\n \n Raises\n ------\n BaseException\n Any exception raised by `coroutine`.\n ' response = (await coroutine) (await client.interaction_application_command_autocomplete(interaction_event, response))<|docstring|>Processes a slasher application command coroutine. This function is a coroutine. Parameters ---------- client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. coroutine : `Coroutine` A coroutine which will produce command response. Raises ------ BaseException Any exception raised by `coroutine`.<|endoftext|>
23438127e13e7a892aa835e54883dcb652e55028ea14c96eccf4e209c972c49a
def __init__(self, content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Creates a new ``InteractionResponse`` instance with the given parameters.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n \n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user. Defaults to the value passed when adding\n the command.\n \n If given as `True` only the message's content will be processed by Discord.\n \n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " self._is_abort = False self._parameters = parameters = {} self._message = message self._event = event if (content is not ...): parameters['content'] = content if (embed is not ...): parameters['embed'] = embed if (file is not ...): parameters['file'] = file if (allowed_mentions is not ...): parameters['allowed_mentions'] = allowed_mentions if (components is not ...): parameters['components'] = components if (tts is not ...): parameters['tts'] = tts if (show_for_invoking_user_only is not ...): parameters['show_for_invoking_user_only'] = show_for_invoking_user_only
Creates a new ``InteractionResponse`` instance with the given parameters. Parameters ---------- content : `str`, ``EmbedBase``, `Any`, Optional The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string. If given as ``EmbedBase`` instance, then is sent as the message's embed. embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only) The embedded content of the message. If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised. file : `Any`, Optional (Keyword only) A file to send. Check ``Client._create_file_form`` for details. allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` ) , Optional (Keyword only) Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details. components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only) Components attached to the message. tts : `bool`, Optional (Keyword only) Whether the message is text-to-speech. show_for_invoking_user_only : `bool`, Optional (Keyword only) Whether the sent message should only be shown to the invoking user. Defaults to the value passed when adding the command. If given as `True` only the message's content will be processed by Discord. message : `None`, ``Message``, Optional (Keyword only) Whether the interaction's message should be edited. event : `None`, ``InteractionEvent``, Optional (Keyword only) A specific event ot answer instead of the command's.
hata/ext/slash/responding.py
__init__
catzoo/hata
173
python
def __init__(self, content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Creates a new ``InteractionResponse`` instance with the given parameters.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n \n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user. Defaults to the value passed when adding\n the command.\n \n If given as `True` only the message's content will be processed by Discord.\n \n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " self._is_abort = False self._parameters = parameters = {} self._message = message self._event = event if (content is not ...): parameters['content'] = content if (embed is not ...): parameters['embed'] = embed if (file is not ...): parameters['file'] = file if (allowed_mentions is not ...): parameters['allowed_mentions'] = allowed_mentions if (components is not ...): parameters['components'] = components if (tts is not ...): parameters['tts'] = tts if (show_for_invoking_user_only is not ...): parameters['show_for_invoking_user_only'] = show_for_invoking_user_only
def __init__(self, content=..., *, embed=..., file=..., allowed_mentions=..., components=..., tts=..., show_for_invoking_user_only=..., message=..., event=None): "\n Creates a new ``InteractionResponse`` instance with the given parameters.\n \n Parameters\n ----------\n content : `str`, ``EmbedBase``, `Any`, Optional\n The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile\n if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string.\n \n If given as ``EmbedBase`` instance, then is sent as the message's embed.\n \n embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only)\n The embedded content of the message.\n \n If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised.\n file : `Any`, Optional (Keyword only)\n A file to send. Check ``Client._create_file_form`` for details.\n allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` )\n , Optional (Keyword only)\n Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details.\n components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only)\n Components attached to the message.\n tts : `bool`, Optional (Keyword only)\n Whether the message is text-to-speech.\n show_for_invoking_user_only : `bool`, Optional (Keyword only)\n Whether the sent message should only be shown to the invoking user. Defaults to the value passed when adding\n the command.\n \n If given as `True` only the message's content will be processed by Discord.\n \n message : `None`, ``Message``, Optional (Keyword only)\n Whether the interaction's message should be edited.\n event : `None`, ``InteractionEvent``, Optional (Keyword only)\n A specific event ot answer instead of the command's.\n " self._is_abort = False self._parameters = parameters = {} self._message = message self._event = event if (content is not ...): parameters['content'] = content if (embed is not ...): parameters['embed'] = embed if (file is not ...): parameters['file'] = file if (allowed_mentions is not ...): parameters['allowed_mentions'] = allowed_mentions if (components is not ...): parameters['components'] = components if (tts is not ...): parameters['tts'] = tts if (show_for_invoking_user_only is not ...): parameters['show_for_invoking_user_only'] = show_for_invoking_user_only<|docstring|>Creates a new ``InteractionResponse`` instance with the given parameters. Parameters ---------- content : `str`, ``EmbedBase``, `Any`, Optional The message's content if given. If given as `str` or empty string, then no content will be sent, meanwhile if any other non `str` or ``EmbedBase`` instance is given, then will be casted to string. If given as ``EmbedBase`` instance, then is sent as the message's embed. embed : ``EmbedBase`` instance or `list` of ``EmbedBase`` instances, Optional (Keyword only) The embedded content of the message. If `embed` and `content` parameters are both given as ``EmbedBase`` instance, then `TypeError` is raised. file : `Any`, Optional (Keyword only) A file to send. Check ``Client._create_file_form`` for details. allowed_mentions : `None`, `str`, ``UserBase``, ``Role``, `list` of (`str`, ``UserBase``, ``Role`` ) , Optional (Keyword only) Which user or role can the message ping (or everyone). Check ``Client._parse_allowed_mentions`` for details. components : `None`, ``ComponentBase``, (`set`, `list`) of ``ComponentBase``, Optional (Keyword only) Components attached to the message. tts : `bool`, Optional (Keyword only) Whether the message is text-to-speech. show_for_invoking_user_only : `bool`, Optional (Keyword only) Whether the sent message should only be shown to the invoking user. Defaults to the value passed when adding the command. If given as `True` only the message's content will be processed by Discord. message : `None`, ``Message``, Optional (Keyword only) Whether the interaction's message should be edited. event : `None`, ``InteractionEvent``, Optional (Keyword only) A specific event ot answer instead of the command's.<|endoftext|>
818aca27430876f05a36fe73805c3a9f17dba19cf32d5f0d576bde09fd070516
def _get_response_parameters(self, allowed_parameters): '\n Gets response parameters to pass to a ``Client`` method.\n \n Parameters\n ----------\n allowed_parameters : `tuple` of `str`\n Allowed parameters to be passed to the respective client method.\n \n Returns\n -------\n response_parameters : `dict` of (`str`, `Any`) items\n Parameters to pass the the respective client method.\n ' parameters = self._parameters response_parameters = {} for key in allowed_parameters: try: value = parameters[key] except KeyError: continue response_parameters[key] = value return response_parameters
Gets response parameters to pass to a ``Client`` method. Parameters ---------- allowed_parameters : `tuple` of `str` Allowed parameters to be passed to the respective client method. Returns ------- response_parameters : `dict` of (`str`, `Any`) items Parameters to pass the the respective client method.
hata/ext/slash/responding.py
_get_response_parameters
catzoo/hata
173
python
def _get_response_parameters(self, allowed_parameters): '\n Gets response parameters to pass to a ``Client`` method.\n \n Parameters\n ----------\n allowed_parameters : `tuple` of `str`\n Allowed parameters to be passed to the respective client method.\n \n Returns\n -------\n response_parameters : `dict` of (`str`, `Any`) items\n Parameters to pass the the respective client method.\n ' parameters = self._parameters response_parameters = {} for key in allowed_parameters: try: value = parameters[key] except KeyError: continue response_parameters[key] = value return response_parameters
def _get_response_parameters(self, allowed_parameters): '\n Gets response parameters to pass to a ``Client`` method.\n \n Parameters\n ----------\n allowed_parameters : `tuple` of `str`\n Allowed parameters to be passed to the respective client method.\n \n Returns\n -------\n response_parameters : `dict` of (`str`, `Any`) items\n Parameters to pass the the respective client method.\n ' parameters = self._parameters response_parameters = {} for key in allowed_parameters: try: value = parameters[key] except KeyError: continue response_parameters[key] = value return response_parameters<|docstring|>Gets response parameters to pass to a ``Client`` method. Parameters ---------- allowed_parameters : `tuple` of `str` Allowed parameters to be passed to the respective client method. Returns ------- response_parameters : `dict` of (`str`, `Any`) items Parameters to pass the the respective client method.<|endoftext|>
ac316750a2498bc70066b7ae837035f28f8775f0771deb66aa20e0093d8e9ca0
def get_request_coroutines(self, client, interaction_event, show_for_invoking_user_only, is_return): '\n Gets request coroutine buildable from the ``InteractionResponse``.\n \n This method is a generator, which should be used inside of a `for` loop.\n \n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' event = self._event if (event is not None): interaction_event = event interaction_event_type = interaction_event.type if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): message = self._message if (message is not ...): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'components', 'embed', 'file')) if (message is None): (yield client.interaction_response_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_followup_message_edit(interaction_event, message, **response_parameters)) return show_for_invoking_user_only = self._parameters.get('show_for_invoking_user_only', show_for_invoking_user_only) if ('file' in self._parameters): need_acknowledging = True elif self._is_abort: need_acknowledging = False elif is_return: need_acknowledging = False elif interaction_event.is_unanswered(): need_acknowledging = True else: need_acknowledging = False if need_acknowledging: (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'file', 'tts', 'components')) if (not need_acknowledging): response_parameters['show_for_invoking_user_only'] = show_for_invoking_user_only (yield client.interaction_followup_message_create(interaction_event, **response_parameters)) return elif (interaction_event.type is INTERACTION_TYPE_MESSAGE_COMPONENT): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'components')) if response_parameters: (yield client.interaction_component_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_component_acknowledge(interaction_event)) return
Gets request coroutine buildable from the ``InteractionResponse``. This method is a generator, which should be used inside of a `for` loop. client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. is_return : `bool` Whether the response is used in a return and we do not require response message. Yields ------- request_coro : `None` or `coroutine`
hata/ext/slash/responding.py
get_request_coroutines
catzoo/hata
173
python
def get_request_coroutines(self, client, interaction_event, show_for_invoking_user_only, is_return): '\n Gets request coroutine buildable from the ``InteractionResponse``.\n \n This method is a generator, which should be used inside of a `for` loop.\n \n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' event = self._event if (event is not None): interaction_event = event interaction_event_type = interaction_event.type if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): message = self._message if (message is not ...): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'components', 'embed', 'file')) if (message is None): (yield client.interaction_response_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_followup_message_edit(interaction_event, message, **response_parameters)) return show_for_invoking_user_only = self._parameters.get('show_for_invoking_user_only', show_for_invoking_user_only) if ('file' in self._parameters): need_acknowledging = True elif self._is_abort: need_acknowledging = False elif is_return: need_acknowledging = False elif interaction_event.is_unanswered(): need_acknowledging = True else: need_acknowledging = False if need_acknowledging: (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'file', 'tts', 'components')) if (not need_acknowledging): response_parameters['show_for_invoking_user_only'] = show_for_invoking_user_only (yield client.interaction_followup_message_create(interaction_event, **response_parameters)) return elif (interaction_event.type is INTERACTION_TYPE_MESSAGE_COMPONENT): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'components')) if response_parameters: (yield client.interaction_component_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_component_acknowledge(interaction_event)) return
def get_request_coroutines(self, client, interaction_event, show_for_invoking_user_only, is_return): '\n Gets request coroutine buildable from the ``InteractionResponse``.\n \n This method is a generator, which should be used inside of a `for` loop.\n \n client : ``Client``\n The client who will send the responses if applicable.\n interaction_event : ``InteractionEvent``\n The respective event to respond on.\n show_for_invoking_user_only : `bool`\n Whether the response message should only be shown for the invoking user.\n is_return : `bool`\n Whether the response is used in a return and we do not require response message.\n \n Yields\n -------\n request_coro : `None` or `coroutine`\n ' event = self._event if (event is not None): interaction_event = event interaction_event_type = interaction_event.type if (interaction_event_type is INTERACTION_TYPE_APPLICATION_COMMAND): message = self._message if (message is not ...): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'components', 'embed', 'file')) if (message is None): (yield client.interaction_response_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_followup_message_edit(interaction_event, message, **response_parameters)) return show_for_invoking_user_only = self._parameters.get('show_for_invoking_user_only', show_for_invoking_user_only) if ('file' in self._parameters): need_acknowledging = True elif self._is_abort: need_acknowledging = False elif is_return: need_acknowledging = False elif interaction_event.is_unanswered(): need_acknowledging = True else: need_acknowledging = False if need_acknowledging: (yield client.interaction_response_message_create(interaction_event, show_for_invoking_user_only=show_for_invoking_user_only)) response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'file', 'tts', 'components')) if (not need_acknowledging): response_parameters['show_for_invoking_user_only'] = show_for_invoking_user_only (yield client.interaction_followup_message_create(interaction_event, **response_parameters)) return elif (interaction_event.type is INTERACTION_TYPE_MESSAGE_COMPONENT): response_parameters = self._get_response_parameters(('allowed_mentions', 'content', 'embed', 'components')) if response_parameters: (yield client.interaction_component_message_edit(interaction_event, **response_parameters)) else: (yield client.interaction_component_acknowledge(interaction_event)) return<|docstring|>Gets request coroutine buildable from the ``InteractionResponse``. This method is a generator, which should be used inside of a `for` loop. client : ``Client`` The client who will send the responses if applicable. interaction_event : ``InteractionEvent`` The respective event to respond on. show_for_invoking_user_only : `bool` Whether the response message should only be shown for the invoking user. is_return : `bool` Whether the response is used in a return and we do not require response message. Yields ------- request_coro : `None` or `coroutine`<|endoftext|>
8da67192247663d9ac0f02ec22545c98c3e5af166fa48335d2e544d869051ef9
def __repr__(self): "Returns the slash response's representation." repr_parts = ['<', self.__class__.__name__, ' '] if self._is_abort: repr_parts.append('(abort) ') parameters = self._parameters if parameters: for (key, value) in parameters.items(): repr_parts.append(key) repr_parts.append('=') repr_parts.append(repr(value)) repr_parts.append(', ') repr_parts[(- 1)] = '>' else: repr_parts.append('>') return ''.join(repr_parts)
Returns the slash response's representation.
hata/ext/slash/responding.py
__repr__
catzoo/hata
173
python
def __repr__(self): repr_parts = ['<', self.__class__.__name__, ' '] if self._is_abort: repr_parts.append('(abort) ') parameters = self._parameters if parameters: for (key, value) in parameters.items(): repr_parts.append(key) repr_parts.append('=') repr_parts.append(repr(value)) repr_parts.append(', ') repr_parts[(- 1)] = '>' else: repr_parts.append('>') return .join(repr_parts)
def __repr__(self): repr_parts = ['<', self.__class__.__name__, ' '] if self._is_abort: repr_parts.append('(abort) ') parameters = self._parameters if parameters: for (key, value) in parameters.items(): repr_parts.append(key) repr_parts.append('=') repr_parts.append(repr(value)) repr_parts.append(', ') repr_parts[(- 1)] = '>' else: repr_parts.append('>') return .join(repr_parts)<|docstring|>Returns the slash response's representation.<|endoftext|>
b39883161a6fc1bd578a2e0e01162f168708f3e0825627cbe167f9c9d6bdb332
def __init__(self, response): '\n Creates a new ``InteractionAbortedError`` instance with the given response.\n \n Parameters\n ----------\n response : ``InteractionResponse``\n The response to send.\n ' self.response = response BaseException.__init__(self, response)
Creates a new ``InteractionAbortedError`` instance with the given response. Parameters ---------- response : ``InteractionResponse`` The response to send.
hata/ext/slash/responding.py
__init__
catzoo/hata
173
python
def __init__(self, response): '\n Creates a new ``InteractionAbortedError`` instance with the given response.\n \n Parameters\n ----------\n response : ``InteractionResponse``\n The response to send.\n ' self.response = response BaseException.__init__(self, response)
def __init__(self, response): '\n Creates a new ``InteractionAbortedError`` instance with the given response.\n \n Parameters\n ----------\n response : ``InteractionResponse``\n The response to send.\n ' self.response = response BaseException.__init__(self, response)<|docstring|>Creates a new ``InteractionAbortedError`` instance with the given response. Parameters ---------- response : ``InteractionResponse`` The response to send.<|endoftext|>
df21c598289e9404ea4abded861b3300f2c1f6fb2bc43579bcedd92a59816026
def __repr__(self): "Returns the exception's representation." return f'{self.__class__.__name__}({self.response!r})'
Returns the exception's representation.
hata/ext/slash/responding.py
__repr__
catzoo/hata
173
python
def __repr__(self): return f'{self.__class__.__name__}({self.response!r})'
def __repr__(self): return f'{self.__class__.__name__}({self.response!r})'<|docstring|>Returns the exception's representation.<|endoftext|>
50cd2751709c4358bc1bd791975cf748bfdabe4114ed95f89cd74a2012bd8bf3
@app.callback(dash.dependencies.Output('info-modal', 'is_open'), [dash.dependencies.Input('info-button', 'n_clicks'), dash.dependencies.Input('close-button', 'n_clicks')], [dash.dependencies.State('info-modal', 'is_open')]) def toggle_modal(n1, n2, is_open): 'Open and close info-box.' if (n1 or n2): return (not is_open) return is_open
Open and close info-box.
web_app.py
toggle_modal
mhcenic/object-detector-web-app
1
python
@app.callback(dash.dependencies.Output('info-modal', 'is_open'), [dash.dependencies.Input('info-button', 'n_clicks'), dash.dependencies.Input('close-button', 'n_clicks')], [dash.dependencies.State('info-modal', 'is_open')]) def toggle_modal(n1, n2, is_open): if (n1 or n2): return (not is_open) return is_open
@app.callback(dash.dependencies.Output('info-modal', 'is_open'), [dash.dependencies.Input('info-button', 'n_clicks'), dash.dependencies.Input('close-button', 'n_clicks')], [dash.dependencies.State('info-modal', 'is_open')]) def toggle_modal(n1, n2, is_open): if (n1 or n2): return (not is_open) return is_open<|docstring|>Open and close info-box.<|endoftext|>
0271152af0239df1e2fbc34d00cf0e365f44080f2f8a8d27248c315e194c8488
@app.callback(dash.dependencies.Output('image0', 'src'), [dash.dependencies.Input('image0-dropdown', 'value')]) def update_image_src(test_image): 'Show selected image.\n\n :param test_image: selected image name.\n :return: path to selected image.\n ' return (static_image_route + test_image)
Show selected image. :param test_image: selected image name. :return: path to selected image.
web_app.py
update_image_src
mhcenic/object-detector-web-app
1
python
@app.callback(dash.dependencies.Output('image0', 'src'), [dash.dependencies.Input('image0-dropdown', 'value')]) def update_image_src(test_image): 'Show selected image.\n\n :param test_image: selected image name.\n :return: path to selected image.\n ' return (static_image_route + test_image)
@app.callback(dash.dependencies.Output('image0', 'src'), [dash.dependencies.Input('image0-dropdown', 'value')]) def update_image_src(test_image): 'Show selected image.\n\n :param test_image: selected image name.\n :return: path to selected image.\n ' return (static_image_route + test_image)<|docstring|>Show selected image. :param test_image: selected image name. :return: path to selected image.<|endoftext|>
e935a0eba40207a58cd57e91bf4591284eddd96f427a48c0e1fa48c37ee42fdb
@app.server.route('{}<image_path>.jpg'.format(static_image_route)) def serve_image(image_path): 'Helper function to load test images.\n\n :param image_path: path to test images.\n :return: test image.\n ' image_name = '{}.jpg'.format(image_path) if (image_name not in TEST_IMAGE_LIST): raise Exception('"{}" is excluded from the allowed static files'.format(image_path)) return flask.send_from_directory(IMAGES_DIR, image_name)
Helper function to load test images. :param image_path: path to test images. :return: test image.
web_app.py
serve_image
mhcenic/object-detector-web-app
1
python
@app.server.route('{}<image_path>.jpg'.format(static_image_route)) def serve_image(image_path): 'Helper function to load test images.\n\n :param image_path: path to test images.\n :return: test image.\n ' image_name = '{}.jpg'.format(image_path) if (image_name not in TEST_IMAGE_LIST): raise Exception('"{}" is excluded from the allowed static files'.format(image_path)) return flask.send_from_directory(IMAGES_DIR, image_name)
@app.server.route('{}<image_path>.jpg'.format(static_image_route)) def serve_image(image_path): 'Helper function to load test images.\n\n :param image_path: path to test images.\n :return: test image.\n ' image_name = '{}.jpg'.format(image_path) if (image_name not in TEST_IMAGE_LIST): raise Exception('"{}" is excluded from the allowed static files'.format(image_path)) return flask.send_from_directory(IMAGES_DIR, image_name)<|docstring|>Helper function to load test images. :param image_path: path to test images. :return: test image.<|endoftext|>
0657755ec343b32381e126ad803d61751092f81a6b9d4cd398339a690be312c3
@app.callback(dash.dependencies.Output('image1', 'src'), [dash.dependencies.Input('image0-dropdown', 'value'), dash.dependencies.Input('my-slider', 'value')]) def run_script(test_image, slider): 'Run YOLO detector with params.\n\n :param test_image: selected test image.\n :param slider: minimum confidence threshold.\n :return: image after prediction.\n ' (boxes, scores, classes) = yolo_eval(yolo_outputs, input_image_shape, score_threshold=slider, iou_threshold=0.6) (image_data, image) = get_image(test_image, IMAGES_DIR, model_image_size) predict(sess, boxes, scores, classes, yolo_model, image_data, input_image_shape, image, test_image, class_names, colors, OUTPUT_DIR) encoded_image = base64.b64encode(open(('out/' + str(test_image)), 'rb').read()) return 'data:image/jpg;base64,{}'.format(encoded_image.decode())
Run YOLO detector with params. :param test_image: selected test image. :param slider: minimum confidence threshold. :return: image after prediction.
web_app.py
run_script
mhcenic/object-detector-web-app
1
python
@app.callback(dash.dependencies.Output('image1', 'src'), [dash.dependencies.Input('image0-dropdown', 'value'), dash.dependencies.Input('my-slider', 'value')]) def run_script(test_image, slider): 'Run YOLO detector with params.\n\n :param test_image: selected test image.\n :param slider: minimum confidence threshold.\n :return: image after prediction.\n ' (boxes, scores, classes) = yolo_eval(yolo_outputs, input_image_shape, score_threshold=slider, iou_threshold=0.6) (image_data, image) = get_image(test_image, IMAGES_DIR, model_image_size) predict(sess, boxes, scores, classes, yolo_model, image_data, input_image_shape, image, test_image, class_names, colors, OUTPUT_DIR) encoded_image = base64.b64encode(open(('out/' + str(test_image)), 'rb').read()) return 'data:image/jpg;base64,{}'.format(encoded_image.decode())
@app.callback(dash.dependencies.Output('image1', 'src'), [dash.dependencies.Input('image0-dropdown', 'value'), dash.dependencies.Input('my-slider', 'value')]) def run_script(test_image, slider): 'Run YOLO detector with params.\n\n :param test_image: selected test image.\n :param slider: minimum confidence threshold.\n :return: image after prediction.\n ' (boxes, scores, classes) = yolo_eval(yolo_outputs, input_image_shape, score_threshold=slider, iou_threshold=0.6) (image_data, image) = get_image(test_image, IMAGES_DIR, model_image_size) predict(sess, boxes, scores, classes, yolo_model, image_data, input_image_shape, image, test_image, class_names, colors, OUTPUT_DIR) encoded_image = base64.b64encode(open(('out/' + str(test_image)), 'rb').read()) return 'data:image/jpg;base64,{}'.format(encoded_image.decode())<|docstring|>Run YOLO detector with params. :param test_image: selected test image. :param slider: minimum confidence threshold. :return: image after prediction.<|endoftext|>
67651603a57d8d9331858ebf829dcb09de8f0a2a0e4698a4eb8db05434072044
def sleep(n): 'Sleep n seconds inside reactor without blocking other co-routines.\n :param n: float\n :return: Deferred()\n ' d = defer.Deferred() reactor.callLater(n, d.callback, True) return d
Sleep n seconds inside reactor without blocking other co-routines. :param n: float :return: Deferred()
python2+twisted/server.py
sleep
drednout/demo_apps
0
python
def sleep(n): 'Sleep n seconds inside reactor without blocking other co-routines.\n :param n: float\n :return: Deferred()\n ' d = defer.Deferred() reactor.callLater(n, d.callback, True) return d
def sleep(n): 'Sleep n seconds inside reactor without blocking other co-routines.\n :param n: float\n :return: Deferred()\n ' d = defer.Deferred() reactor.callLater(n, d.callback, True) return d<|docstring|>Sleep n seconds inside reactor without blocking other co-routines. :param n: float :return: Deferred()<|endoftext|>