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 |
|---|---|---|---|---|---|---|---|---|---|
c9087297e3357b70a572239dd247a9ada07320e2e5fa465915974ef7acd72a1a | def test_parse_grid_data(simple_grid):
'Test parse_grid_data method in Grid class'
assert (simple_grid.num_points == 8)
assert (simple_grid.dr == (0.1 / 7))
grid_conf2 = {'r_min': 0, 'r_max': 0.1, 'dr': (0.1 / 7)}
grid2 = Grid(grid_conf2)
assert (grid2.dr == (0.1 / 7))
assert (grid2.num_points == 8) | Test parse_grid_data method in Grid class | tests/test_core.py | test_parse_grid_data | kpf59/turbopy | 0 | python | def test_parse_grid_data(simple_grid):
assert (simple_grid.num_points == 8)
assert (simple_grid.dr == (0.1 / 7))
grid_conf2 = {'r_min': 0, 'r_max': 0.1, 'dr': (0.1 / 7)}
grid2 = Grid(grid_conf2)
assert (grid2.dr == (0.1 / 7))
assert (grid2.num_points == 8) | def test_parse_grid_data(simple_grid):
assert (simple_grid.num_points == 8)
assert (simple_grid.dr == (0.1 / 7))
grid_conf2 = {'r_min': 0, 'r_max': 0.1, 'dr': (0.1 / 7)}
grid2 = Grid(grid_conf2)
assert (grid2.dr == (0.1 / 7))
assert (grid2.num_points == 8)<|docstring|>Test parse_grid_data method in Grid class<|endoftext|> |
de79c423f7b6c9f48cad955e659ea0ddc82eeb05c0406e9eb8a478804d6c7041 | def test_set_value_from_keys(simple_grid):
'Test set_value_from_keys method in Grid class'
assert (simple_grid.r_min == 0)
assert (simple_grid.r_max == 0.1)
grid_conf1 = {'N': 8, 'r_min': 0}
with pytest.raises(Exception):
assert Grid(grid_conf1) | Test set_value_from_keys method in Grid class | tests/test_core.py | test_set_value_from_keys | kpf59/turbopy | 0 | python | def test_set_value_from_keys(simple_grid):
assert (simple_grid.r_min == 0)
assert (simple_grid.r_max == 0.1)
grid_conf1 = {'N': 8, 'r_min': 0}
with pytest.raises(Exception):
assert Grid(grid_conf1) | def test_set_value_from_keys(simple_grid):
assert (simple_grid.r_min == 0)
assert (simple_grid.r_max == 0.1)
grid_conf1 = {'N': 8, 'r_min': 0}
with pytest.raises(Exception):
assert Grid(grid_conf1)<|docstring|>Test set_value_from_keys method in Grid class<|endoftext|> |
b51e129067b903480835845f42a841b0ce6ad6e3366e185f1b7cb0b09f56558f | def test_generate_field(simple_grid):
'Test generate_field method in Grid class'
assert np.allclose(simple_grid.generate_field(), np.zeros(8))
assert np.allclose(simple_grid.generate_field(3), np.zeros((8, 3))) | Test generate_field method in Grid class | tests/test_core.py | test_generate_field | kpf59/turbopy | 0 | python | def test_generate_field(simple_grid):
assert np.allclose(simple_grid.generate_field(), np.zeros(8))
assert np.allclose(simple_grid.generate_field(3), np.zeros((8, 3))) | def test_generate_field(simple_grid):
assert np.allclose(simple_grid.generate_field(), np.zeros(8))
assert np.allclose(simple_grid.generate_field(3), np.zeros((8, 3)))<|docstring|>Test generate_field method in Grid class<|endoftext|> |
a20d02395b3c046e95b31917d3348cf2394fe8ca5eda9e3aaca75988cab913bd | def test_generate_linear(simple_grid):
'Test generate_linear method in Grid class'
comp = []
for i in range(simple_grid.num_points):
comp.append((i / (simple_grid.num_points - 1)))
assert np.allclose(simple_grid.generate_linear(), np.array(comp)) | Test generate_linear method in Grid class | tests/test_core.py | test_generate_linear | kpf59/turbopy | 0 | python | def test_generate_linear(simple_grid):
comp = []
for i in range(simple_grid.num_points):
comp.append((i / (simple_grid.num_points - 1)))
assert np.allclose(simple_grid.generate_linear(), np.array(comp)) | def test_generate_linear(simple_grid):
comp = []
for i in range(simple_grid.num_points):
comp.append((i / (simple_grid.num_points - 1)))
assert np.allclose(simple_grid.generate_linear(), np.array(comp))<|docstring|>Test generate_linear method in Grid class<|endoftext|> |
9bcc2a1f510ad5a78bc4ad3807f8d57372be39819f0cacf4fffc5e5783a92280 | def test_create_interpolator(simple_grid):
'Test create_interpolator method in Grid class'
field = simple_grid.generate_linear()
r_val = 0.05
interp = simple_grid.create_interpolator(r_val)
linear_value = (r_val / (simple_grid.r_max - simple_grid.r_min))
assert np.allclose(interp(field), linear_value) | Test create_interpolator method in Grid class | tests/test_core.py | test_create_interpolator | kpf59/turbopy | 0 | python | def test_create_interpolator(simple_grid):
field = simple_grid.generate_linear()
r_val = 0.05
interp = simple_grid.create_interpolator(r_val)
linear_value = (r_val / (simple_grid.r_max - simple_grid.r_min))
assert np.allclose(interp(field), linear_value) | def test_create_interpolator(simple_grid):
field = simple_grid.generate_linear()
r_val = 0.05
interp = simple_grid.create_interpolator(r_val)
linear_value = (r_val / (simple_grid.r_max - simple_grid.r_min))
assert np.allclose(interp(field), linear_value)<|docstring|>Test create_interpolator method in Grid class<|endoftext|> |
51782db44d3fdf8900651a33c5b85a61289656c0c2aebcf00ce5238a696a6717 | def test_set_cartesian_volumes():
'Test that cell volumes are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (edges[1:] - edges[0:(- 1)])
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (edges[1] - edges[0])
for i in range((edges.size - 2)):
volumes[(i + 1)] = (0.5 * (edges[(i + 2)] - edges[i]))
volumes[(- 1)] = (edges[(- 1)] - edges[(- 2)])
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | Test that cell volumes are set properly. | tests/test_core.py | test_set_cartesian_volumes | kpf59/turbopy | 0 | python | def test_set_cartesian_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (edges[1:] - edges[0:(- 1)])
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (edges[1] - edges[0])
for i in range((edges.size - 2)):
volumes[(i + 1)] = (0.5 * (edges[(i + 2)] - edges[i]))
volumes[(- 1)] = (edges[(- 1)] - edges[(- 2)])
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | def test_set_cartesian_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (edges[1:] - edges[0:(- 1)])
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (edges[1] - edges[0])
for i in range((edges.size - 2)):
volumes[(i + 1)] = (0.5 * (edges[(i + 2)] - edges[i]))
volumes[(- 1)] = (edges[(- 1)] - edges[(- 2)])
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes)<|docstring|>Test that cell volumes are set properly.<|endoftext|> |
f22789de1ced477f1d3a40e363f8544b1a836bf86ed1762a8d9e9bfbeb108460 | def test_set_cylindrical_volumes():
'Test that cell volumes are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (np.pi * ((edges[1:] ** 2) - (edges[0:(- 1)] ** 2)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (np.pi * ((edges[1] ** 2) - (edges[0] ** 2)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((0.5 * np.pi) * ((edges[(i + 2)] ** 2) - (edges[i] ** 2)))
volumes[(- 1)] = (np.pi * ((edges[(- 1)] ** 2) - (edges[(- 2)] ** 2)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | Test that cell volumes are set properly. | tests/test_core.py | test_set_cylindrical_volumes | kpf59/turbopy | 0 | python | def test_set_cylindrical_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (np.pi * ((edges[1:] ** 2) - (edges[0:(- 1)] ** 2)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (np.pi * ((edges[1] ** 2) - (edges[0] ** 2)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((0.5 * np.pi) * ((edges[(i + 2)] ** 2) - (edges[i] ** 2)))
volumes[(- 1)] = (np.pi * ((edges[(- 1)] ** 2) - (edges[(- 2)] ** 2)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | def test_set_cylindrical_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (np.pi * ((edges[1:] ** 2) - (edges[0:(- 1)] ** 2)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (np.pi * ((edges[1] ** 2) - (edges[0] ** 2)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((0.5 * np.pi) * ((edges[(i + 2)] ** 2) - (edges[i] ** 2)))
volumes[(- 1)] = (np.pi * ((edges[(- 1)] ** 2) - (edges[(- 2)] ** 2)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes)<|docstring|>Test that cell volumes are set properly.<|endoftext|> |
e966a5806c38ab96ff738e483f3a3cbf9ea6e1b331d98bba852d951598e773c8 | def test_set_spherical_volumes():
'Test that cell volumes are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (((4 / 3) * np.pi) * ((edges[1:] ** 3) - (edges[0:(- 1)] ** 3)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (((4 / 3) * np.pi) * ((edges[1] ** 3) - (edges[0] ** 3)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((((0.5 * 4) / 3) * np.pi) * ((edges[(i + 2)] ** 3) - (edges[i] ** 3)))
volumes[(- 1)] = (((4 / 3) * np.pi) * ((edges[(- 1)] ** 3) - (edges[(- 2)] ** 3)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | Test that cell volumes are set properly. | tests/test_core.py | test_set_spherical_volumes | kpf59/turbopy | 0 | python | def test_set_spherical_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (((4 / 3) * np.pi) * ((edges[1:] ** 3) - (edges[0:(- 1)] ** 3)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (((4 / 3) * np.pi) * ((edges[1] ** 3) - (edges[0] ** 3)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((((0.5 * 4) / 3) * np.pi) * ((edges[(i + 2)] ** 3) - (edges[i] ** 3)))
volumes[(- 1)] = (((4 / 3) * np.pi) * ((edges[(- 1)] ** 3) - (edges[(- 2)] ** 3)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes) | def test_set_spherical_volumes():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
volumes = (((4 / 3) * np.pi) * ((edges[1:] ** 3) - (edges[0:(- 1)] ** 3)))
assert (grid2.cell_volumes.size == volumes.size)
assert np.allclose(grid2.cell_volumes, volumes)
volumes = np.zeros_like(edges)
volumes[0] = (((4 / 3) * np.pi) * ((edges[1] ** 3) - (edges[0] ** 3)))
for i in range((edges.size - 2)):
volumes[(i + 1)] = ((((0.5 * 4) / 3) * np.pi) * ((edges[(i + 2)] ** 3) - (edges[i] ** 3)))
volumes[(- 1)] = (((4 / 3) * np.pi) * ((edges[(- 1)] ** 3) - (edges[(- 2)] ** 3)))
assert (grid2.interface_volumes.size == volumes.size)
assert np.allclose(grid2.interface_volumes, volumes)<|docstring|>Test that cell volumes are set properly.<|endoftext|> |
80ce226f885be6aa1c8ecd1b4b8f29088818f799a98dd12d1ec8240f155a5564 | def test_set_cartesian_areas():
'Test that cell areas are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
areas = np.ones_like(grid2.interface_areas)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | Test that cell areas are set properly. | tests/test_core.py | test_set_cartesian_areas | kpf59/turbopy | 0 | python | def test_set_cartesian_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
areas = np.ones_like(grid2.interface_areas)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | def test_set_cartesian_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cartesian'}
grid2 = Grid(grid_conf2)
areas = np.ones_like(grid2.interface_areas)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas)<|docstring|>Test that cell areas are set properly.<|endoftext|> |
4895d02267635d333365bf4f209e8fe345eae632e9e24025032f04aeda909a46 | def test_set_cylindrical_areas():
'Test that cell areas are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = ((2.0 * np.pi) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | Test that cell areas are set properly. | tests/test_core.py | test_set_cylindrical_areas | kpf59/turbopy | 0 | python | def test_set_cylindrical_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = ((2.0 * np.pi) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | def test_set_cylindrical_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'cylindrical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = ((2.0 * np.pi) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas)<|docstring|>Test that cell areas are set properly.<|endoftext|> |
51d400da37e975cdf138231826252dcdf94bd4cdd782e045ebf14f4208ec0372 | def test_set_spherical_areas():
'Test that cell areas are set properly.'
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = (((4.0 * np.pi) * edges) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | Test that cell areas are set properly. | tests/test_core.py | test_set_spherical_areas | kpf59/turbopy | 0 | python | def test_set_spherical_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = (((4.0 * np.pi) * edges) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas) | def test_set_spherical_areas():
grid_conf2 = {'r_min': 0, 'r_max': 1, 'dr': 0.1, 'coordinate_system': 'spherical'}
grid2 = Grid(grid_conf2)
edges = grid2.cell_edges
areas = (((4.0 * np.pi) * edges) * edges)
assert (grid2.interface_areas.size == areas.size)
assert np.allclose(grid2.interface_areas, areas)<|docstring|>Test that cell areas are set properly.<|endoftext|> |
b68380e6f577aafc9f8cac898883749691d5a92296a60d80dd1f9284d0bef9b8 | def test_integer_num_steps():
'Tests for initialization of SimulationClock'
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 10.5), 'print_time': True}
with pytest.raises(RuntimeError):
SimulationClock(Simulation({}), clock_config) | Tests for initialization of SimulationClock | tests/test_core.py | test_integer_num_steps | kpf59/turbopy | 0 | python | def test_integer_num_steps():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 10.5), 'print_time': True}
with pytest.raises(RuntimeError):
SimulationClock(Simulation({}), clock_config) | def test_integer_num_steps():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 10.5), 'print_time': True}
with pytest.raises(RuntimeError):
SimulationClock(Simulation({}), clock_config)<|docstring|>Tests for initialization of SimulationClock<|endoftext|> |
69ae9dcbbe77ea76ad403e4e394998ce54367db26e7f21bba01295d964549eb2 | def test_advance():
'Tests `advance` method of the SimulationClock class'
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'num_steps': 20, 'print_time': True}
clock1 = SimulationClock(Simulation({}), clock_config)
assert (clock1.num_steps == ((clock1.end_time - clock1.start_time) / clock1.dt))
clock1.advance()
assert (clock1.this_step == 1)
assert (clock1.time == (clock1.start_time + (clock1.dt * clock1.this_step))) | Tests `advance` method of the SimulationClock class | tests/test_core.py | test_advance | kpf59/turbopy | 0 | python | def test_advance():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'num_steps': 20, 'print_time': True}
clock1 = SimulationClock(Simulation({}), clock_config)
assert (clock1.num_steps == ((clock1.end_time - clock1.start_time) / clock1.dt))
clock1.advance()
assert (clock1.this_step == 1)
assert (clock1.time == (clock1.start_time + (clock1.dt * clock1.this_step))) | def test_advance():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'num_steps': 20, 'print_time': True}
clock1 = SimulationClock(Simulation({}), clock_config)
assert (clock1.num_steps == ((clock1.end_time - clock1.start_time) / clock1.dt))
clock1.advance()
assert (clock1.this_step == 1)
assert (clock1.time == (clock1.start_time + (clock1.dt * clock1.this_step)))<|docstring|>Tests `advance` method of the SimulationClock class<|endoftext|> |
49e63474dba98a5ba14a2db37cb5951501f8bf04ad272d0772c4e5017ba30d85 | def test_is_running():
'Tests `is_running` method of the SimulationClock class'
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 20), 'print_time': True}
clock2 = SimulationClock(Simulation({}), clock_config)
assert (clock2.num_steps == 20)
assert (clock2.is_running() and (clock2.this_step < clock2.num_steps))
for i in range(clock2.num_steps):
clock2.advance()
assert (not clock2.is_running()) | Tests `is_running` method of the SimulationClock class | tests/test_core.py | test_is_running | kpf59/turbopy | 0 | python | def test_is_running():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 20), 'print_time': True}
clock2 = SimulationClock(Simulation({}), clock_config)
assert (clock2.num_steps == 20)
assert (clock2.is_running() and (clock2.this_step < clock2.num_steps))
for i in range(clock2.num_steps):
clock2.advance()
assert (not clock2.is_running()) | def test_is_running():
clock_config = {'start_time': 0.0, 'end_time': 1e-08, 'dt': (1e-08 / 20), 'print_time': True}
clock2 = SimulationClock(Simulation({}), clock_config)
assert (clock2.num_steps == 20)
assert (clock2.is_running() and (clock2.this_step < clock2.num_steps))
for i in range(clock2.num_steps):
clock2.advance()
assert (not clock2.is_running())<|docstring|>Tests `is_running` method of the SimulationClock class<|endoftext|> |
0c42425c2d3a50d6f535773494c588ea825a700f9b49710d74689574e8baed4e | def urijoin(*args):
'Joins given arguments into a URI.\n :returns: a URI string\n '
return '/'.join(map((lambda x: str(x).strip('/')), args)) | Joins given arguments into a URI.
:returns: a URI string | groupsio_subscriptions.py | urijoin | LF-Engineering/perceval-scripts | 2 | python | def urijoin(*args):
'Joins given arguments into a URI.\n :returns: a URI string\n '
return '/'.join(map((lambda x: str(x).strip('/')), args)) | def urijoin(*args):
'Joins given arguments into a URI.\n :returns: a URI string\n '
return '/'.join(map((lambda x: str(x).strip('/')), args))<|docstring|>Joins given arguments into a URI.
:returns: a URI string<|endoftext|> |
7a64065814522b3e23e93a0894e7f742287d3e1e9fd7e979e23a2a0924dc60ee | def fetch(url, payload, auth):
'Fetch requests from groupsio API'
r = requests.get(url, params=payload, auth=auth)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise e
return r | Fetch requests from groupsio API | groupsio_subscriptions.py | fetch | LF-Engineering/perceval-scripts | 2 | python | def fetch(url, payload, auth):
r = requests.get(url, params=payload, auth=auth)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise e
return r | def fetch(url, payload, auth):
r = requests.get(url, params=payload, auth=auth)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise e
return r<|docstring|>Fetch requests from groupsio API<|endoftext|> |
c22870875f213519b8624b419d7a361fda1ed2eae5b01cd3f4beef4e1f45d8f3 | @staticmethod
def parse_image(im, model):
'Parses graph image downloaded from innerfidelity.com'
box = (69, 31, 550, 290)
im = im.crop(box)
px_a_max = 0
px_a_min = im.size[1]
f_min = 20
f_max = 20000
f_step = ((f_max / f_min) ** (1 / im.size[0]))
f = [f_min]
for _ in range(1, im.size[0]):
f.append((f[(- 1)] * f_step))
a_max = 150
a_min = 66
a_res = ((a_max - a_min) / (px_a_min - px_a_max))
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 203, 206, 0.8, 1.0, a_max, a_res)
if (len([x for x in amplitude if (x is None)]) >= (0.5 * len(amplitude))):
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 119, 121, 0.8, 1.0, a_max, a_res)
draw = ImageDraw.Draw(_im)
x0 = (np.log((30 / f_min)) / np.log(f_step))
x1 = (np.log((10000 / f_min)) / np.log(f_step))
y_0 = (px_a_max + (12 / a_res))
y_1 = (px_a_min - (12 / a_res))
draw.rectangle(((x0, y_0), (x1, y_1)), outline='magenta')
draw.rectangle((((x0 + 1), (y_0 + 1)), ((x1 - 1), (y_1 - 1))), outline='magenta')
fr = FrequencyResponse(model, f, amplitude)
fr.interpolate()
if (len(fr.frequency) < 2):
im.show()
raise ValueError(f'Failed to parse image for {fr.name}')
fr.smoothen_fractional_octave(window_size=(1 / 3), treble_window_size=(1 / 3))
fr.raw = fr.smoothed.copy()
fr.smoothed = np.array([])
fr.center()
return (fr, _im) | Parses graph image downloaded from innerfidelity.com | measurements/referenceaudioanalyzer/reference_audio_analyzer_crawler.py | parse_image | eliMakeouthill/AutoEq | 3 | python | @staticmethod
def parse_image(im, model):
box = (69, 31, 550, 290)
im = im.crop(box)
px_a_max = 0
px_a_min = im.size[1]
f_min = 20
f_max = 20000
f_step = ((f_max / f_min) ** (1 / im.size[0]))
f = [f_min]
for _ in range(1, im.size[0]):
f.append((f[(- 1)] * f_step))
a_max = 150
a_min = 66
a_res = ((a_max - a_min) / (px_a_min - px_a_max))
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 203, 206, 0.8, 1.0, a_max, a_res)
if (len([x for x in amplitude if (x is None)]) >= (0.5 * len(amplitude))):
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 119, 121, 0.8, 1.0, a_max, a_res)
draw = ImageDraw.Draw(_im)
x0 = (np.log((30 / f_min)) / np.log(f_step))
x1 = (np.log((10000 / f_min)) / np.log(f_step))
y_0 = (px_a_max + (12 / a_res))
y_1 = (px_a_min - (12 / a_res))
draw.rectangle(((x0, y_0), (x1, y_1)), outline='magenta')
draw.rectangle((((x0 + 1), (y_0 + 1)), ((x1 - 1), (y_1 - 1))), outline='magenta')
fr = FrequencyResponse(model, f, amplitude)
fr.interpolate()
if (len(fr.frequency) < 2):
im.show()
raise ValueError(f'Failed to parse image for {fr.name}')
fr.smoothen_fractional_octave(window_size=(1 / 3), treble_window_size=(1 / 3))
fr.raw = fr.smoothed.copy()
fr.smoothed = np.array([])
fr.center()
return (fr, _im) | @staticmethod
def parse_image(im, model):
box = (69, 31, 550, 290)
im = im.crop(box)
px_a_max = 0
px_a_min = im.size[1]
f_min = 20
f_max = 20000
f_step = ((f_max / f_min) ** (1 / im.size[0]))
f = [f_min]
for _ in range(1, im.size[0]):
f.append((f[(- 1)] * f_step))
a_max = 150
a_min = 66
a_res = ((a_max - a_min) / (px_a_min - px_a_max))
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 203, 206, 0.8, 1.0, a_max, a_res)
if (len([x for x in amplitude if (x is None)]) >= (0.5 * len(amplitude))):
_im = im.copy()
inspection = _im.load()
(amplitude, _im, _inspection) = ReferenceAudioAnalyzerCrawler.find_curve(_im, inspection, 119, 121, 0.8, 1.0, a_max, a_res)
draw = ImageDraw.Draw(_im)
x0 = (np.log((30 / f_min)) / np.log(f_step))
x1 = (np.log((10000 / f_min)) / np.log(f_step))
y_0 = (px_a_max + (12 / a_res))
y_1 = (px_a_min - (12 / a_res))
draw.rectangle(((x0, y_0), (x1, y_1)), outline='magenta')
draw.rectangle((((x0 + 1), (y_0 + 1)), ((x1 - 1), (y_1 - 1))), outline='magenta')
fr = FrequencyResponse(model, f, amplitude)
fr.interpolate()
if (len(fr.frequency) < 2):
im.show()
raise ValueError(f'Failed to parse image for {fr.name}')
fr.smoothen_fractional_octave(window_size=(1 / 3), treble_window_size=(1 / 3))
fr.raw = fr.smoothed.copy()
fr.smoothed = np.array([])
fr.center()
return (fr, _im)<|docstring|>Parses graph image downloaded from innerfidelity.com<|endoftext|> |
b199ab05019be6f91799ef71ed9eaa91b307dbd0854d8e15449c2707615bb35b | @app.cli.command()
def test():
'Run the unit tests.'
import unittest
tests = unittest.TestLoader().discover('tests')
testresult = unittest.TextTestRunner(verbosity=2).run(tests)
if testresult.wasSuccessful():
exit(0)
else:
exit(1) | Run the unit tests. | app.py | test | UST-QuAntiL/Quokka | 0 | python | @app.cli.command()
def test():
import unittest
tests = unittest.TestLoader().discover('tests')
testresult = unittest.TextTestRunner(verbosity=2).run(tests)
if testresult.wasSuccessful():
exit(0)
else:
exit(1) | @app.cli.command()
def test():
import unittest
tests = unittest.TestLoader().discover('tests')
testresult = unittest.TextTestRunner(verbosity=2).run(tests)
if testresult.wasSuccessful():
exit(0)
else:
exit(1)<|docstring|>Run the unit tests.<|endoftext|> |
e9a2558c9dfd6932fb851464016c857d9b6ac4bc0f3cc03e9df3e151c53dc253 | def remove_refct_calls(func):
'\n Remove redundant incref/decref within on a per block basis\n '
for bb in func.basic_blocks:
remove_null_refct_call(bb)
remove_refct_pairs(bb) | Remove redundant incref/decref within on a per block basis | numba/targets/cpu.py | remove_refct_calls | SPIRV/NUMBA | 4 | python | def remove_refct_calls(func):
'\n \n '
for bb in func.basic_blocks:
remove_null_refct_call(bb)
remove_refct_pairs(bb) | def remove_refct_calls(func):
'\n \n '
for bb in func.basic_blocks:
remove_null_refct_call(bb)
remove_refct_pairs(bb)<|docstring|>Remove redundant incref/decref within on a per block basis<|endoftext|> |
5ba2051cce6f30ebd6380883a6b84c1654f15178e9a3a02413a5cf861d325768 | def remove_null_refct_call(bb):
'\n Remove refct api calls to NULL pointer\n '
pass | Remove refct api calls to NULL pointer | numba/targets/cpu.py | remove_null_refct_call | SPIRV/NUMBA | 4 | python | def remove_null_refct_call(bb):
'\n \n '
pass | def remove_null_refct_call(bb):
'\n \n '
pass<|docstring|>Remove refct api calls to NULL pointer<|endoftext|> |
9be760e972dd88926d29282337e2fa577673817a86a56562858308f9e14b1b41 | def remove_refct_pairs(bb):
'\n Remove incref decref pairs on the same variable\n '
didsomething = True
while didsomething:
didsomething = False
increfs = {}
decrefs = {}
for inst in bb.instructions:
if isinstance(inst, lc.CallOrInvokeInstruction):
fname = inst.called_function.name
if (fname == 'Py_IncRef'):
arg = inst.operands[0]
increfs[arg] = inst
elif (fname == 'Py_DecRef'):
arg = inst.operands[0]
decrefs[arg] = inst
for val in increfs.keys():
if (val in decrefs):
increfs[val].erase_from_parent()
decrefs[val].erase_from_parent()
didsomething = True | Remove incref decref pairs on the same variable | numba/targets/cpu.py | remove_refct_pairs | SPIRV/NUMBA | 4 | python | def remove_refct_pairs(bb):
'\n \n '
didsomething = True
while didsomething:
didsomething = False
increfs = {}
decrefs = {}
for inst in bb.instructions:
if isinstance(inst, lc.CallOrInvokeInstruction):
fname = inst.called_function.name
if (fname == 'Py_IncRef'):
arg = inst.operands[0]
increfs[arg] = inst
elif (fname == 'Py_DecRef'):
arg = inst.operands[0]
decrefs[arg] = inst
for val in increfs.keys():
if (val in decrefs):
increfs[val].erase_from_parent()
decrefs[val].erase_from_parent()
didsomething = True | def remove_refct_pairs(bb):
'\n \n '
didsomething = True
while didsomething:
didsomething = False
increfs = {}
decrefs = {}
for inst in bb.instructions:
if isinstance(inst, lc.CallOrInvokeInstruction):
fname = inst.called_function.name
if (fname == 'Py_IncRef'):
arg = inst.operands[0]
increfs[arg] = inst
elif (fname == 'Py_DecRef'):
arg = inst.operands[0]
decrefs[arg] = inst
for val in increfs.keys():
if (val in decrefs):
increfs[val].erase_from_parent()
decrefs[val].erase_from_parent()
didsomething = True<|docstring|>Remove incref decref pairs on the same variable<|endoftext|> |
57b5cc44beb79a17cb96c4fae49d3e06e8b1fc96dd809b28aecd9a9f7aa6fc70 | def get_env_from_closure(self, builder, clo):
'\n From the pointer *clo* to a _dynfunc.Closure, get a pointer\n to the enclosed _dynfunc.Environment.\n '
with cgutils.if_unlikely(builder, cgutils.is_null(builder, clo)):
self.debug_print(builder, 'Fatal error: missing _dynfunc.Closure')
builder.unreachable()
clo_body_ptr = cgutils.pointer_add(builder, clo, _dynfunc._impl_info['offsetof_closure_body'])
clo_body = ClosureBody(self, builder, ref=clo_body_ptr, cast_ref=True)
return clo_body.env | From the pointer *clo* to a _dynfunc.Closure, get a pointer
to the enclosed _dynfunc.Environment. | numba/targets/cpu.py | get_env_from_closure | SPIRV/NUMBA | 4 | python | def get_env_from_closure(self, builder, clo):
'\n From the pointer *clo* to a _dynfunc.Closure, get a pointer\n to the enclosed _dynfunc.Environment.\n '
with cgutils.if_unlikely(builder, cgutils.is_null(builder, clo)):
self.debug_print(builder, 'Fatal error: missing _dynfunc.Closure')
builder.unreachable()
clo_body_ptr = cgutils.pointer_add(builder, clo, _dynfunc._impl_info['offsetof_closure_body'])
clo_body = ClosureBody(self, builder, ref=clo_body_ptr, cast_ref=True)
return clo_body.env | def get_env_from_closure(self, builder, clo):
'\n From the pointer *clo* to a _dynfunc.Closure, get a pointer\n to the enclosed _dynfunc.Environment.\n '
with cgutils.if_unlikely(builder, cgutils.is_null(builder, clo)):
self.debug_print(builder, 'Fatal error: missing _dynfunc.Closure')
builder.unreachable()
clo_body_ptr = cgutils.pointer_add(builder, clo, _dynfunc._impl_info['offsetof_closure_body'])
clo_body = ClosureBody(self, builder, ref=clo_body_ptr, cast_ref=True)
return clo_body.env<|docstring|>From the pointer *clo* to a _dynfunc.Closure, get a pointer
to the enclosed _dynfunc.Environment.<|endoftext|> |
084d7d1439935894733a6829bf541e1128ac98df79ea8126a40419d534ea7606 | def get_env_body(self, builder, envptr):
'\n From the given *envptr* (a pointer to a _dynfunc.Environment object),\n get a EnvBody allowing structured access to environment fields.\n '
body_ptr = cgutils.pointer_add(builder, envptr, _dynfunc._impl_info['offsetof_env_body'])
return EnvBody(self, builder, ref=body_ptr, cast_ref=True) | From the given *envptr* (a pointer to a _dynfunc.Environment object),
get a EnvBody allowing structured access to environment fields. | numba/targets/cpu.py | get_env_body | SPIRV/NUMBA | 4 | python | def get_env_body(self, builder, envptr):
'\n From the given *envptr* (a pointer to a _dynfunc.Environment object),\n get a EnvBody allowing structured access to environment fields.\n '
body_ptr = cgutils.pointer_add(builder, envptr, _dynfunc._impl_info['offsetof_env_body'])
return EnvBody(self, builder, ref=body_ptr, cast_ref=True) | def get_env_body(self, builder, envptr):
'\n From the given *envptr* (a pointer to a _dynfunc.Environment object),\n get a EnvBody allowing structured access to environment fields.\n '
body_ptr = cgutils.pointer_add(builder, envptr, _dynfunc._impl_info['offsetof_env_body'])
return EnvBody(self, builder, ref=body_ptr, cast_ref=True)<|docstring|>From the given *envptr* (a pointer to a _dynfunc.Environment object),
get a EnvBody allowing structured access to environment fields.<|endoftext|> |
ffdb813a2cbe0072ee021bf825ea3bdf5393851761bb48241a202165f429f5fc | def get_generator_state(self, builder, genptr, return_type):
'\n From the given *genptr* (a pointer to a _dynfunc.Generator object),\n get a pointer to its state area.\n '
return cgutils.pointer_add(builder, genptr, _dynfunc._impl_info['offsetof_generator_state'], return_type=return_type) | From the given *genptr* (a pointer to a _dynfunc.Generator object),
get a pointer to its state area. | numba/targets/cpu.py | get_generator_state | SPIRV/NUMBA | 4 | python | def get_generator_state(self, builder, genptr, return_type):
'\n From the given *genptr* (a pointer to a _dynfunc.Generator object),\n get a pointer to its state area.\n '
return cgutils.pointer_add(builder, genptr, _dynfunc._impl_info['offsetof_generator_state'], return_type=return_type) | def get_generator_state(self, builder, genptr, return_type):
'\n From the given *genptr* (a pointer to a _dynfunc.Generator object),\n get a pointer to its state area.\n '
return cgutils.pointer_add(builder, genptr, _dynfunc._impl_info['offsetof_generator_state'], return_type=return_type)<|docstring|>From the given *genptr* (a pointer to a _dynfunc.Generator object),
get a pointer to its state area.<|endoftext|> |
48b9a8ce74ca4d057b48f8560ff1f131d27dca6c5ad07f7eadd843ba50fa19a9 | def build_list(self, builder, list_type, items):
'\n Build a list from the Numba *list_type* and its initial *items*.\n '
return listobj.build_list(self, builder, list_type, items) | Build a list from the Numba *list_type* and its initial *items*. | numba/targets/cpu.py | build_list | SPIRV/NUMBA | 4 | python | def build_list(self, builder, list_type, items):
'\n \n '
return listobj.build_list(self, builder, list_type, items) | def build_list(self, builder, list_type, items):
'\n \n '
return listobj.build_list(self, builder, list_type, items)<|docstring|>Build a list from the Numba *list_type* and its initial *items*.<|endoftext|> |
554585819c0a72829df163680e55ccaaf22aff2e5d85a7672c7beca65d90c236 | def build_set(self, builder, set_type, items):
'\n Build a set from the Numba *set_type* and its initial *items*.\n '
return setobj.build_set(self, builder, set_type, items) | Build a set from the Numba *set_type* and its initial *items*. | numba/targets/cpu.py | build_set | SPIRV/NUMBA | 4 | python | def build_set(self, builder, set_type, items):
'\n \n '
return setobj.build_set(self, builder, set_type, items) | def build_set(self, builder, set_type, items):
'\n \n '
return setobj.build_set(self, builder, set_type, items)<|docstring|>Build a set from the Numba *set_type* and its initial *items*.<|endoftext|> |
8b714fdeed37f89b59c9d579e82db9606141ede9e178bd793b50a1304e08e747 | def get_executable(self, library, fndesc, env):
'\n Returns\n -------\n (cfunc, fnptr)\n\n - cfunc\n callable function (Can be None)\n - fnptr\n callable function address\n - env\n an execution environment (from _dynfunc)\n '
baseptr = library.get_pointer_to_function(fndesc.llvm_func_name)
fnptr = library.get_pointer_to_function(fndesc.llvm_cpython_wrapper_name)
doc = ('compiled wrapper for %r' % (fndesc.qualname,))
cfunc = _dynfunc.make_function(fndesc.lookup_module(), fndesc.qualname.split('.')[(- 1)], doc, fnptr, env, (library,))
return cfunc | Returns
-------
(cfunc, fnptr)
- cfunc
callable function (Can be None)
- fnptr
callable function address
- env
an execution environment (from _dynfunc) | numba/targets/cpu.py | get_executable | SPIRV/NUMBA | 4 | python | def get_executable(self, library, fndesc, env):
'\n Returns\n -------\n (cfunc, fnptr)\n\n - cfunc\n callable function (Can be None)\n - fnptr\n callable function address\n - env\n an execution environment (from _dynfunc)\n '
baseptr = library.get_pointer_to_function(fndesc.llvm_func_name)
fnptr = library.get_pointer_to_function(fndesc.llvm_cpython_wrapper_name)
doc = ('compiled wrapper for %r' % (fndesc.qualname,))
cfunc = _dynfunc.make_function(fndesc.lookup_module(), fndesc.qualname.split('.')[(- 1)], doc, fnptr, env, (library,))
return cfunc | def get_executable(self, library, fndesc, env):
'\n Returns\n -------\n (cfunc, fnptr)\n\n - cfunc\n callable function (Can be None)\n - fnptr\n callable function address\n - env\n an execution environment (from _dynfunc)\n '
baseptr = library.get_pointer_to_function(fndesc.llvm_func_name)
fnptr = library.get_pointer_to_function(fndesc.llvm_cpython_wrapper_name)
doc = ('compiled wrapper for %r' % (fndesc.qualname,))
cfunc = _dynfunc.make_function(fndesc.lookup_module(), fndesc.qualname.split('.')[(- 1)], doc, fnptr, env, (library,))
return cfunc<|docstring|>Returns
-------
(cfunc, fnptr)
- cfunc
callable function (Can be None)
- fnptr
callable function address
- env
an execution environment (from _dynfunc)<|endoftext|> |
159ecc1aab61627f2780b9482ae046af844399ab8c8b9259384064f38b853a2f | def calc_array_sizeof(self, ndim):
'\n Calculate the size of an array struct on the CPU target\n '
aryty = types.Array(types.int32, ndim, 'A')
return self.get_abi_sizeof(self.get_value_type(aryty)) | Calculate the size of an array struct on the CPU target | numba/targets/cpu.py | calc_array_sizeof | SPIRV/NUMBA | 4 | python | def calc_array_sizeof(self, ndim):
'\n \n '
aryty = types.Array(types.int32, ndim, 'A')
return self.get_abi_sizeof(self.get_value_type(aryty)) | def calc_array_sizeof(self, ndim):
'\n \n '
aryty = types.Array(types.int32, ndim, 'A')
return self.get_abi_sizeof(self.get_value_type(aryty))<|docstring|>Calculate the size of an array struct on the CPU target<|endoftext|> |
b75317cd2cae015ed3565aa6132c25d2dc1f6fde96eafaf182330840b6cf13c9 | def get_validate_image(request_session):
'\n Get validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return "" if fail\n '
headers = {'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8', 'Referer': 'https://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = request_session.get(GET_IMAGE_URL, headers=headers)
if (code != 0):
return (code, key, '')
return (0, 'success', resp) | Get validate image
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_validate_image | Svolcano/python_exercise | 6 | python | def get_validate_image(request_session):
'\n Get validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return if fail\n '
headers = {'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8', 'Referer': 'https://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = request_session.get(GET_IMAGE_URL, headers=headers)
if (code != 0):
return (code, key, )
return (0, 'success', resp) | def get_validate_image(request_session):
'\n Get validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return if fail\n '
headers = {'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8', 'Referer': 'https://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = request_session.get(GET_IMAGE_URL, headers=headers)
if (code != 0):
return (code, key, )
return (0, 'success', resp)<|docstring|>Get validate image
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail<|endoftext|> |
9316c52fe0dec8df04de302d082a641fea43f0e512678ad9066a2e087a7c5b51 | def refresh_validate_image(request_session):
'\n 该函数已废弃\n Get another validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return "" if fail\n '
(code, key, resp) = request_session.get(REFRESH_IMAGE_URL)
if (code != 0):
return (code, key, '')
return (0, 'success', base64.b64encode(resp.content)) | 该函数已废弃
Get another validate image
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | refresh_validate_image | Svolcano/python_exercise | 6 | python | def refresh_validate_image(request_session):
'\n 该函数已废弃\n Get another validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return if fail\n '
(code, key, resp) = request_session.get(REFRESH_IMAGE_URL)
if (code != 0):
return (code, key, )
return (0, 'success', base64.b64encode(resp.content)) | def refresh_validate_image(request_session):
'\n 该函数已废弃\n Get another validate image\n :param request_session: Requests session\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n image_str: str, Raw byte of Captcha in base64 format, return if fail\n '
(code, key, resp) = request_session.get(REFRESH_IMAGE_URL)
if (code != 0):
return (code, key, )
return (0, 'success', base64.b64encode(resp.content))<|docstring|>该函数已废弃
Get another validate image
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail<|endoftext|> |
6405a30460740bf7a5f675c58c1097c25e5d15abcd1539becafc590d34868b43 | def is_cq_local_number(tel, requests):
'\n Verify if the target tel number is a cq local number\n :param tel: Tel number\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
headers = {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Referer': 'http://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = requests.get(url=ICS_SERVICE_URL, params=get_check_cq_local_param(str(tel)), headers=headers)
if (code != 0):
return (code, key, '')
try:
root = etree.fromstring(resp.text.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'request_error', 'No dataset error')
else:
return (0, 'success', json.loads(return_dataset[0].text)[0]['FLAG'])
except:
error = traceback.format_exc()
return (9, 'xml_error', error) | Verify if the target tel number is a cq local number
:param tel: Tel number
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | is_cq_local_number | Svolcano/python_exercise | 6 | python | def is_cq_local_number(tel, requests):
'\n Verify if the target tel number is a cq local number\n :param tel: Tel number\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
headers = {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Referer': 'http://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = requests.get(url=ICS_SERVICE_URL, params=get_check_cq_local_param(str(tel)), headers=headers)
if (code != 0):
return (code, key, )
try:
root = etree.fromstring(resp.text.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'request_error', 'No dataset error')
else:
return (0, 'success', json.loads(return_dataset[0].text)[0]['FLAG'])
except:
error = traceback.format_exc()
return (9, 'xml_error', error) | def is_cq_local_number(tel, requests):
'\n Verify if the target tel number is a cq local number\n :param tel: Tel number\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
headers = {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Referer': 'http://service.cq.10086.cn/httpsFiles/pageLogin.html'}
(code, key, resp) = requests.get(url=ICS_SERVICE_URL, params=get_check_cq_local_param(str(tel)), headers=headers)
if (code != 0):
return (code, key, )
try:
root = etree.fromstring(resp.text.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'request_error', 'No dataset error')
else:
return (0, 'success', json.loads(return_dataset[0].text)[0]['FLAG'])
except:
error = traceback.format_exc()
return (9, 'xml_error', error)<|docstring|>Verify if the target tel number is a cq local number
:param tel: Tel number
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message<|endoftext|> |
0f09f57e26ade20dd34ee96dd17f37242f1718c2f48296c195af2acbdc17796f | def is_validate(user_id, user_password, picture_validate_code, requests):
'\n Check if the target tel, password, code are valid\n :param user_id: Tel number\n :param user_password: Password\n :param picture_validate_code: code in Capcha image\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
if (len(picture_validate_code) < 4):
return (2, 'verify_error', '您输入的校验码不足4位,请重新填写。'.decode('UTF-8'))
elif (len(user_password) < 6):
return (1, 'pin_pwd_error', '您输入的密码不足6位,请重新填写。'.decode('UTF-8'))
elif (len(user_id) < 11):
return (1, 'invalid_tel', '您输入的的手机号码不足11位,请重新填写。'.decode('UTF-8'))
(level, key, message) = is_cq_local_number(user_id, requests)
if (level != 0):
return (level, key, message)
elif (message == 'false'):
return (1, 'invalid_tel', 'Not a valid cq tel number'.decode('UTF-8'))
elif (message == 'true'):
return (0, 'success', 'True')
else:
return (9, 'unknown_error', u'unknown return format') | Check if the target tel, password, code are valid
:param user_id: Tel number
:param user_password: Password
:param picture_validate_code: code in Capcha image
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | is_validate | Svolcano/python_exercise | 6 | python | def is_validate(user_id, user_password, picture_validate_code, requests):
'\n Check if the target tel, password, code are valid\n :param user_id: Tel number\n :param user_password: Password\n :param picture_validate_code: code in Capcha image\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
if (len(picture_validate_code) < 4):
return (2, 'verify_error', '您输入的校验码不足4位,请重新填写。'.decode('UTF-8'))
elif (len(user_password) < 6):
return (1, 'pin_pwd_error', '您输入的密码不足6位,请重新填写。'.decode('UTF-8'))
elif (len(user_id) < 11):
return (1, 'invalid_tel', '您输入的的手机号码不足11位,请重新填写。'.decode('UTF-8'))
(level, key, message) = is_cq_local_number(user_id, requests)
if (level != 0):
return (level, key, message)
elif (message == 'false'):
return (1, 'invalid_tel', 'Not a valid cq tel number'.decode('UTF-8'))
elif (message == 'true'):
return (0, 'success', 'True')
else:
return (9, 'unknown_error', u'unknown return format') | def is_validate(user_id, user_password, picture_validate_code, requests):
'\n Check if the target tel, password, code are valid\n :param user_id: Tel number\n :param user_password: Password\n :param picture_validate_code: code in Capcha image\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
if (len(picture_validate_code) < 4):
return (2, 'verify_error', '您输入的校验码不足4位,请重新填写。'.decode('UTF-8'))
elif (len(user_password) < 6):
return (1, 'pin_pwd_error', '您输入的密码不足6位,请重新填写。'.decode('UTF-8'))
elif (len(user_id) < 11):
return (1, 'invalid_tel', '您输入的的手机号码不足11位,请重新填写。'.decode('UTF-8'))
(level, key, message) = is_cq_local_number(user_id, requests)
if (level != 0):
return (level, key, message)
elif (message == 'false'):
return (1, 'invalid_tel', 'Not a valid cq tel number'.decode('UTF-8'))
elif (message == 'true'):
return (0, 'success', 'True')
else:
return (9, 'unknown_error', u'unknown return format')<|docstring|>Check if the target tel, password, code are valid
:param user_id: Tel number
:param user_password: Password
:param picture_validate_code: code in Capcha image
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message<|endoftext|> |
4c4d8f341123c07b7a349a8dec67b836fc7f6901afea2e1c29fec587fd00cecd | def get_redirect_url_from_text(response_text):
'\n Get redirect url from target response text\n :param response_text: Response text returned from Request Login\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n url: str, The redirect url\n '
try:
if ('"RESULT":"0"' in response_text):
return ('success', 0, 'Get redirect url', re.search('"url":"(.+?)"', response_text).group(0))
else:
return ('login_error', 9, 'No redirect url error', '')
except Exception as e:
return ('unknown_error', 9, (u'get redirect_url failed: %s' % e), '') | Get redirect url from target response text
:param response_text: Response text returned from Request Login
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
url: str, The redirect url | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_redirect_url_from_text | Svolcano/python_exercise | 6 | python | def get_redirect_url_from_text(response_text):
'\n Get redirect url from target response text\n :param response_text: Response text returned from Request Login\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n url: str, The redirect url\n '
try:
if ('"RESULT":"0"' in response_text):
return ('success', 0, 'Get redirect url', re.search('"url":"(.+?)"', response_text).group(0))
else:
return ('login_error', 9, 'No redirect url error', )
except Exception as e:
return ('unknown_error', 9, (u'get redirect_url failed: %s' % e), ) | def get_redirect_url_from_text(response_text):
'\n Get redirect url from target response text\n :param response_text: Response text returned from Request Login\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n url: str, The redirect url\n '
try:
if ('"RESULT":"0"' in response_text):
return ('success', 0, 'Get redirect url', re.search('"url":"(.+?)"', response_text).group(0))
else:
return ('login_error', 9, 'No redirect url error', )
except Exception as e:
return ('unknown_error', 9, (u'get redirect_url failed: %s' % e), )<|docstring|>Get redirect url from target response text
:param response_text: Response text returned from Request Login
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
url: str, The redirect url<|endoftext|> |
5511bc3fe6d8963230b2f222e6ab09b49dacac88aafd2ef57ae0b5b6da858a3d | def get_sam_lart_from_xhtml(xhtml_string):
'\n Get SAMLart from target xhtml string\n :param xhtml_string: Response returned from Request Login Box\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n samlart: str, The SAMLart id\n '
try:
root = lxml.html.document_fromstring(xhtml_string)
error_info_value = root.xpath('//*[@name="errInfo"]/@value')
if (len(error_info_value) > 0):
return ('verify_error', 1, urllib.unquote(error_info_value[0]).decode('gbk'), '')
sam_lart_value = root.xpath('//*[@name="SAMLart"]/@value')
if (len(sam_lart_value) > 0):
return ('success', 0, 'Get SAMLart', sam_lart_value[0])
else:
return ('html_error', 9, 'No SAM LArt error', '')
except Exception as e:
return ('unknown_error', 9, (u'get_sam_lart_from_xhtml failed: %s' % e), '') | Get SAMLart from target xhtml string
:param xhtml_string: Response returned from Request Login Box
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
samlart: str, The SAMLart id | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_sam_lart_from_xhtml | Svolcano/python_exercise | 6 | python | def get_sam_lart_from_xhtml(xhtml_string):
'\n Get SAMLart from target xhtml string\n :param xhtml_string: Response returned from Request Login Box\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n samlart: str, The SAMLart id\n '
try:
root = lxml.html.document_fromstring(xhtml_string)
error_info_value = root.xpath('//*[@name="errInfo"]/@value')
if (len(error_info_value) > 0):
return ('verify_error', 1, urllib.unquote(error_info_value[0]).decode('gbk'), )
sam_lart_value = root.xpath('//*[@name="SAMLart"]/@value')
if (len(sam_lart_value) > 0):
return ('success', 0, 'Get SAMLart', sam_lart_value[0])
else:
return ('html_error', 9, 'No SAM LArt error', )
except Exception as e:
return ('unknown_error', 9, (u'get_sam_lart_from_xhtml failed: %s' % e), ) | def get_sam_lart_from_xhtml(xhtml_string):
'\n Get SAMLart from target xhtml string\n :param xhtml_string: Response returned from Request Login Box\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n samlart: str, The SAMLart id\n '
try:
root = lxml.html.document_fromstring(xhtml_string)
error_info_value = root.xpath('//*[@name="errInfo"]/@value')
if (len(error_info_value) > 0):
return ('verify_error', 1, urllib.unquote(error_info_value[0]).decode('gbk'), )
sam_lart_value = root.xpath('//*[@name="SAMLart"]/@value')
if (len(sam_lart_value) > 0):
return ('success', 0, 'Get SAMLart', sam_lart_value[0])
else:
return ('html_error', 9, 'No SAM LArt error', )
except Exception as e:
return ('unknown_error', 9, (u'get_sam_lart_from_xhtml failed: %s' % e), )<|docstring|>Get SAMLart from target xhtml string
:param xhtml_string: Response returned from Request Login Box
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
samlart: str, The SAMLart id<|endoftext|> |
3da6744556f45bc960db6bf0d791086cd3fa6b435dd6513f1cabb0e086738a23 | def get_good_id_from_xml(xml_string):
'\n Get good id from target xml string\n :param xml_string: Response returned from Get Good IDs\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n good_id: str, The good id\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No good id dataset error', '')
else:
good_id_value = json.loads(return_dataset[0].text)[0].get('X_RETURNRESULT', '')
if good_id_value:
if (len(good_id_value) == 0):
return (9, 'xml_error', 'No good id', '')
good_id_str = good_id_value[0]['GOODS_ID']
else:
good_id_str = re.findall('"GOODS_ID":"(.*?)"', return_dataset[0].text)[0]
return (0, 'success', 'Get good id', good_id_str)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, '') | Get good id from target xml string
:param xml_string: Response returned from Get Good IDs
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
good_id: str, The good id | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_good_id_from_xml | Svolcano/python_exercise | 6 | python | def get_good_id_from_xml(xml_string):
'\n Get good id from target xml string\n :param xml_string: Response returned from Get Good IDs\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n good_id: str, The good id\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No good id dataset error', )
else:
good_id_value = json.loads(return_dataset[0].text)[0].get('X_RETURNRESULT', )
if good_id_value:
if (len(good_id_value) == 0):
return (9, 'xml_error', 'No good id', )
good_id_str = good_id_value[0]['GOODS_ID']
else:
good_id_str = re.findall('"GOODS_ID":"(.*?)"', return_dataset[0].text)[0]
return (0, 'success', 'Get good id', good_id_str)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, ) | def get_good_id_from_xml(xml_string):
'\n Get good id from target xml string\n :param xml_string: Response returned from Get Good IDs\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n good_id: str, The good id\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No good id dataset error', )
else:
good_id_value = json.loads(return_dataset[0].text)[0].get('X_RETURNRESULT', )
if good_id_value:
if (len(good_id_value) == 0):
return (9, 'xml_error', 'No good id', )
good_id_str = good_id_value[0]['GOODS_ID']
else:
good_id_str = re.findall('"GOODS_ID":"(.*?)"', return_dataset[0].text)[0]
return (0, 'success', 'Get good id', good_id_str)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, )<|docstring|>Get good id from target xml string
:param xml_string: Response returned from Get Good IDs
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
good_id: str, The good id<|endoftext|> |
496f655f0105e7d2946a2b50268c7a29d539ef19e6dbd43b3b66190271121b98 | def get_personal_info_from_xml(xml_string):
"\n Get personal info from target xml string\n :param xml_string: Response returned from Get Personal Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n personal_info_value: dict, The person's info\n "
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', {})
else:
personal_info_value = json.loads(return_dataset[0].text)[0]
if (len(personal_info_value) == 0):
return (9, 'xml_error', 'No personal info', {})
return (0, 'success', 'Get personal info', personal_info_value)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, {}) | Get personal info from target xml string
:param xml_string: Response returned from Get Personal Info
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
personal_info_value: dict, The person's info | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_personal_info_from_xml | Svolcano/python_exercise | 6 | python | def get_personal_info_from_xml(xml_string):
"\n Get personal info from target xml string\n :param xml_string: Response returned from Get Personal Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n personal_info_value: dict, The person's info\n "
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', {})
else:
personal_info_value = json.loads(return_dataset[0].text)[0]
if (len(personal_info_value) == 0):
return (9, 'xml_error', 'No personal info', {})
return (0, 'success', 'Get personal info', personal_info_value)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, {}) | def get_personal_info_from_xml(xml_string):
"\n Get personal info from target xml string\n :param xml_string: Response returned from Get Personal Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n personal_info_value: dict, The person's info\n "
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', {})
else:
personal_info_value = json.loads(return_dataset[0].text)[0]
if (len(personal_info_value) == 0):
return (9, 'xml_error', 'No personal info', {})
return (0, 'success', 'Get personal info', personal_info_value)
except:
error = traceback.format_exc()
return (9, 'unknown_error', error, {})<|docstring|>Get personal info from target xml string
:param xml_string: Response returned from Get Personal Info
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
personal_info_value: dict, The person's info<|endoftext|> |
ea716aeb04d4fb9f4844f059977054fcaf28294ba6c52a9f2c4c4f5b02cb822e | def get_second_validate_result_from_xml(xml_string):
'\n Get second validate result from xml string\n :param xml_string: Response returned from Check SMS Validate Code\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
try:
if (u'Stack Trace' in xml_string):
return (9, 'website_busy_error', '')
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', '')
else:
second_validate_value = json.loads(return_dataset[0].text)[0]
if (len(second_validate_value) == 0):
return (9, 'xml_error', '')
elif (second_validate_value['FLAG'] == 'false'):
if (second_validate_value['RESULT'] == '7'):
return (2, 'verify_error', '')
if (second_validate_value['RESULT'] == '8'):
return (9, 'param_timeout', '')
return (9, 'xml_error', '')
return (0, 'success', '')
except:
error = traceback.format_exc()
return (9, 'unknown_error', error) | Get second validate result from xml string
:param xml_string: Response returned from Check SMS Validate Code
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_second_validate_result_from_xml | Svolcano/python_exercise | 6 | python | def get_second_validate_result_from_xml(xml_string):
'\n Get second validate result from xml string\n :param xml_string: Response returned from Check SMS Validate Code\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
try:
if (u'Stack Trace' in xml_string):
return (9, 'website_busy_error', )
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', )
else:
second_validate_value = json.loads(return_dataset[0].text)[0]
if (len(second_validate_value) == 0):
return (9, 'xml_error', )
elif (second_validate_value['FLAG'] == 'false'):
if (second_validate_value['RESULT'] == '7'):
return (2, 'verify_error', )
if (second_validate_value['RESULT'] == '8'):
return (9, 'param_timeout', )
return (9, 'xml_error', )
return (0, 'success', )
except:
error = traceback.format_exc()
return (9, 'unknown_error', error) | def get_second_validate_result_from_xml(xml_string):
'\n Get second validate result from xml string\n :param xml_string: Response returned from Check SMS Validate Code\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n '
try:
if (u'Stack Trace' in xml_string):
return (9, 'website_busy_error', )
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', )
else:
second_validate_value = json.loads(return_dataset[0].text)[0]
if (len(second_validate_value) == 0):
return (9, 'xml_error', )
elif (second_validate_value['FLAG'] == 'false'):
if (second_validate_value['RESULT'] == '7'):
return (2, 'verify_error', )
if (second_validate_value['RESULT'] == '8'):
return (9, 'param_timeout', )
return (9, 'xml_error', )
return (0, 'success', )
except:
error = traceback.format_exc()
return (9, 'unknown_error', error)<|docstring|>Get second validate result from xml string
:param xml_string: Response returned from Check SMS Validate Code
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message<|endoftext|> |
eda4c74b3d766c5e01b08b126a818251797f46e6e765d9d3eb5433fda1dcd685 | def get_detail_bill_from_xml(xml_string):
'\n Get detail bill from target xml string\n :param xml_string: Response returned from Get Detail Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n detail_bill_value: list, The list of detail bill info\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', [])
detail_bill_value = json.loads(return_dataset[0].text)[0]
if (len(detail_bill_value) == 0):
return (9, 'xml_error', 'No detail bill info', [])
elif (detail_bill_value['X_RESULTCODE'] != '0'):
if (detail_bill_value['X_RESULTCODE'] == '102'):
return (0, 'success', detail_bill_value['X_RESULTINFO'], [])
if (u'打开的文件过多' in xml_string):
return (9, 'website_busy_error', '{}'.format(xml_string), [])
return (9, 'expected_key_error', detail_bill_value['X_RESULTINFO'], [])
return (0, 'success', 'Got detail bill info', detail_bill_value['resultData'])
except Exception as e:
return (9, 'unknown_error', (u'get_detail_bill_from_xml failed: %s' % e), []) | Get detail bill from target xml string
:param xml_string: Response returned from Get Detail Info
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
detail_bill_value: list, The list of detail bill info | dianhua/worker/crawler/china_mobile/chongqing/base_info_crawler.py | get_detail_bill_from_xml | Svolcano/python_exercise | 6 | python | def get_detail_bill_from_xml(xml_string):
'\n Get detail bill from target xml string\n :param xml_string: Response returned from Get Detail Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n detail_bill_value: list, The list of detail bill info\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', [])
detail_bill_value = json.loads(return_dataset[0].text)[0]
if (len(detail_bill_value) == 0):
return (9, 'xml_error', 'No detail bill info', [])
elif (detail_bill_value['X_RESULTCODE'] != '0'):
if (detail_bill_value['X_RESULTCODE'] == '102'):
return (0, 'success', detail_bill_value['X_RESULTINFO'], [])
if (u'打开的文件过多' in xml_string):
return (9, 'website_busy_error', '{}'.format(xml_string), [])
return (9, 'expected_key_error', detail_bill_value['X_RESULTINFO'], [])
return (0, 'success', 'Got detail bill info', detail_bill_value['resultData'])
except Exception as e:
return (9, 'unknown_error', (u'get_detail_bill_from_xml failed: %s' % e), []) | def get_detail_bill_from_xml(xml_string):
'\n Get detail bill from target xml string\n :param xml_string: Response returned from Get Detail Info\n :return:\n status_key: str, The key of status code\n level: int, Error level\n message: unicode, Error Message\n detail_bill_value: list, The list of detail bill info\n '
try:
root = etree.fromstring(xml_string.encode('utf-8'))
return_dataset = root.xpath('//*[@id="dataset"]')
if (len(return_dataset) == 0):
return (9, 'xml_error', 'No personal info dataset error', [])
detail_bill_value = json.loads(return_dataset[0].text)[0]
if (len(detail_bill_value) == 0):
return (9, 'xml_error', 'No detail bill info', [])
elif (detail_bill_value['X_RESULTCODE'] != '0'):
if (detail_bill_value['X_RESULTCODE'] == '102'):
return (0, 'success', detail_bill_value['X_RESULTINFO'], [])
if (u'打开的文件过多' in xml_string):
return (9, 'website_busy_error', '{}'.format(xml_string), [])
return (9, 'expected_key_error', detail_bill_value['X_RESULTINFO'], [])
return (0, 'success', 'Got detail bill info', detail_bill_value['resultData'])
except Exception as e:
return (9, 'unknown_error', (u'get_detail_bill_from_xml failed: %s' % e), [])<|docstring|>Get detail bill from target xml string
:param xml_string: Response returned from Get Detail Info
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
detail_bill_value: list, The list of detail bill info<|endoftext|> |
3d863c1b2bdf30d2041b6d4eaa4c54a693926c744dffe72d2cef0e51b2fbad30 | def __init__(self, x, y, radius, sx, sy, color=Color.RED):
'初始化方法'
self.x = x
self.y = y
self.radius = radius
self.sx = sx
self.sy = sy
self.color = color
self.alive = True | 初始化方法 | com/xy/ztang/gui/ball.py | __init__ | zhangptang/python_learning | 0 | python | def __init__(self, x, y, radius, sx, sy, color=Color.RED):
self.x = x
self.y = y
self.radius = radius
self.sx = sx
self.sy = sy
self.color = color
self.alive = True | def __init__(self, x, y, radius, sx, sy, color=Color.RED):
self.x = x
self.y = y
self.radius = radius
self.sx = sx
self.sy = sy
self.color = color
self.alive = True<|docstring|>初始化方法<|endoftext|> |
75ce63e36c016a4aed36edd7463d237130060b323d36af76e98922ae7fa72743 | def _to_m8(key):
'\n Timedelta-like => dt64\n '
if (not isinstance(key, Timedelta)):
key = Timedelta(key)
return np.int64(key.value).view(_TD_DTYPE) | Timedelta-like => dt64 | pandas/core/arrays/timedeltas.py | _to_m8 | fleimgruber/pandas | 1 | python | def _to_m8(key):
'\n \n '
if (not isinstance(key, Timedelta)):
key = Timedelta(key)
return np.int64(key.value).view(_TD_DTYPE) | def _to_m8(key):
'\n \n '
if (not isinstance(key, Timedelta)):
key = Timedelta(key)
return np.int64(key.value).view(_TD_DTYPE)<|docstring|>Timedelta-like => dt64<|endoftext|> |
002d535d84eef6f4fc1df45330971c434dd3f7e404db4631753f67ebcb202848 | def _td_array_cmp(cls, op):
'\n Wrap comparison operations to convert timedelta-like to timedelta64\n '
opname = '__{name}__'.format(name=op.__name__)
nat_result = (True if (opname == '__ne__') else False)
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
def wrapper(self, other):
if (_is_convertible_to_td(other) or (other is NaT)):
try:
other = _to_m8(other)
except ValueError:
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
if isna(other):
result.fill(nat_result)
elif (not is_list_like(other)):
return ops.invalid_comparison(self, other, op)
elif (len(other) != len(self)):
raise ValueError('Lengths must match')
else:
try:
other = type(self)._from_sequence(other)._data
except (ValueError, TypeError):
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
result = com.values_from_object(result)
o_mask = np.array(isna(other))
if o_mask.any():
result[o_mask] = nat_result
if self._hasnans:
result[self._isnan] = nat_result
return result
return compat.set_function_name(wrapper, opname, cls) | Wrap comparison operations to convert timedelta-like to timedelta64 | pandas/core/arrays/timedeltas.py | _td_array_cmp | fleimgruber/pandas | 1 | python | def _td_array_cmp(cls, op):
'\n \n '
opname = '__{name}__'.format(name=op.__name__)
nat_result = (True if (opname == '__ne__') else False)
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
def wrapper(self, other):
if (_is_convertible_to_td(other) or (other is NaT)):
try:
other = _to_m8(other)
except ValueError:
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
if isna(other):
result.fill(nat_result)
elif (not is_list_like(other)):
return ops.invalid_comparison(self, other, op)
elif (len(other) != len(self)):
raise ValueError('Lengths must match')
else:
try:
other = type(self)._from_sequence(other)._data
except (ValueError, TypeError):
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
result = com.values_from_object(result)
o_mask = np.array(isna(other))
if o_mask.any():
result[o_mask] = nat_result
if self._hasnans:
result[self._isnan] = nat_result
return result
return compat.set_function_name(wrapper, opname, cls) | def _td_array_cmp(cls, op):
'\n \n '
opname = '__{name}__'.format(name=op.__name__)
nat_result = (True if (opname == '__ne__') else False)
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
def wrapper(self, other):
if (_is_convertible_to_td(other) or (other is NaT)):
try:
other = _to_m8(other)
except ValueError:
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
if isna(other):
result.fill(nat_result)
elif (not is_list_like(other)):
return ops.invalid_comparison(self, other, op)
elif (len(other) != len(self)):
raise ValueError('Lengths must match')
else:
try:
other = type(self)._from_sequence(other)._data
except (ValueError, TypeError):
return ops.invalid_comparison(self, other, op)
result = meth(self, other)
result = com.values_from_object(result)
o_mask = np.array(isna(other))
if o_mask.any():
result[o_mask] = nat_result
if self._hasnans:
result[self._isnan] = nat_result
return result
return compat.set_function_name(wrapper, opname, cls)<|docstring|>Wrap comparison operations to convert timedelta-like to timedelta64<|endoftext|> |
786cc5d5cc2fd71d8cfd810d66479df8954f80e5abc82ed71f410ccb58add17d | def sequence_to_td64ns(data, copy=False, unit='ns', errors='raise'):
'\n Parameters\n ----------\n array : list-like\n copy : bool, default False\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n converted : numpy.ndarray\n The sequence converted to a numpy array with dtype ``timedelta64[ns]``.\n inferred_freq : Tick or None\n The inferred frequency of the sequence.\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
inferred_freq = None
unit = parse_timedelta_unit(unit)
if (not hasattr(data, 'dtype')):
if (np.ndim(data) == 0):
data = list(data)
data = np.array(data, copy=False)
elif isinstance(data, ABCSeries):
data = data._values
elif isinstance(data, (ABCTimedeltaIndex, TimedeltaArrayMixin)):
inferred_freq = data.freq
data = data._data
if (is_object_dtype(data) or is_string_dtype(data)):
data = objects_to_td64ns(data, unit=unit, errors=errors)
copy = False
elif is_integer_dtype(data):
(data, copy_made) = ints_to_td64ns(data, unit=unit)
copy = (copy and (not copy_made))
elif is_float_dtype(data):
mask = np.isnan(data)
coeff = (np.timedelta64(1, unit) / np.timedelta64(1, 'ns'))
data = (coeff * data).astype(np.int64).view('timedelta64[ns]')
data[mask] = iNaT
copy = False
elif is_timedelta64_dtype(data):
if (data.dtype != _TD_DTYPE):
data = data.astype(_TD_DTYPE)
copy = False
elif is_datetime64_dtype(data):
warnings.warn('Passing datetime64-dtype data to TimedeltaIndex is deprecated, will raise a TypeError in a future version', FutureWarning, stacklevel=4)
data = ensure_int64(data).view(_TD_DTYPE)
else:
raise TypeError('dtype {dtype} cannot be converted to timedelta64[ns]'.format(dtype=data.dtype))
data = np.array(data, copy=copy)
assert (data.dtype == 'm8[ns]'), data
return (data, inferred_freq) | Parameters
----------
array : list-like
copy : bool, default False
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : {"raise", "coerce", "ignore"}, default "raise"
How to handle elements that cannot be converted to timedelta64[ns].
See ``pandas.to_timedelta`` for details.
Returns
-------
converted : numpy.ndarray
The sequence converted to a numpy array with dtype ``timedelta64[ns]``.
inferred_freq : Tick or None
The inferred frequency of the sequence.
Raises
------
ValueError : Data cannot be converted to timedelta64[ns].
Notes
-----
Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause
errors to be ignored; they are caught and subsequently ignored at a
higher level. | pandas/core/arrays/timedeltas.py | sequence_to_td64ns | fleimgruber/pandas | 1 | python | def sequence_to_td64ns(data, copy=False, unit='ns', errors='raise'):
'\n Parameters\n ----------\n array : list-like\n copy : bool, default False\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n converted : numpy.ndarray\n The sequence converted to a numpy array with dtype ``timedelta64[ns]``.\n inferred_freq : Tick or None\n The inferred frequency of the sequence.\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
inferred_freq = None
unit = parse_timedelta_unit(unit)
if (not hasattr(data, 'dtype')):
if (np.ndim(data) == 0):
data = list(data)
data = np.array(data, copy=False)
elif isinstance(data, ABCSeries):
data = data._values
elif isinstance(data, (ABCTimedeltaIndex, TimedeltaArrayMixin)):
inferred_freq = data.freq
data = data._data
if (is_object_dtype(data) or is_string_dtype(data)):
data = objects_to_td64ns(data, unit=unit, errors=errors)
copy = False
elif is_integer_dtype(data):
(data, copy_made) = ints_to_td64ns(data, unit=unit)
copy = (copy and (not copy_made))
elif is_float_dtype(data):
mask = np.isnan(data)
coeff = (np.timedelta64(1, unit) / np.timedelta64(1, 'ns'))
data = (coeff * data).astype(np.int64).view('timedelta64[ns]')
data[mask] = iNaT
copy = False
elif is_timedelta64_dtype(data):
if (data.dtype != _TD_DTYPE):
data = data.astype(_TD_DTYPE)
copy = False
elif is_datetime64_dtype(data):
warnings.warn('Passing datetime64-dtype data to TimedeltaIndex is deprecated, will raise a TypeError in a future version', FutureWarning, stacklevel=4)
data = ensure_int64(data).view(_TD_DTYPE)
else:
raise TypeError('dtype {dtype} cannot be converted to timedelta64[ns]'.format(dtype=data.dtype))
data = np.array(data, copy=copy)
assert (data.dtype == 'm8[ns]'), data
return (data, inferred_freq) | def sequence_to_td64ns(data, copy=False, unit='ns', errors='raise'):
'\n Parameters\n ----------\n array : list-like\n copy : bool, default False\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n converted : numpy.ndarray\n The sequence converted to a numpy array with dtype ``timedelta64[ns]``.\n inferred_freq : Tick or None\n The inferred frequency of the sequence.\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
inferred_freq = None
unit = parse_timedelta_unit(unit)
if (not hasattr(data, 'dtype')):
if (np.ndim(data) == 0):
data = list(data)
data = np.array(data, copy=False)
elif isinstance(data, ABCSeries):
data = data._values
elif isinstance(data, (ABCTimedeltaIndex, TimedeltaArrayMixin)):
inferred_freq = data.freq
data = data._data
if (is_object_dtype(data) or is_string_dtype(data)):
data = objects_to_td64ns(data, unit=unit, errors=errors)
copy = False
elif is_integer_dtype(data):
(data, copy_made) = ints_to_td64ns(data, unit=unit)
copy = (copy and (not copy_made))
elif is_float_dtype(data):
mask = np.isnan(data)
coeff = (np.timedelta64(1, unit) / np.timedelta64(1, 'ns'))
data = (coeff * data).astype(np.int64).view('timedelta64[ns]')
data[mask] = iNaT
copy = False
elif is_timedelta64_dtype(data):
if (data.dtype != _TD_DTYPE):
data = data.astype(_TD_DTYPE)
copy = False
elif is_datetime64_dtype(data):
warnings.warn('Passing datetime64-dtype data to TimedeltaIndex is deprecated, will raise a TypeError in a future version', FutureWarning, stacklevel=4)
data = ensure_int64(data).view(_TD_DTYPE)
else:
raise TypeError('dtype {dtype} cannot be converted to timedelta64[ns]'.format(dtype=data.dtype))
data = np.array(data, copy=copy)
assert (data.dtype == 'm8[ns]'), data
return (data, inferred_freq)<|docstring|>Parameters
----------
array : list-like
copy : bool, default False
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : {"raise", "coerce", "ignore"}, default "raise"
How to handle elements that cannot be converted to timedelta64[ns].
See ``pandas.to_timedelta`` for details.
Returns
-------
converted : numpy.ndarray
The sequence converted to a numpy array with dtype ``timedelta64[ns]``.
inferred_freq : Tick or None
The inferred frequency of the sequence.
Raises
------
ValueError : Data cannot be converted to timedelta64[ns].
Notes
-----
Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause
errors to be ignored; they are caught and subsequently ignored at a
higher level.<|endoftext|> |
349b60eb2c0f6ab5fe53a8fb7b73fa0d100c7e2a29b1ce616d176c7fc790cc73 | def ints_to_td64ns(data, unit='ns'):
'\n Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating\n the integers as multiples of the given timedelta unit.\n\n Parameters\n ----------\n data : numpy.ndarray with integer-dtype\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n bool : whether a copy was made\n '
copy_made = False
unit = (unit if (unit is not None) else 'ns')
if (data.dtype != np.int64):
data = data.astype(np.int64)
copy_made = True
if (unit != 'ns'):
dtype_str = 'timedelta64[{unit}]'.format(unit=unit)
data = data.view(dtype_str)
data = data.astype('timedelta64[ns]')
copy_made = True
else:
data = data.view('timedelta64[ns]')
return (data, copy_made) | Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating
the integers as multiples of the given timedelta unit.
Parameters
----------
data : numpy.ndarray with integer-dtype
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
Returns
-------
numpy.ndarray : timedelta64[ns] array converted from data
bool : whether a copy was made | pandas/core/arrays/timedeltas.py | ints_to_td64ns | fleimgruber/pandas | 1 | python | def ints_to_td64ns(data, unit='ns'):
'\n Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating\n the integers as multiples of the given timedelta unit.\n\n Parameters\n ----------\n data : numpy.ndarray with integer-dtype\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n bool : whether a copy was made\n '
copy_made = False
unit = (unit if (unit is not None) else 'ns')
if (data.dtype != np.int64):
data = data.astype(np.int64)
copy_made = True
if (unit != 'ns'):
dtype_str = 'timedelta64[{unit}]'.format(unit=unit)
data = data.view(dtype_str)
data = data.astype('timedelta64[ns]')
copy_made = True
else:
data = data.view('timedelta64[ns]')
return (data, copy_made) | def ints_to_td64ns(data, unit='ns'):
'\n Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating\n the integers as multiples of the given timedelta unit.\n\n Parameters\n ----------\n data : numpy.ndarray with integer-dtype\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n bool : whether a copy was made\n '
copy_made = False
unit = (unit if (unit is not None) else 'ns')
if (data.dtype != np.int64):
data = data.astype(np.int64)
copy_made = True
if (unit != 'ns'):
dtype_str = 'timedelta64[{unit}]'.format(unit=unit)
data = data.view(dtype_str)
data = data.astype('timedelta64[ns]')
copy_made = True
else:
data = data.view('timedelta64[ns]')
return (data, copy_made)<|docstring|>Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating
the integers as multiples of the given timedelta unit.
Parameters
----------
data : numpy.ndarray with integer-dtype
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
Returns
-------
numpy.ndarray : timedelta64[ns] array converted from data
bool : whether a copy was made<|endoftext|> |
2e23fc7fc25bb935f91e74d1e93d8f483c51a9e1474afd1053d8c0b8abd4423c | def objects_to_td64ns(data, unit='ns', errors='raise'):
'\n Convert a object-dtyped or string-dtyped array into an\n timedelta64[ns]-dtyped array.\n\n Parameters\n ----------\n data : ndarray or Index\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
values = np.array(data, dtype=np.object_, copy=False)
result = array_to_timedelta64(values, unit=unit, errors=errors)
return result.view('timedelta64[ns]') | Convert a object-dtyped or string-dtyped array into an
timedelta64[ns]-dtyped array.
Parameters
----------
data : ndarray or Index
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : {"raise", "coerce", "ignore"}, default "raise"
How to handle elements that cannot be converted to timedelta64[ns].
See ``pandas.to_timedelta`` for details.
Returns
-------
numpy.ndarray : timedelta64[ns] array converted from data
Raises
------
ValueError : Data cannot be converted to timedelta64[ns].
Notes
-----
Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause
errors to be ignored; they are caught and subsequently ignored at a
higher level. | pandas/core/arrays/timedeltas.py | objects_to_td64ns | fleimgruber/pandas | 1 | python | def objects_to_td64ns(data, unit='ns', errors='raise'):
'\n Convert a object-dtyped or string-dtyped array into an\n timedelta64[ns]-dtyped array.\n\n Parameters\n ----------\n data : ndarray or Index\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
values = np.array(data, dtype=np.object_, copy=False)
result = array_to_timedelta64(values, unit=unit, errors=errors)
return result.view('timedelta64[ns]') | def objects_to_td64ns(data, unit='ns', errors='raise'):
'\n Convert a object-dtyped or string-dtyped array into an\n timedelta64[ns]-dtyped array.\n\n Parameters\n ----------\n data : ndarray or Index\n unit : str, default "ns"\n The timedelta unit to treat integers as multiples of.\n errors : {"raise", "coerce", "ignore"}, default "raise"\n How to handle elements that cannot be converted to timedelta64[ns].\n See ``pandas.to_timedelta`` for details.\n\n Returns\n -------\n numpy.ndarray : timedelta64[ns] array converted from data\n\n Raises\n ------\n ValueError : Data cannot be converted to timedelta64[ns].\n\n Notes\n -----\n Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause\n errors to be ignored; they are caught and subsequently ignored at a\n higher level.\n '
values = np.array(data, dtype=np.object_, copy=False)
result = array_to_timedelta64(values, unit=unit, errors=errors)
return result.view('timedelta64[ns]')<|docstring|>Convert a object-dtyped or string-dtyped array into an
timedelta64[ns]-dtyped array.
Parameters
----------
data : ndarray or Index
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : {"raise", "coerce", "ignore"}, default "raise"
How to handle elements that cannot be converted to timedelta64[ns].
See ``pandas.to_timedelta`` for details.
Returns
-------
numpy.ndarray : timedelta64[ns] array converted from data
Raises
------
ValueError : Data cannot be converted to timedelta64[ns].
Notes
-----
Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause
errors to be ignored; they are caught and subsequently ignored at a
higher level.<|endoftext|> |
0054f2dbc4e91494b8570e7dc3693fb1012920c0abe03cb0054002524be43012 | def _add_delta(self, delta):
'\n Add a timedelta-like, Tick, or TimedeltaIndex-like object\n to self, yielding a new TimedeltaArray.\n\n Parameters\n ----------\n other : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result : TimedeltaArray\n '
new_values = super(TimedeltaArrayMixin, self)._add_delta(delta)
return type(self)._from_sequence(new_values, freq='infer') | Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new TimedeltaArray.
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : TimedeltaArray | pandas/core/arrays/timedeltas.py | _add_delta | fleimgruber/pandas | 1 | python | def _add_delta(self, delta):
'\n Add a timedelta-like, Tick, or TimedeltaIndex-like object\n to self, yielding a new TimedeltaArray.\n\n Parameters\n ----------\n other : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result : TimedeltaArray\n '
new_values = super(TimedeltaArrayMixin, self)._add_delta(delta)
return type(self)._from_sequence(new_values, freq='infer') | def _add_delta(self, delta):
'\n Add a timedelta-like, Tick, or TimedeltaIndex-like object\n to self, yielding a new TimedeltaArray.\n\n Parameters\n ----------\n other : {timedelta, np.timedelta64, Tick,\n TimedeltaIndex, ndarray[timedelta64]}\n\n Returns\n -------\n result : TimedeltaArray\n '
new_values = super(TimedeltaArrayMixin, self)._add_delta(delta)
return type(self)._from_sequence(new_values, freq='infer')<|docstring|>Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new TimedeltaArray.
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : TimedeltaArray<|endoftext|> |
0748861753f47783d0ca1364d52efc5a4e96e6d60418b8f2a0b10e153acd2aa4 | def _add_datetime_arraylike(self, other):
'\n Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.\n '
if isinstance(other, np.ndarray):
from pandas.core.arrays import DatetimeArrayMixin
other = DatetimeArrayMixin(other)
return (other + self) | Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. | pandas/core/arrays/timedeltas.py | _add_datetime_arraylike | fleimgruber/pandas | 1 | python | def _add_datetime_arraylike(self, other):
'\n \n '
if isinstance(other, np.ndarray):
from pandas.core.arrays import DatetimeArrayMixin
other = DatetimeArrayMixin(other)
return (other + self) | def _add_datetime_arraylike(self, other):
'\n \n '
if isinstance(other, np.ndarray):
from pandas.core.arrays import DatetimeArrayMixin
other = DatetimeArrayMixin(other)
return (other + self)<|docstring|>Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.<|endoftext|> |
651b960b511617333a20174341a831886c4bf89e7f7ae277ecd21deb88f47952 | def total_seconds(self):
"\n Return total duration of each element expressed in seconds.\n\n This method is available directly on TimedeltaArray, TimedeltaIndex\n and on Series containing timedelta values under the ``.dt`` namespace.\n\n Returns\n -------\n seconds : [ndarray, Float64Index, Series]\n When the calling object is a TimedeltaArray, the return type\n is ndarray. When the calling object is a TimedeltaIndex,\n the return type is a Float64Index. When the calling object\n is a Series, the return type is Series of type `float64` whose\n index is the same as the original.\n\n See Also\n --------\n datetime.timedelta.total_seconds : Standard library version\n of this method.\n TimedeltaIndex.components : Return a DataFrame with components of\n each Timedelta.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))\n >>> s\n 0 0 days\n 1 1 days\n 2 2 days\n 3 3 days\n 4 4 days\n dtype: timedelta64[ns]\n\n >>> s.dt.total_seconds()\n 0 0.0\n 1 86400.0\n 2 172800.0\n 3 259200.0\n 4 345600.0\n dtype: float64\n\n **TimedeltaIndex**\n\n >>> idx = pd.to_timedelta(np.arange(5), unit='d')\n >>> idx\n TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq=None)\n\n >>> idx.total_seconds()\n Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0],\n dtype='float64')\n "
return self._maybe_mask_results((1e-09 * self.asi8), fill_value=None) | Return total duration of each element expressed in seconds.
This method is available directly on TimedeltaArray, TimedeltaIndex
and on Series containing timedelta values under the ``.dt`` namespace.
Returns
-------
seconds : [ndarray, Float64Index, Series]
When the calling object is a TimedeltaArray, the return type
is ndarray. When the calling object is a TimedeltaIndex,
the return type is a Float64Index. When the calling object
is a Series, the return type is Series of type `float64` whose
index is the same as the original.
See Also
--------
datetime.timedelta.total_seconds : Standard library version
of this method.
TimedeltaIndex.components : Return a DataFrame with components of
each Timedelta.
Examples
--------
**Series**
>>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))
>>> s
0 0 days
1 1 days
2 2 days
3 3 days
4 4 days
dtype: timedelta64[ns]
>>> s.dt.total_seconds()
0 0.0
1 86400.0
2 172800.0
3 259200.0
4 345600.0
dtype: float64
**TimedeltaIndex**
>>> idx = pd.to_timedelta(np.arange(5), unit='d')
>>> idx
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
>>> idx.total_seconds()
Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0],
dtype='float64') | pandas/core/arrays/timedeltas.py | total_seconds | fleimgruber/pandas | 1 | python | def total_seconds(self):
"\n Return total duration of each element expressed in seconds.\n\n This method is available directly on TimedeltaArray, TimedeltaIndex\n and on Series containing timedelta values under the ``.dt`` namespace.\n\n Returns\n -------\n seconds : [ndarray, Float64Index, Series]\n When the calling object is a TimedeltaArray, the return type\n is ndarray. When the calling object is a TimedeltaIndex,\n the return type is a Float64Index. When the calling object\n is a Series, the return type is Series of type `float64` whose\n index is the same as the original.\n\n See Also\n --------\n datetime.timedelta.total_seconds : Standard library version\n of this method.\n TimedeltaIndex.components : Return a DataFrame with components of\n each Timedelta.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))\n >>> s\n 0 0 days\n 1 1 days\n 2 2 days\n 3 3 days\n 4 4 days\n dtype: timedelta64[ns]\n\n >>> s.dt.total_seconds()\n 0 0.0\n 1 86400.0\n 2 172800.0\n 3 259200.0\n 4 345600.0\n dtype: float64\n\n **TimedeltaIndex**\n\n >>> idx = pd.to_timedelta(np.arange(5), unit='d')\n >>> idx\n TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq=None)\n\n >>> idx.total_seconds()\n Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0],\n dtype='float64')\n "
return self._maybe_mask_results((1e-09 * self.asi8), fill_value=None) | def total_seconds(self):
"\n Return total duration of each element expressed in seconds.\n\n This method is available directly on TimedeltaArray, TimedeltaIndex\n and on Series containing timedelta values under the ``.dt`` namespace.\n\n Returns\n -------\n seconds : [ndarray, Float64Index, Series]\n When the calling object is a TimedeltaArray, the return type\n is ndarray. When the calling object is a TimedeltaIndex,\n the return type is a Float64Index. When the calling object\n is a Series, the return type is Series of type `float64` whose\n index is the same as the original.\n\n See Also\n --------\n datetime.timedelta.total_seconds : Standard library version\n of this method.\n TimedeltaIndex.components : Return a DataFrame with components of\n each Timedelta.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))\n >>> s\n 0 0 days\n 1 1 days\n 2 2 days\n 3 3 days\n 4 4 days\n dtype: timedelta64[ns]\n\n >>> s.dt.total_seconds()\n 0 0.0\n 1 86400.0\n 2 172800.0\n 3 259200.0\n 4 345600.0\n dtype: float64\n\n **TimedeltaIndex**\n\n >>> idx = pd.to_timedelta(np.arange(5), unit='d')\n >>> idx\n TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],\n dtype='timedelta64[ns]', freq=None)\n\n >>> idx.total_seconds()\n Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0],\n dtype='float64')\n "
return self._maybe_mask_results((1e-09 * self.asi8), fill_value=None)<|docstring|>Return total duration of each element expressed in seconds.
This method is available directly on TimedeltaArray, TimedeltaIndex
and on Series containing timedelta values under the ``.dt`` namespace.
Returns
-------
seconds : [ndarray, Float64Index, Series]
When the calling object is a TimedeltaArray, the return type
is ndarray. When the calling object is a TimedeltaIndex,
the return type is a Float64Index. When the calling object
is a Series, the return type is Series of type `float64` whose
index is the same as the original.
See Also
--------
datetime.timedelta.total_seconds : Standard library version
of this method.
TimedeltaIndex.components : Return a DataFrame with components of
each Timedelta.
Examples
--------
**Series**
>>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))
>>> s
0 0 days
1 1 days
2 2 days
3 3 days
4 4 days
dtype: timedelta64[ns]
>>> s.dt.total_seconds()
0 0.0
1 86400.0
2 172800.0
3 259200.0
4 345600.0
dtype: float64
**TimedeltaIndex**
>>> idx = pd.to_timedelta(np.arange(5), unit='d')
>>> idx
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
>>> idx.total_seconds()
Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0],
dtype='float64')<|endoftext|> |
e746795bb18896d307664969e7ea373fb1d03f476568a7101840bba69a918ddd | def to_pytimedelta(self):
'\n Return Timedelta Array/Index as object ndarray of datetime.timedelta\n objects.\n\n Returns\n -------\n datetimes : ndarray\n '
return tslibs.ints_to_pytimedelta(self.asi8) | Return Timedelta Array/Index as object ndarray of datetime.timedelta
objects.
Returns
-------
datetimes : ndarray | pandas/core/arrays/timedeltas.py | to_pytimedelta | fleimgruber/pandas | 1 | python | def to_pytimedelta(self):
'\n Return Timedelta Array/Index as object ndarray of datetime.timedelta\n objects.\n\n Returns\n -------\n datetimes : ndarray\n '
return tslibs.ints_to_pytimedelta(self.asi8) | def to_pytimedelta(self):
'\n Return Timedelta Array/Index as object ndarray of datetime.timedelta\n objects.\n\n Returns\n -------\n datetimes : ndarray\n '
return tslibs.ints_to_pytimedelta(self.asi8)<|docstring|>Return Timedelta Array/Index as object ndarray of datetime.timedelta
objects.
Returns
-------
datetimes : ndarray<|endoftext|> |
56d909bc85ff47fc9b7f5f848e30da60e265515313cde164034a65a366faafb2 | @property
def components(self):
'\n Return a dataframe of the components (days, hours, minutes,\n seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.\n\n Returns\n -------\n a DataFrame\n '
from pandas import DataFrame
columns = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds']
hasnans = self._hasnans
if hasnans:
def f(x):
if isna(x):
return ([np.nan] * len(columns))
return x.components
else:
def f(x):
return x.components
result = DataFrame([f(x) for x in self], columns=columns)
if (not hasnans):
result = result.astype('int64')
return result | Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame | pandas/core/arrays/timedeltas.py | components | fleimgruber/pandas | 1 | python | @property
def components(self):
'\n Return a dataframe of the components (days, hours, minutes,\n seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.\n\n Returns\n -------\n a DataFrame\n '
from pandas import DataFrame
columns = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds']
hasnans = self._hasnans
if hasnans:
def f(x):
if isna(x):
return ([np.nan] * len(columns))
return x.components
else:
def f(x):
return x.components
result = DataFrame([f(x) for x in self], columns=columns)
if (not hasnans):
result = result.astype('int64')
return result | @property
def components(self):
'\n Return a dataframe of the components (days, hours, minutes,\n seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.\n\n Returns\n -------\n a DataFrame\n '
from pandas import DataFrame
columns = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds']
hasnans = self._hasnans
if hasnans:
def f(x):
if isna(x):
return ([np.nan] * len(columns))
return x.components
else:
def f(x):
return x.components
result = DataFrame([f(x) for x in self], columns=columns)
if (not hasnans):
result = result.astype('int64')
return result<|docstring|>Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame<|endoftext|> |
f003947e2f003bbb8625eec02a89731d26d0f5d7722cd01ae3b89cbd5916145b | @typing.overload
def __init__(self: TelegramClient, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop):
"Start TelegramClient with customized api.\n\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n \n ### Arguments:\n session (`str` | `Session`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it's `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you're done.\n\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n " | Start TelegramClient with customized api.
Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)
### Arguments:
session (`str` | `Session`):
The file name of the `session file` to be used, if a string is\
given (it may be a full path), or the `Session` instance to be used\
Otherwise, if it's `None`, the `session` will not be saved,\
and you should call method `.log_out()` when you're done.
Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`. | src/tl/telethon.py | __init__ | annihilatorrrr/opentele | 30 | python | @typing.overload
def __init__(self: TelegramClient, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop):
"Start TelegramClient with customized api.\n\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n \n ### Arguments:\n session (`str` | `Session`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it's `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you're done.\n\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n " | @typing.overload
def __init__(self: TelegramClient, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop):
"Start TelegramClient with customized api.\n\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n \n ### Arguments:\n session (`str` | `Session`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it's `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you're done.\n\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n "<|docstring|>Start TelegramClient with customized api.
Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)
### Arguments:
session (`str` | `Session`):
The file name of the `session file` to be used, if a string is\
given (it may be a full path), or the `Session` instance to be used\
Otherwise, if it's `None`, the `session` will not be saved,\
and you should call method `.log_out()` when you're done.
Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.<|endoftext|> |
39e37c180ce97f2a2934fa04d9cb0a4b6c6678031ee33c17ba073f36a3c16727 | @typing.overload
def __init__(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=None, api_id: int=0, api_hash: str=None, *, connection: typing.Type[Connection]=ConnectionTcpFull, use_ipv6: bool=False, proxy: Union[(tuple, dict)]=None, local_addr: Union[(str, tuple)]=None, timeout: int=10, request_retries: int=5, connection_retries: int=5, retry_delay: int=1, auto_reconnect: bool=True, sequential_updates: bool=False, flood_sleep_threshold: int=60, raise_last_call_error: bool=False, device_model: str=None, system_version: str=None, app_version: str=None, lang_code: str='en', system_lang_code: str='en', loop: asyncio.AbstractEventLoop=None, base_logger: Union[(str, logging.Logger)]=None, receive_updates: bool=True):
'\n !skip\n This is the abstract base class for the client. It defines some\n basic stuff like connecting, switching data center, etc, and\n leaves the `__call__` unimplemented.\n\n ### Arguments:\n session (`str` | `Session`, default=`None`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it\'s `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you\'re done.\n\n Note that if you pass a string it will be a file in the current working directory, although you can also pass absolute paths.\\\n\n The session file contains enough information for you to login\\\n without re-sending the code, so if you have to enter the code\\\n more than once, maybe you\'re changing the working directory,\\\n renaming or removing the file, or using random names.\n\n api (`API`, default=None):\n Use custom api_id and api_hash for better experience.\n\n These arguments will be ignored if it is set in the API: `api_id`, `api_hash`, `device_model`, `system_version`, `app_version`, `lang_code`, `system_lang_code`\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n\n api_id (`int` | `str`, default=0):\n The API ID you obtained from https://my.telegram.org.\n\n api_hash (`str`, default=None):\n The API hash you obtained from https://my.telegram.org.\n\n connection (`telethon.network.connection.common.Connection`, default=ConnectionTcpFull):\n The connection instance to be used when creating a new connection\n to the servers. It **must** be a type.\n\n Defaults to `telethon.network.connection.tcpfull.ConnectionTcpFull`.\n\n use_ipv6 (`bool`, default=False):\n Whether to connect to the servers through IPv6 or not.\n By default this is `False` as IPv6 support is not\n too widespread yet.\n\n proxy (`tuple` | `list` | `dict`, default=None):\n An iterable consisting of the proxy info. If `connection` is\n one of `MTProxy`, then it should contain MTProxy credentials:\n ``(\'hostname\', port, \'secret\')``. Otherwise, it\'s meant to store\n function parameters for PySocks, like ``(type, \'hostname\', port)``.\n See https://github.com/Anorov/PySocks#usage-1 for more.\n\n local_addr (`str` | `tuple`, default=None):\n Local host address (and port, optionally) used to bind the socket to locally.\n You only need to use this if you have multiple network cards and\n want to use a specific one.\n\n timeout (`int` | `float`, default=10):\n The timeout in seconds to be used when connecting.\n This is **not** the timeout to be used when ``await``\'ing for\n invoked requests, and you should use ``asyncio.wait`` or\n ``asyncio.wait_for`` for that.\n\n request_retries (`int` | `None`, default=5):\n How many times a request should be retried. Request are retried\n when Telegram is having internal issues (due to either\n ``errors.ServerError`` or ``errors.RpcCallFailError``),\n when there is a ``errors.FloodWaitError`` less than\n `flood_sleep_threshold`, or when there\'s a migrate error.\n\n May take a negative or `None` value for infinite retries, but\n this is not recommended, since some requests can always trigger\n a call fail (such as searching for messages).\n\n connection_retries (`int` | `None`, default=5):\n How many times the reconnection should retry, either on the\n initial connection or when Telegram disconnects us. May be\n set to a negative or `None` value for infinite retries, but\n this is not recommended, since the program can get stuck in an\n infinite loop.\n\n retry_delay (`int` | `float`, default=1):\n The delay in seconds to sleep between automatic reconnections.\n\n auto_reconnect (`bool`, default=True):\n Whether reconnection should be retried `connection_retries`\n times automatically if Telegram disconnects us or not.\n\n sequential_updates (`bool`, default=False):\n By default every incoming update will create a new task, so\n you can handle several updates in parallel. Some scripts need\n the order in which updates are processed to be sequential, and\n this setting allows them to do so.\n\n If set to `True`, incoming updates will be put in a queue\n and processed sequentially. This means your event handlers\n should *not* perform long-running operations since new\n updates are put inside of an unbounded queue.\n\n flood_sleep_threshold (`int` | `float`, default=60):\n The threshold below which the library should automatically\n sleep on flood wait and slow mode wait errors (inclusive). For instance, if a\n ``FloodWaitError`` for 17s occurs and `flood_sleep_threshold`\n is 20s, the library will ``sleep`` automatically. If the error\n was for 21s, it would ``raise FloodWaitError`` instead. Values\n larger than a day (like ``float(\'inf\')``) will be changed to a day.\n\n raise_last_call_error (`bool`, default=False):\n When API calls fail in a way that causes Telethon to retry\n automatically, should the RPC error of the last attempt be raised\n instead of a generic ValueError. This is mostly useful for\n detecting when Telegram has internal issues.\n\n device_model (`str`, default=None):\n "Device model" to be sent when creating the initial connection.\n Defaults to \'PC (n)bit\' derived from ``platform.uname().machine``, or its direct value if unknown.\n\n system_version (`str`, default=None):\n "System version" to be sent when creating the initial connection.\n Defaults to ``platform.uname().release`` stripped of everything ahead of -.\n\n app_version (`str`, default=None):\n "App version" to be sent when creating the initial connection.\n Defaults to `telethon.version.__version__`.\n\n lang_code (`str`, default=\'en\'):\n "Language code" to be sent when creating the initial connection.\n Defaults to ``\'en\'``.\n\n system_lang_code (`str`, default=\'en\'):\n "System lang code" to be sent when creating the initial connection.\n Defaults to `lang_code`.\n\n loop (`asyncio.AbstractEventLoop`, default=None):\n Asyncio event loop to use. Defaults to `asyncio.get_event_loop()`.\n This argument is ignored.\n\n base_logger (`str` | `logging.Logger`, default=None):\n Base logger name or instance to use.\n If a `str` is given, it\'ll be passed to `logging.getLogger()`. If a\n `logging.Logger` is given, it\'ll be used directly. If something\n else or nothing is given, the default logger will be used.\n\n receive_updates (`bool`, default=True):\n Whether the client will receive updates or not. By default, updates\n will be received from Telegram as they occur.\n\n Turning this off means that Telegram will not send updates at all\n so event handlers, conversations, and QR login will not work.\n However, certain scripts don\'t need updates, so this will reduce\n the amount of bandwidth used.\n \n ' | !skip
This is the abstract base class for the client. It defines some
basic stuff like connecting, switching data center, etc, and
leaves the `__call__` unimplemented.
### Arguments:
session (`str` | `Session`, default=`None`):
The file name of the `session file` to be used, if a string is\
given (it may be a full path), or the `Session` instance to be used\
Otherwise, if it's `None`, the `session` will not be saved,\
and you should call method `.log_out()` when you're done.
Note that if you pass a string it will be a file in the current working directory, although you can also pass absolute paths.\
The session file contains enough information for you to login\
without re-sending the code, so if you have to enter the code\
more than once, maybe you're changing the working directory,\
renaming or removing the file, or using random names.
api (`API`, default=None):
Use custom api_id and api_hash for better experience.
These arguments will be ignored if it is set in the API: `api_id`, `api_hash`, `device_model`, `system_version`, `app_version`, `lang_code`, `system_lang_code`
Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)
api_id (`int` | `str`, default=0):
The API ID you obtained from https://my.telegram.org.
api_hash (`str`, default=None):
The API hash you obtained from https://my.telegram.org.
connection (`telethon.network.connection.common.Connection`, default=ConnectionTcpFull):
The connection instance to be used when creating a new connection
to the servers. It **must** be a type.
Defaults to `telethon.network.connection.tcpfull.ConnectionTcpFull`.
use_ipv6 (`bool`, default=False):
Whether to connect to the servers through IPv6 or not.
By default this is `False` as IPv6 support is not
too widespread yet.
proxy (`tuple` | `list` | `dict`, default=None):
An iterable consisting of the proxy info. If `connection` is
one of `MTProxy`, then it should contain MTProxy credentials:
``('hostname', port, 'secret')``. Otherwise, it's meant to store
function parameters for PySocks, like ``(type, 'hostname', port)``.
See https://github.com/Anorov/PySocks#usage-1 for more.
local_addr (`str` | `tuple`, default=None):
Local host address (and port, optionally) used to bind the socket to locally.
You only need to use this if you have multiple network cards and
want to use a specific one.
timeout (`int` | `float`, default=10):
The timeout in seconds to be used when connecting.
This is **not** the timeout to be used when ``await``'ing for
invoked requests, and you should use ``asyncio.wait`` or
``asyncio.wait_for`` for that.
request_retries (`int` | `None`, default=5):
How many times a request should be retried. Request are retried
when Telegram is having internal issues (due to either
``errors.ServerError`` or ``errors.RpcCallFailError``),
when there is a ``errors.FloodWaitError`` less than
`flood_sleep_threshold`, or when there's a migrate error.
May take a negative or `None` value for infinite retries, but
this is not recommended, since some requests can always trigger
a call fail (such as searching for messages).
connection_retries (`int` | `None`, default=5):
How many times the reconnection should retry, either on the
initial connection or when Telegram disconnects us. May be
set to a negative or `None` value for infinite retries, but
this is not recommended, since the program can get stuck in an
infinite loop.
retry_delay (`int` | `float`, default=1):
The delay in seconds to sleep between automatic reconnections.
auto_reconnect (`bool`, default=True):
Whether reconnection should be retried `connection_retries`
times automatically if Telegram disconnects us or not.
sequential_updates (`bool`, default=False):
By default every incoming update will create a new task, so
you can handle several updates in parallel. Some scripts need
the order in which updates are processed to be sequential, and
this setting allows them to do so.
If set to `True`, incoming updates will be put in a queue
and processed sequentially. This means your event handlers
should *not* perform long-running operations since new
updates are put inside of an unbounded queue.
flood_sleep_threshold (`int` | `float`, default=60):
The threshold below which the library should automatically
sleep on flood wait and slow mode wait errors (inclusive). For instance, if a
``FloodWaitError`` for 17s occurs and `flood_sleep_threshold`
is 20s, the library will ``sleep`` automatically. If the error
was for 21s, it would ``raise FloodWaitError`` instead. Values
larger than a day (like ``float('inf')``) will be changed to a day.
raise_last_call_error (`bool`, default=False):
When API calls fail in a way that causes Telethon to retry
automatically, should the RPC error of the last attempt be raised
instead of a generic ValueError. This is mostly useful for
detecting when Telegram has internal issues.
device_model (`str`, default=None):
"Device model" to be sent when creating the initial connection.
Defaults to 'PC (n)bit' derived from ``platform.uname().machine``, or its direct value if unknown.
system_version (`str`, default=None):
"System version" to be sent when creating the initial connection.
Defaults to ``platform.uname().release`` stripped of everything ahead of -.
app_version (`str`, default=None):
"App version" to be sent when creating the initial connection.
Defaults to `telethon.version.__version__`.
lang_code (`str`, default='en'):
"Language code" to be sent when creating the initial connection.
Defaults to ``'en'``.
system_lang_code (`str`, default='en'):
"System lang code" to be sent when creating the initial connection.
Defaults to `lang_code`.
loop (`asyncio.AbstractEventLoop`, default=None):
Asyncio event loop to use. Defaults to `asyncio.get_event_loop()`.
This argument is ignored.
base_logger (`str` | `logging.Logger`, default=None):
Base logger name or instance to use.
If a `str` is given, it'll be passed to `logging.getLogger()`. If a
`logging.Logger` is given, it'll be used directly. If something
else or nothing is given, the default logger will be used.
receive_updates (`bool`, default=True):
Whether the client will receive updates or not. By default, updates
will be received from Telegram as they occur.
Turning this off means that Telegram will not send updates at all
so event handlers, conversations, and QR login will not work.
However, certain scripts don't need updates, so this will reduce
the amount of bandwidth used. | src/tl/telethon.py | __init__ | annihilatorrrr/opentele | 30 | python | @typing.overload
def __init__(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=None, api_id: int=0, api_hash: str=None, *, connection: typing.Type[Connection]=ConnectionTcpFull, use_ipv6: bool=False, proxy: Union[(tuple, dict)]=None, local_addr: Union[(str, tuple)]=None, timeout: int=10, request_retries: int=5, connection_retries: int=5, retry_delay: int=1, auto_reconnect: bool=True, sequential_updates: bool=False, flood_sleep_threshold: int=60, raise_last_call_error: bool=False, device_model: str=None, system_version: str=None, app_version: str=None, lang_code: str='en', system_lang_code: str='en', loop: asyncio.AbstractEventLoop=None, base_logger: Union[(str, logging.Logger)]=None, receive_updates: bool=True):
'\n !skip\n This is the abstract base class for the client. It defines some\n basic stuff like connecting, switching data center, etc, and\n leaves the `__call__` unimplemented.\n\n ### Arguments:\n session (`str` | `Session`, default=`None`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it\'s `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you\'re done.\n\n Note that if you pass a string it will be a file in the current working directory, although you can also pass absolute paths.\\\n\n The session file contains enough information for you to login\\\n without re-sending the code, so if you have to enter the code\\\n more than once, maybe you\'re changing the working directory,\\\n renaming or removing the file, or using random names.\n\n api (`API`, default=None):\n Use custom api_id and api_hash for better experience.\n\n These arguments will be ignored if it is set in the API: `api_id`, `api_hash`, `device_model`, `system_version`, `app_version`, `lang_code`, `system_lang_code`\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n\n api_id (`int` | `str`, default=0):\n The API ID you obtained from https://my.telegram.org.\n\n api_hash (`str`, default=None):\n The API hash you obtained from https://my.telegram.org.\n\n connection (`telethon.network.connection.common.Connection`, default=ConnectionTcpFull):\n The connection instance to be used when creating a new connection\n to the servers. It **must** be a type.\n\n Defaults to `telethon.network.connection.tcpfull.ConnectionTcpFull`.\n\n use_ipv6 (`bool`, default=False):\n Whether to connect to the servers through IPv6 or not.\n By default this is `False` as IPv6 support is not\n too widespread yet.\n\n proxy (`tuple` | `list` | `dict`, default=None):\n An iterable consisting of the proxy info. If `connection` is\n one of `MTProxy`, then it should contain MTProxy credentials:\n ``(\'hostname\', port, \'secret\')``. Otherwise, it\'s meant to store\n function parameters for PySocks, like ``(type, \'hostname\', port)``.\n See https://github.com/Anorov/PySocks#usage-1 for more.\n\n local_addr (`str` | `tuple`, default=None):\n Local host address (and port, optionally) used to bind the socket to locally.\n You only need to use this if you have multiple network cards and\n want to use a specific one.\n\n timeout (`int` | `float`, default=10):\n The timeout in seconds to be used when connecting.\n This is **not** the timeout to be used when ``await``\'ing for\n invoked requests, and you should use ``asyncio.wait`` or\n ``asyncio.wait_for`` for that.\n\n request_retries (`int` | `None`, default=5):\n How many times a request should be retried. Request are retried\n when Telegram is having internal issues (due to either\n ``errors.ServerError`` or ``errors.RpcCallFailError``),\n when there is a ``errors.FloodWaitError`` less than\n `flood_sleep_threshold`, or when there\'s a migrate error.\n\n May take a negative or `None` value for infinite retries, but\n this is not recommended, since some requests can always trigger\n a call fail (such as searching for messages).\n\n connection_retries (`int` | `None`, default=5):\n How many times the reconnection should retry, either on the\n initial connection or when Telegram disconnects us. May be\n set to a negative or `None` value for infinite retries, but\n this is not recommended, since the program can get stuck in an\n infinite loop.\n\n retry_delay (`int` | `float`, default=1):\n The delay in seconds to sleep between automatic reconnections.\n\n auto_reconnect (`bool`, default=True):\n Whether reconnection should be retried `connection_retries`\n times automatically if Telegram disconnects us or not.\n\n sequential_updates (`bool`, default=False):\n By default every incoming update will create a new task, so\n you can handle several updates in parallel. Some scripts need\n the order in which updates are processed to be sequential, and\n this setting allows them to do so.\n\n If set to `True`, incoming updates will be put in a queue\n and processed sequentially. This means your event handlers\n should *not* perform long-running operations since new\n updates are put inside of an unbounded queue.\n\n flood_sleep_threshold (`int` | `float`, default=60):\n The threshold below which the library should automatically\n sleep on flood wait and slow mode wait errors (inclusive). For instance, if a\n ``FloodWaitError`` for 17s occurs and `flood_sleep_threshold`\n is 20s, the library will ``sleep`` automatically. If the error\n was for 21s, it would ``raise FloodWaitError`` instead. Values\n larger than a day (like ``float(\'inf\')``) will be changed to a day.\n\n raise_last_call_error (`bool`, default=False):\n When API calls fail in a way that causes Telethon to retry\n automatically, should the RPC error of the last attempt be raised\n instead of a generic ValueError. This is mostly useful for\n detecting when Telegram has internal issues.\n\n device_model (`str`, default=None):\n "Device model" to be sent when creating the initial connection.\n Defaults to \'PC (n)bit\' derived from ``platform.uname().machine``, or its direct value if unknown.\n\n system_version (`str`, default=None):\n "System version" to be sent when creating the initial connection.\n Defaults to ``platform.uname().release`` stripped of everything ahead of -.\n\n app_version (`str`, default=None):\n "App version" to be sent when creating the initial connection.\n Defaults to `telethon.version.__version__`.\n\n lang_code (`str`, default=\'en\'):\n "Language code" to be sent when creating the initial connection.\n Defaults to ``\'en\'``.\n\n system_lang_code (`str`, default=\'en\'):\n "System lang code" to be sent when creating the initial connection.\n Defaults to `lang_code`.\n\n loop (`asyncio.AbstractEventLoop`, default=None):\n Asyncio event loop to use. Defaults to `asyncio.get_event_loop()`.\n This argument is ignored.\n\n base_logger (`str` | `logging.Logger`, default=None):\n Base logger name or instance to use.\n If a `str` is given, it\'ll be passed to `logging.getLogger()`. If a\n `logging.Logger` is given, it\'ll be used directly. If something\n else or nothing is given, the default logger will be used.\n\n receive_updates (`bool`, default=True):\n Whether the client will receive updates or not. By default, updates\n will be received from Telegram as they occur.\n\n Turning this off means that Telegram will not send updates at all\n so event handlers, conversations, and QR login will not work.\n However, certain scripts don\'t need updates, so this will reduce\n the amount of bandwidth used.\n \n ' | @typing.overload
def __init__(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=None, api_id: int=0, api_hash: str=None, *, connection: typing.Type[Connection]=ConnectionTcpFull, use_ipv6: bool=False, proxy: Union[(tuple, dict)]=None, local_addr: Union[(str, tuple)]=None, timeout: int=10, request_retries: int=5, connection_retries: int=5, retry_delay: int=1, auto_reconnect: bool=True, sequential_updates: bool=False, flood_sleep_threshold: int=60, raise_last_call_error: bool=False, device_model: str=None, system_version: str=None, app_version: str=None, lang_code: str='en', system_lang_code: str='en', loop: asyncio.AbstractEventLoop=None, base_logger: Union[(str, logging.Logger)]=None, receive_updates: bool=True):
'\n !skip\n This is the abstract base class for the client. It defines some\n basic stuff like connecting, switching data center, etc, and\n leaves the `__call__` unimplemented.\n\n ### Arguments:\n session (`str` | `Session`, default=`None`):\n The file name of the `session file` to be used, if a string is\\\n given (it may be a full path), or the `Session` instance to be used\\\n Otherwise, if it\'s `None`, the `session` will not be saved,\\\n and you should call method `.log_out()` when you\'re done.\n\n Note that if you pass a string it will be a file in the current working directory, although you can also pass absolute paths.\\\n\n The session file contains enough information for you to login\\\n without re-sending the code, so if you have to enter the code\\\n more than once, maybe you\'re changing the working directory,\\\n renaming or removing the file, or using random names.\n\n api (`API`, default=None):\n Use custom api_id and api_hash for better experience.\n\n These arguments will be ignored if it is set in the API: `api_id`, `api_hash`, `device_model`, `system_version`, `app_version`, `lang_code`, `system_lang_code`\n Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)\n\n api_id (`int` | `str`, default=0):\n The API ID you obtained from https://my.telegram.org.\n\n api_hash (`str`, default=None):\n The API hash you obtained from https://my.telegram.org.\n\n connection (`telethon.network.connection.common.Connection`, default=ConnectionTcpFull):\n The connection instance to be used when creating a new connection\n to the servers. It **must** be a type.\n\n Defaults to `telethon.network.connection.tcpfull.ConnectionTcpFull`.\n\n use_ipv6 (`bool`, default=False):\n Whether to connect to the servers through IPv6 or not.\n By default this is `False` as IPv6 support is not\n too widespread yet.\n\n proxy (`tuple` | `list` | `dict`, default=None):\n An iterable consisting of the proxy info. If `connection` is\n one of `MTProxy`, then it should contain MTProxy credentials:\n ``(\'hostname\', port, \'secret\')``. Otherwise, it\'s meant to store\n function parameters for PySocks, like ``(type, \'hostname\', port)``.\n See https://github.com/Anorov/PySocks#usage-1 for more.\n\n local_addr (`str` | `tuple`, default=None):\n Local host address (and port, optionally) used to bind the socket to locally.\n You only need to use this if you have multiple network cards and\n want to use a specific one.\n\n timeout (`int` | `float`, default=10):\n The timeout in seconds to be used when connecting.\n This is **not** the timeout to be used when ``await``\'ing for\n invoked requests, and you should use ``asyncio.wait`` or\n ``asyncio.wait_for`` for that.\n\n request_retries (`int` | `None`, default=5):\n How many times a request should be retried. Request are retried\n when Telegram is having internal issues (due to either\n ``errors.ServerError`` or ``errors.RpcCallFailError``),\n when there is a ``errors.FloodWaitError`` less than\n `flood_sleep_threshold`, or when there\'s a migrate error.\n\n May take a negative or `None` value for infinite retries, but\n this is not recommended, since some requests can always trigger\n a call fail (such as searching for messages).\n\n connection_retries (`int` | `None`, default=5):\n How many times the reconnection should retry, either on the\n initial connection or when Telegram disconnects us. May be\n set to a negative or `None` value for infinite retries, but\n this is not recommended, since the program can get stuck in an\n infinite loop.\n\n retry_delay (`int` | `float`, default=1):\n The delay in seconds to sleep between automatic reconnections.\n\n auto_reconnect (`bool`, default=True):\n Whether reconnection should be retried `connection_retries`\n times automatically if Telegram disconnects us or not.\n\n sequential_updates (`bool`, default=False):\n By default every incoming update will create a new task, so\n you can handle several updates in parallel. Some scripts need\n the order in which updates are processed to be sequential, and\n this setting allows them to do so.\n\n If set to `True`, incoming updates will be put in a queue\n and processed sequentially. This means your event handlers\n should *not* perform long-running operations since new\n updates are put inside of an unbounded queue.\n\n flood_sleep_threshold (`int` | `float`, default=60):\n The threshold below which the library should automatically\n sleep on flood wait and slow mode wait errors (inclusive). For instance, if a\n ``FloodWaitError`` for 17s occurs and `flood_sleep_threshold`\n is 20s, the library will ``sleep`` automatically. If the error\n was for 21s, it would ``raise FloodWaitError`` instead. Values\n larger than a day (like ``float(\'inf\')``) will be changed to a day.\n\n raise_last_call_error (`bool`, default=False):\n When API calls fail in a way that causes Telethon to retry\n automatically, should the RPC error of the last attempt be raised\n instead of a generic ValueError. This is mostly useful for\n detecting when Telegram has internal issues.\n\n device_model (`str`, default=None):\n "Device model" to be sent when creating the initial connection.\n Defaults to \'PC (n)bit\' derived from ``platform.uname().machine``, or its direct value if unknown.\n\n system_version (`str`, default=None):\n "System version" to be sent when creating the initial connection.\n Defaults to ``platform.uname().release`` stripped of everything ahead of -.\n\n app_version (`str`, default=None):\n "App version" to be sent when creating the initial connection.\n Defaults to `telethon.version.__version__`.\n\n lang_code (`str`, default=\'en\'):\n "Language code" to be sent when creating the initial connection.\n Defaults to ``\'en\'``.\n\n system_lang_code (`str`, default=\'en\'):\n "System lang code" to be sent when creating the initial connection.\n Defaults to `lang_code`.\n\n loop (`asyncio.AbstractEventLoop`, default=None):\n Asyncio event loop to use. Defaults to `asyncio.get_event_loop()`.\n This argument is ignored.\n\n base_logger (`str` | `logging.Logger`, default=None):\n Base logger name or instance to use.\n If a `str` is given, it\'ll be passed to `logging.getLogger()`. If a\n `logging.Logger` is given, it\'ll be used directly. If something\n else or nothing is given, the default logger will be used.\n\n receive_updates (`bool`, default=True):\n Whether the client will receive updates or not. By default, updates\n will be received from Telegram as they occur.\n\n Turning this off means that Telegram will not send updates at all\n so event handlers, conversations, and QR login will not work.\n However, certain scripts don\'t need updates, so this will reduce\n the amount of bandwidth used.\n \n '<|docstring|>!skip
This is the abstract base class for the client. It defines some
basic stuff like connecting, switching data center, etc, and
leaves the `__call__` unimplemented.
### Arguments:
session (`str` | `Session`, default=`None`):
The file name of the `session file` to be used, if a string is\
given (it may be a full path), or the `Session` instance to be used\
Otherwise, if it's `None`, the `session` will not be saved,\
and you should call method `.log_out()` when you're done.
Note that if you pass a string it will be a file in the current working directory, although you can also pass absolute paths.\
The session file contains enough information for you to login\
without re-sending the code, so if you have to enter the code\
more than once, maybe you're changing the working directory,\
renaming or removing the file, or using random names.
api (`API`, default=None):
Use custom api_id and api_hash for better experience.
These arguments will be ignored if it is set in the API: `api_id`, `api_hash`, `device_model`, `system_version`, `app_version`, `lang_code`, `system_lang_code`
Read more at [opentele GitHub](https://github.com/thedemons/opentele#authorization)
api_id (`int` | `str`, default=0):
The API ID you obtained from https://my.telegram.org.
api_hash (`str`, default=None):
The API hash you obtained from https://my.telegram.org.
connection (`telethon.network.connection.common.Connection`, default=ConnectionTcpFull):
The connection instance to be used when creating a new connection
to the servers. It **must** be a type.
Defaults to `telethon.network.connection.tcpfull.ConnectionTcpFull`.
use_ipv6 (`bool`, default=False):
Whether to connect to the servers through IPv6 or not.
By default this is `False` as IPv6 support is not
too widespread yet.
proxy (`tuple` | `list` | `dict`, default=None):
An iterable consisting of the proxy info. If `connection` is
one of `MTProxy`, then it should contain MTProxy credentials:
``('hostname', port, 'secret')``. Otherwise, it's meant to store
function parameters for PySocks, like ``(type, 'hostname', port)``.
See https://github.com/Anorov/PySocks#usage-1 for more.
local_addr (`str` | `tuple`, default=None):
Local host address (and port, optionally) used to bind the socket to locally.
You only need to use this if you have multiple network cards and
want to use a specific one.
timeout (`int` | `float`, default=10):
The timeout in seconds to be used when connecting.
This is **not** the timeout to be used when ``await``'ing for
invoked requests, and you should use ``asyncio.wait`` or
``asyncio.wait_for`` for that.
request_retries (`int` | `None`, default=5):
How many times a request should be retried. Request are retried
when Telegram is having internal issues (due to either
``errors.ServerError`` or ``errors.RpcCallFailError``),
when there is a ``errors.FloodWaitError`` less than
`flood_sleep_threshold`, or when there's a migrate error.
May take a negative or `None` value for infinite retries, but
this is not recommended, since some requests can always trigger
a call fail (such as searching for messages).
connection_retries (`int` | `None`, default=5):
How many times the reconnection should retry, either on the
initial connection or when Telegram disconnects us. May be
set to a negative or `None` value for infinite retries, but
this is not recommended, since the program can get stuck in an
infinite loop.
retry_delay (`int` | `float`, default=1):
The delay in seconds to sleep between automatic reconnections.
auto_reconnect (`bool`, default=True):
Whether reconnection should be retried `connection_retries`
times automatically if Telegram disconnects us or not.
sequential_updates (`bool`, default=False):
By default every incoming update will create a new task, so
you can handle several updates in parallel. Some scripts need
the order in which updates are processed to be sequential, and
this setting allows them to do so.
If set to `True`, incoming updates will be put in a queue
and processed sequentially. This means your event handlers
should *not* perform long-running operations since new
updates are put inside of an unbounded queue.
flood_sleep_threshold (`int` | `float`, default=60):
The threshold below which the library should automatically
sleep on flood wait and slow mode wait errors (inclusive). For instance, if a
``FloodWaitError`` for 17s occurs and `flood_sleep_threshold`
is 20s, the library will ``sleep`` automatically. If the error
was for 21s, it would ``raise FloodWaitError`` instead. Values
larger than a day (like ``float('inf')``) will be changed to a day.
raise_last_call_error (`bool`, default=False):
When API calls fail in a way that causes Telethon to retry
automatically, should the RPC error of the last attempt be raised
instead of a generic ValueError. This is mostly useful for
detecting when Telegram has internal issues.
device_model (`str`, default=None):
"Device model" to be sent when creating the initial connection.
Defaults to 'PC (n)bit' derived from ``platform.uname().machine``, or its direct value if unknown.
system_version (`str`, default=None):
"System version" to be sent when creating the initial connection.
Defaults to ``platform.uname().release`` stripped of everything ahead of -.
app_version (`str`, default=None):
"App version" to be sent when creating the initial connection.
Defaults to `telethon.version.__version__`.
lang_code (`str`, default='en'):
"Language code" to be sent when creating the initial connection.
Defaults to ``'en'``.
system_lang_code (`str`, default='en'):
"System lang code" to be sent when creating the initial connection.
Defaults to `lang_code`.
loop (`asyncio.AbstractEventLoop`, default=None):
Asyncio event loop to use. Defaults to `asyncio.get_event_loop()`.
This argument is ignored.
base_logger (`str` | `logging.Logger`, default=None):
Base logger name or instance to use.
If a `str` is given, it'll be passed to `logging.getLogger()`. If a
`logging.Logger` is given, it'll be used directly. If something
else or nothing is given, the default logger will be used.
receive_updates (`bool`, default=True):
Whether the client will receive updates or not. By default, updates
will be received from Telegram as they occur.
Turning this off means that Telegram will not send updates at all
so event handlers, conversations, and QR login will not work.
However, certain scripts don't need updates, so this will reduce
the amount of bandwidth used.<|endoftext|> |
bb18e685c21590d954903b62d70ec66501ff520b8fee78f0f9a006f7ea51f820 | async def GetSessions(self) -> Optional[types.account.Authorizations]:
'\n Get all logged-in sessions.\n\n ### Returns:\n - Return an instance of `Authorizations` on success\n '
return (await self(functions.account.GetAuthorizationsRequest())) | Get all logged-in sessions.
### Returns:
- Return an instance of `Authorizations` on success | src/tl/telethon.py | GetSessions | annihilatorrrr/opentele | 30 | python | async def GetSessions(self) -> Optional[types.account.Authorizations]:
'\n Get all logged-in sessions.\n\n ### Returns:\n - Return an instance of `Authorizations` on success\n '
return (await self(functions.account.GetAuthorizationsRequest())) | async def GetSessions(self) -> Optional[types.account.Authorizations]:
'\n Get all logged-in sessions.\n\n ### Returns:\n - Return an instance of `Authorizations` on success\n '
return (await self(functions.account.GetAuthorizationsRequest()))<|docstring|>Get all logged-in sessions.
### Returns:
- Return an instance of `Authorizations` on success<|endoftext|> |
a163a33e8019591038e3d99416f65f3207f90313a1998df9b05cfd4a5899aa37 | async def GetCurrentSession(self) -> Optional[types.Authorization]:
'\n Get current logged-in session.\n\n ### Returns:\n Return `telethon.types.Authorization` on success.\n Return `None` on failure.\n '
results = (await self.GetSessions())
return (next((auth for auth in results.authorizations if auth.current), None) if (results != None) else None) | Get current logged-in session.
### Returns:
Return `telethon.types.Authorization` on success.
Return `None` on failure. | src/tl/telethon.py | GetCurrentSession | annihilatorrrr/opentele | 30 | python | async def GetCurrentSession(self) -> Optional[types.Authorization]:
'\n Get current logged-in session.\n\n ### Returns:\n Return `telethon.types.Authorization` on success.\n Return `None` on failure.\n '
results = (await self.GetSessions())
return (next((auth for auth in results.authorizations if auth.current), None) if (results != None) else None) | async def GetCurrentSession(self) -> Optional[types.Authorization]:
'\n Get current logged-in session.\n\n ### Returns:\n Return `telethon.types.Authorization` on success.\n Return `None` on failure.\n '
results = (await self.GetSessions())
return (next((auth for auth in results.authorizations if auth.current), None) if (results != None) else None)<|docstring|>Get current logged-in session.
### Returns:
Return `telethon.types.Authorization` on success.
Return `None` on failure.<|endoftext|> |
11f4f526c43c100dfe905d1632f7784aa3d1f5f9cf536916c49fc992400e57e4 | async def TerminateSession(self, hash: int):
"\n Terminate a specific session\n\n ### Arguments:\n hash (`int`):\n The `session`'s hash to terminate\n\n ### Raises:\n `FreshResetAuthorisationForbiddenError`: You can't log out other `sessions` if less than `24 hours` have passed since you logged on to the `current session`.\n `HashInvalidError`: The provided hash is invalid.\n "
try:
(await self(functions.account.ResetAuthorizationRequest(hash)))
except FreshResetAuthorisationForbiddenError as e:
raise FreshResetAuthorisationForbiddenError("You can't logout other sessions if less than 24 hours have passed since you logged on the current session.")
except HashInvalidError as e:
raise HashInvalidError('The provided hash is invalid.') | Terminate a specific session
### Arguments:
hash (`int`):
The `session`'s hash to terminate
### Raises:
`FreshResetAuthorisationForbiddenError`: You can't log out other `sessions` if less than `24 hours` have passed since you logged on to the `current session`.
`HashInvalidError`: The provided hash is invalid. | src/tl/telethon.py | TerminateSession | annihilatorrrr/opentele | 30 | python | async def TerminateSession(self, hash: int):
"\n Terminate a specific session\n\n ### Arguments:\n hash (`int`):\n The `session`'s hash to terminate\n\n ### Raises:\n `FreshResetAuthorisationForbiddenError`: You can't log out other `sessions` if less than `24 hours` have passed since you logged on to the `current session`.\n `HashInvalidError`: The provided hash is invalid.\n "
try:
(await self(functions.account.ResetAuthorizationRequest(hash)))
except FreshResetAuthorisationForbiddenError as e:
raise FreshResetAuthorisationForbiddenError("You can't logout other sessions if less than 24 hours have passed since you logged on the current session.")
except HashInvalidError as e:
raise HashInvalidError('The provided hash is invalid.') | async def TerminateSession(self, hash: int):
"\n Terminate a specific session\n\n ### Arguments:\n hash (`int`):\n The `session`'s hash to terminate\n\n ### Raises:\n `FreshResetAuthorisationForbiddenError`: You can't log out other `sessions` if less than `24 hours` have passed since you logged on to the `current session`.\n `HashInvalidError`: The provided hash is invalid.\n "
try:
(await self(functions.account.ResetAuthorizationRequest(hash)))
except FreshResetAuthorisationForbiddenError as e:
raise FreshResetAuthorisationForbiddenError("You can't logout other sessions if less than 24 hours have passed since you logged on the current session.")
except HashInvalidError as e:
raise HashInvalidError('The provided hash is invalid.')<|docstring|>Terminate a specific session
### Arguments:
hash (`int`):
The `session`'s hash to terminate
### Raises:
`FreshResetAuthorisationForbiddenError`: You can't log out other `sessions` if less than `24 hours` have passed since you logged on to the `current session`.
`HashInvalidError`: The provided hash is invalid.<|endoftext|> |
21ade977914f819ecf0ed9f85bdfb1b58ad307776b76a83b93f709bcddee83fd | async def TerminateAllSessions(self) -> bool:
'\n Terminate all other sessions.\n '
sessions = (await self.GetSessions())
if (sessions == None):
return False
for ss in sessions.authorizations:
if (not ss.current):
(await self.TerminateSession(ss.hash))
return True | Terminate all other sessions. | src/tl/telethon.py | TerminateAllSessions | annihilatorrrr/opentele | 30 | python | async def TerminateAllSessions(self) -> bool:
'\n \n '
sessions = (await self.GetSessions())
if (sessions == None):
return False
for ss in sessions.authorizations:
if (not ss.current):
(await self.TerminateSession(ss.hash))
return True | async def TerminateAllSessions(self) -> bool:
'\n \n '
sessions = (await self.GetSessions())
if (sessions == None):
return False
for ss in sessions.authorizations:
if (not ss.current):
(await self.TerminateSession(ss.hash))
return True<|docstring|>Terminate all other sessions.<|endoftext|> |
3a1b90339fb53be2747cef333c8f35b4afba6ed9cca666497414b8370825fdac | async def PrintSessions(self, sessions: types.account.Authorizations=None):
'\n Pretty-print all logged-in sessions.\n\n ### Arguments:\n sessions (`Authorizations`, default=`None`):\n `Sessions` that return by `GetSessions()`, if `None` then it will `GetSessions()` first.\n\n ### Returns:\n On success, it should prints the sessions table as the code below.\n ```\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | | Device | Platform | System | API_ID | App name | Official App |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | Current | MacBook Pro | macOS | 10.15.6 | 2834 | Telegram macOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | 1 | Chrome 96 | Windows | | 2496 | Telegram Web 1.28.3 Z | ✔ |\n | 2 | iMac | macOS | 11.3.1 | 2834 | Telegram macOS 8.4 | ✔ |\n | 3 | MacBook Pro | macOS | 10.12 | 2834 | Telegram macOS 8.4 | ✔ |\n | 4 | Huawei Y360-U93 | Android | 7.1 N MR1 (25) | 21724 | Telegram Android X 8.4.1 | ✔ |\n | 5 | Samsung Galaxy Spica | Android | 6.0 M (23) | 6 | Telegram Android 8.4.1 | ✔ |\n | 6 | Xiaomi Redmi Note 8 | Android | 10 Q (29) | 6 | Telegram Android 8.4.1 | ✔ |\n | 7 | Samsung Galaxy Tab A (2017) | Android | 7.0 N (24) | 6 | Telegram Android 8.4.1 | ✔ |\n | 8 | Samsung Galaxy XCover Pro | Android | 8.0 O (26) | 6 | Telegram Android 8.4.1 | ✔ |\n | 9 | iPhone X | iOS | 13.1.3 | 10840 | Telegram iOS 8.4 | ✔ |\n | 10 | iPhone XS Max | iOS | 12.11.0 | 10840 | Telegram iOS 8.4 | ✔ |\n | 11 | iPhone 11 Pro Max | iOS | 14.4.2 | 10840 | Telegram iOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n ```\n\n '
if ((sessions == None) or (not isinstance(sessions, types.account.Authorizations))):
sessions = (await self.GetSessions())
assert sessions
table = []
index = 0
for session in sessions.authorizations:
table.append({' ': ('Current' if session.current else index), 'Device': session.device_model, 'Platform': session.platform, 'System': session.system_version, 'API_ID': session.api_id, 'App name': '{} {}'.format(session.app_name, session.app_version), 'Official App': ('✔' if session.official_app else '✖')})
index += 1
print(PrettyTable(table, [1])) | Pretty-print all logged-in sessions.
### Arguments:
sessions (`Authorizations`, default=`None`):
`Sessions` that return by `GetSessions()`, if `None` then it will `GetSessions()` first.
### Returns:
On success, it should prints the sessions table as the code below.
```
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| | Device | Platform | System | API_ID | App name | Official App |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| Current | MacBook Pro | macOS | 10.15.6 | 2834 | Telegram macOS 8.4 | ✔ |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| 1 | Chrome 96 | Windows | | 2496 | Telegram Web 1.28.3 Z | ✔ |
| 2 | iMac | macOS | 11.3.1 | 2834 | Telegram macOS 8.4 | ✔ |
| 3 | MacBook Pro | macOS | 10.12 | 2834 | Telegram macOS 8.4 | ✔ |
| 4 | Huawei Y360-U93 | Android | 7.1 N MR1 (25) | 21724 | Telegram Android X 8.4.1 | ✔ |
| 5 | Samsung Galaxy Spica | Android | 6.0 M (23) | 6 | Telegram Android 8.4.1 | ✔ |
| 6 | Xiaomi Redmi Note 8 | Android | 10 Q (29) | 6 | Telegram Android 8.4.1 | ✔ |
| 7 | Samsung Galaxy Tab A (2017) | Android | 7.0 N (24) | 6 | Telegram Android 8.4.1 | ✔ |
| 8 | Samsung Galaxy XCover Pro | Android | 8.0 O (26) | 6 | Telegram Android 8.4.1 | ✔ |
| 9 | iPhone X | iOS | 13.1.3 | 10840 | Telegram iOS 8.4 | ✔ |
| 10 | iPhone XS Max | iOS | 12.11.0 | 10840 | Telegram iOS 8.4 | ✔ |
| 11 | iPhone 11 Pro Max | iOS | 14.4.2 | 10840 | Telegram iOS 8.4 | ✔ |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
``` | src/tl/telethon.py | PrintSessions | annihilatorrrr/opentele | 30 | python | async def PrintSessions(self, sessions: types.account.Authorizations=None):
'\n Pretty-print all logged-in sessions.\n\n ### Arguments:\n sessions (`Authorizations`, default=`None`):\n `Sessions` that return by `GetSessions()`, if `None` then it will `GetSessions()` first.\n\n ### Returns:\n On success, it should prints the sessions table as the code below.\n ```\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | | Device | Platform | System | API_ID | App name | Official App |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | Current | MacBook Pro | macOS | 10.15.6 | 2834 | Telegram macOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | 1 | Chrome 96 | Windows | | 2496 | Telegram Web 1.28.3 Z | ✔ |\n | 2 | iMac | macOS | 11.3.1 | 2834 | Telegram macOS 8.4 | ✔ |\n | 3 | MacBook Pro | macOS | 10.12 | 2834 | Telegram macOS 8.4 | ✔ |\n | 4 | Huawei Y360-U93 | Android | 7.1 N MR1 (25) | 21724 | Telegram Android X 8.4.1 | ✔ |\n | 5 | Samsung Galaxy Spica | Android | 6.0 M (23) | 6 | Telegram Android 8.4.1 | ✔ |\n | 6 | Xiaomi Redmi Note 8 | Android | 10 Q (29) | 6 | Telegram Android 8.4.1 | ✔ |\n | 7 | Samsung Galaxy Tab A (2017) | Android | 7.0 N (24) | 6 | Telegram Android 8.4.1 | ✔ |\n | 8 | Samsung Galaxy XCover Pro | Android | 8.0 O (26) | 6 | Telegram Android 8.4.1 | ✔ |\n | 9 | iPhone X | iOS | 13.1.3 | 10840 | Telegram iOS 8.4 | ✔ |\n | 10 | iPhone XS Max | iOS | 12.11.0 | 10840 | Telegram iOS 8.4 | ✔ |\n | 11 | iPhone 11 Pro Max | iOS | 14.4.2 | 10840 | Telegram iOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n ```\n\n '
if ((sessions == None) or (not isinstance(sessions, types.account.Authorizations))):
sessions = (await self.GetSessions())
assert sessions
table = []
index = 0
for session in sessions.authorizations:
table.append({' ': ('Current' if session.current else index), 'Device': session.device_model, 'Platform': session.platform, 'System': session.system_version, 'API_ID': session.api_id, 'App name': '{} {}'.format(session.app_name, session.app_version), 'Official App': ('✔' if session.official_app else '✖')})
index += 1
print(PrettyTable(table, [1])) | async def PrintSessions(self, sessions: types.account.Authorizations=None):
'\n Pretty-print all logged-in sessions.\n\n ### Arguments:\n sessions (`Authorizations`, default=`None`):\n `Sessions` that return by `GetSessions()`, if `None` then it will `GetSessions()` first.\n\n ### Returns:\n On success, it should prints the sessions table as the code below.\n ```\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | | Device | Platform | System | API_ID | App name | Official App |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | Current | MacBook Pro | macOS | 10.15.6 | 2834 | Telegram macOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n | 1 | Chrome 96 | Windows | | 2496 | Telegram Web 1.28.3 Z | ✔ |\n | 2 | iMac | macOS | 11.3.1 | 2834 | Telegram macOS 8.4 | ✔ |\n | 3 | MacBook Pro | macOS | 10.12 | 2834 | Telegram macOS 8.4 | ✔ |\n | 4 | Huawei Y360-U93 | Android | 7.1 N MR1 (25) | 21724 | Telegram Android X 8.4.1 | ✔ |\n | 5 | Samsung Galaxy Spica | Android | 6.0 M (23) | 6 | Telegram Android 8.4.1 | ✔ |\n | 6 | Xiaomi Redmi Note 8 | Android | 10 Q (29) | 6 | Telegram Android 8.4.1 | ✔ |\n | 7 | Samsung Galaxy Tab A (2017) | Android | 7.0 N (24) | 6 | Telegram Android 8.4.1 | ✔ |\n | 8 | Samsung Galaxy XCover Pro | Android | 8.0 O (26) | 6 | Telegram Android 8.4.1 | ✔ |\n | 9 | iPhone X | iOS | 13.1.3 | 10840 | Telegram iOS 8.4 | ✔ |\n | 10 | iPhone XS Max | iOS | 12.11.0 | 10840 | Telegram iOS 8.4 | ✔ |\n | 11 | iPhone 11 Pro Max | iOS | 14.4.2 | 10840 | Telegram iOS 8.4 | ✔ |\n |---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|\n ```\n\n '
if ((sessions == None) or (not isinstance(sessions, types.account.Authorizations))):
sessions = (await self.GetSessions())
assert sessions
table = []
index = 0
for session in sessions.authorizations:
table.append({' ': ('Current' if session.current else index), 'Device': session.device_model, 'Platform': session.platform, 'System': session.system_version, 'API_ID': session.api_id, 'App name': '{} {}'.format(session.app_name, session.app_version), 'Official App': ('✔' if session.official_app else '✖')})
index += 1
print(PrettyTable(table, [1]))<|docstring|>Pretty-print all logged-in sessions.
### Arguments:
sessions (`Authorizations`, default=`None`):
`Sessions` that return by `GetSessions()`, if `None` then it will `GetSessions()` first.
### Returns:
On success, it should prints the sessions table as the code below.
```
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| | Device | Platform | System | API_ID | App name | Official App |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| Current | MacBook Pro | macOS | 10.15.6 | 2834 | Telegram macOS 8.4 | ✔ |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
| 1 | Chrome 96 | Windows | | 2496 | Telegram Web 1.28.3 Z | ✔ |
| 2 | iMac | macOS | 11.3.1 | 2834 | Telegram macOS 8.4 | ✔ |
| 3 | MacBook Pro | macOS | 10.12 | 2834 | Telegram macOS 8.4 | ✔ |
| 4 | Huawei Y360-U93 | Android | 7.1 N MR1 (25) | 21724 | Telegram Android X 8.4.1 | ✔ |
| 5 | Samsung Galaxy Spica | Android | 6.0 M (23) | 6 | Telegram Android 8.4.1 | ✔ |
| 6 | Xiaomi Redmi Note 8 | Android | 10 Q (29) | 6 | Telegram Android 8.4.1 | ✔ |
| 7 | Samsung Galaxy Tab A (2017) | Android | 7.0 N (24) | 6 | Telegram Android 8.4.1 | ✔ |
| 8 | Samsung Galaxy XCover Pro | Android | 8.0 O (26) | 6 | Telegram Android 8.4.1 | ✔ |
| 9 | iPhone X | iOS | 13.1.3 | 10840 | Telegram iOS 8.4 | ✔ |
| 10 | iPhone XS Max | iOS | 12.11.0 | 10840 | Telegram iOS 8.4 | ✔ |
| 11 | iPhone 11 Pro Max | iOS | 14.4.2 | 10840 | Telegram iOS 8.4 | ✔ |
|---------+-----------------------------+----------+----------------+--------+----------------------------+--------------|
```<|endoftext|> |
a7896dde02808dc41417d45fda6d29c27123268f8002fff4d189ed2e85dbf9bc | async def is_official_app(self) -> bool:
'\n Return `True` if this session was logged-in using an official app (`API`).\n '
auth = (await self.GetCurrentSession())
return (False if (auth == None) else bool(auth.official_app)) | Return `True` if this session was logged-in using an official app (`API`). | src/tl/telethon.py | is_official_app | annihilatorrrr/opentele | 30 | python | async def is_official_app(self) -> bool:
'\n \n '
auth = (await self.GetCurrentSession())
return (False if (auth == None) else bool(auth.official_app)) | async def is_official_app(self) -> bool:
'\n \n '
auth = (await self.GetCurrentSession())
return (False if (auth == None) else bool(auth.official_app))<|docstring|>Return `True` if this session was logged-in using an official app (`API`).<|endoftext|> |
feda1927bd826e8c9ed5c70db9e33a8307e21323639392a83cc9ea4c6fa9baff | @typing.overload
async def QRLoginToNewClient(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n Create a new session using the current session.\n\n ### Arguments:\n session (`str`, `Session`, default=`None`):\n description\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification password, set if needed.\n\n ### Raises:\n - `NoPasswordProvided`: The account\'s two-step verification is enabled and no `password` was provided. Please set the `password` parameters.\n - `PasswordIncorrect`: The two-step verification `password` is incorrect.\n - `TimeoutError`: Time out waiting for the client to be authorized.\n\n ### Returns:\n - Return an instance of `TelegramClient` on success.\n\n ### Examples:\n Use to current session to authorize a new session:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n newClient = await client.QRLoginToNewClient(session="new.session", api=newAPI)\n await newClient.connect()\n await newClient.PrintSessions()\n ```\n ' | Create a new session using the current session.
### Arguments:
session (`str`, `Session`, default=`None`):
description
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification password, set if needed.
### Raises:
- `NoPasswordProvided`: The account's two-step verification is enabled and no `password` was provided. Please set the `password` parameters.
- `PasswordIncorrect`: The two-step verification `password` is incorrect.
- `TimeoutError`: Time out waiting for the client to be authorized.
### Returns:
- Return an instance of `TelegramClient` on success.
### Examples:
Use to current session to authorize a new session:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")
oldclient = TelegramClient("old.session", api=oldAPI)
await oldClient.connect()
# We can safely authorize the new client with a different API.
newAPI = API.TelegramAndroid.Generate(unique_id="new.session")
newClient = await client.QRLoginToNewClient(session="new.session", api=newAPI)
await newClient.connect()
await newClient.PrintSessions()
``` | src/tl/telethon.py | QRLoginToNewClient | annihilatorrrr/opentele | 30 | python | @typing.overload
async def QRLoginToNewClient(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n Create a new session using the current session.\n\n ### Arguments:\n session (`str`, `Session`, default=`None`):\n description\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification password, set if needed.\n\n ### Raises:\n - `NoPasswordProvided`: The account\'s two-step verification is enabled and no `password` was provided. Please set the `password` parameters.\n - `PasswordIncorrect`: The two-step verification `password` is incorrect.\n - `TimeoutError`: Time out waiting for the client to be authorized.\n\n ### Returns:\n - Return an instance of `TelegramClient` on success.\n\n ### Examples:\n Use to current session to authorize a new session:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n newClient = await client.QRLoginToNewClient(session="new.session", api=newAPI)\n await newClient.connect()\n await newClient.PrintSessions()\n ```\n ' | @typing.overload
async def QRLoginToNewClient(self, session: Union[(str, Session)]=None, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n Create a new session using the current session.\n\n ### Arguments:\n session (`str`, `Session`, default=`None`):\n description\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification password, set if needed.\n\n ### Raises:\n - `NoPasswordProvided`: The account\'s two-step verification is enabled and no `password` was provided. Please set the `password` parameters.\n - `PasswordIncorrect`: The two-step verification `password` is incorrect.\n - `TimeoutError`: Time out waiting for the client to be authorized.\n\n ### Returns:\n - Return an instance of `TelegramClient` on success.\n\n ### Examples:\n Use to current session to authorize a new session:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n newClient = await client.QRLoginToNewClient(session="new.session", api=newAPI)\n await newClient.connect()\n await newClient.PrintSessions()\n ```\n '<|docstring|>Create a new session using the current session.
### Arguments:
session (`str`, `Session`, default=`None`):
description
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification password, set if needed.
### Raises:
- `NoPasswordProvided`: The account's two-step verification is enabled and no `password` was provided. Please set the `password` parameters.
- `PasswordIncorrect`: The two-step verification `password` is incorrect.
- `TimeoutError`: Time out waiting for the client to be authorized.
### Returns:
- Return an instance of `TelegramClient` on success.
### Examples:
Use to current session to authorize a new session:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")
oldclient = TelegramClient("old.session", api=oldAPI)
await oldClient.connect()
# We can safely authorize the new client with a different API.
newAPI = API.TelegramAndroid.Generate(unique_id="new.session")
newClient = await client.QRLoginToNewClient(session="new.session", api=newAPI)
await newClient.connect()
await newClient.PrintSessions()
```<|endoftext|> |
5e40728bfffb8dc1c348d97cd2491ff2a9370a7b1085bf3927267cfabf90c7e8 | async def ToTDesktop(self, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> td.TDesktop:
'\n Convert this instance of `TelegramClient` to `TDesktop`\n\n ### Arguments:\n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification `password` if needed.\n\n ### Returns:\n - Return an instance of `TDesktop` on success\n\n ### Examples:\n Save a telethon session to tdata:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely CreateNewSession with a different API.\n # Be aware that you should not use UseCurrentSession with a different API than the one that first authorized it.\n newAPI = API.TelegramAndroid.Generate(unique_id="new_tdata")\n tdesk = await oldClient.ToTDesktop(flag=CreateNewSession, api=newAPI)\n\n # Save the new session to a folder named "new_tdata"\n tdesk.SaveTData("new_tdata")\n ```\n '
return (await td.TDesktop.FromTelethon(self, flag=flag, api=api, password=password)) | Convert this instance of `TelegramClient` to `TDesktop`
### Arguments:
flag (`LoginFlag`, default=`CreateNewSession`):
The login flag. Read more `[here](LoginFlag)`.
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification `password` if needed.
### Returns:
- Return an instance of `TDesktop` on success
### Examples:
Save a telethon session to tdata:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")
oldclient = TelegramClient("old.session", api=oldAPI)
await oldClient.connect()
# We can safely CreateNewSession with a different API.
# Be aware that you should not use UseCurrentSession with a different API than the one that first authorized it.
newAPI = API.TelegramAndroid.Generate(unique_id="new_tdata")
tdesk = await oldClient.ToTDesktop(flag=CreateNewSession, api=newAPI)
# Save the new session to a folder named "new_tdata"
tdesk.SaveTData("new_tdata")
``` | src/tl/telethon.py | ToTDesktop | annihilatorrrr/opentele | 30 | python | async def ToTDesktop(self, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> td.TDesktop:
'\n Convert this instance of `TelegramClient` to `TDesktop`\n\n ### Arguments:\n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification `password` if needed.\n\n ### Returns:\n - Return an instance of `TDesktop` on success\n\n ### Examples:\n Save a telethon session to tdata:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely CreateNewSession with a different API.\n # Be aware that you should not use UseCurrentSession with a different API than the one that first authorized it.\n newAPI = API.TelegramAndroid.Generate(unique_id="new_tdata")\n tdesk = await oldClient.ToTDesktop(flag=CreateNewSession, api=newAPI)\n\n # Save the new session to a folder named "new_tdata"\n tdesk.SaveTData("new_tdata")\n ```\n '
return (await td.TDesktop.FromTelethon(self, flag=flag, api=api, password=password)) | async def ToTDesktop(self, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> td.TDesktop:
'\n Convert this instance of `TelegramClient` to `TDesktop`\n\n ### Arguments:\n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n\n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n\n password (`str`, default=`None`):\n Two-step verification `password` if needed.\n\n ### Returns:\n - Return an instance of `TDesktop` on success\n\n ### Examples:\n Save a telethon session to tdata:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")\n oldclient = TelegramClient("old.session", api=oldAPI)\n await oldClient.connect()\n\n # We can safely CreateNewSession with a different API.\n # Be aware that you should not use UseCurrentSession with a different API than the one that first authorized it.\n newAPI = API.TelegramAndroid.Generate(unique_id="new_tdata")\n tdesk = await oldClient.ToTDesktop(flag=CreateNewSession, api=newAPI)\n\n # Save the new session to a folder named "new_tdata"\n tdesk.SaveTData("new_tdata")\n ```\n '
return (await td.TDesktop.FromTelethon(self, flag=flag, api=api, password=password))<|docstring|>Convert this instance of `TelegramClient` to `TDesktop`
### Arguments:
flag (`LoginFlag`, default=`CreateNewSession`):
The login flag. Read more `[here](LoginFlag)`.
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification `password` if needed.
### Returns:
- Return an instance of `TDesktop` on success
### Examples:
Save a telethon session to tdata:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old.session")
oldclient = TelegramClient("old.session", api=oldAPI)
await oldClient.connect()
# We can safely CreateNewSession with a different API.
# Be aware that you should not use UseCurrentSession with a different API than the one that first authorized it.
newAPI = API.TelegramAndroid.Generate(unique_id="new_tdata")
tdesk = await oldClient.ToTDesktop(flag=CreateNewSession, api=newAPI)
# Save the new session to a folder named "new_tdata"
tdesk.SaveTData("new_tdata")
```<|endoftext|> |
c0b8d4b9cf8bdd87e70a5e0175ea86835f1c0177233ca97e7ea79d70c975e302 | @typing.overload
@staticmethod
async def FromTDesktop(account: Union[(td.TDesktop, td.Account)], session: Union[(str, Session)]=None, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n \n ### Arguments:\n account (`TDesktop`, `Account`):\n The `TDesktop` or `Account` you want to convert from.\n \n session (`str`, `Session`, default=`None`):\n The file name of the `session file` to be used, if `None` then the session will not be saved.\\\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n \n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n \n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n \n password (`str`, default=`None`):\n Two-step verification password if needed.\n \n ### Returns:\n - Return an instance of `TelegramClient` on success\n \n ### Examples:\n Create a telethon session using tdata folder:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old_tdata")\n tdesk = TDesktop("old_tdata", api=oldAPI)\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n client = await TelegramClient.FromTDesktop(tdesk, session="new.session", flag=CreateNewSession, api=newAPI)\n await client.connect()\n await client.PrintSessions()\n ```\n ' | ### Arguments:
account (`TDesktop`, `Account`):
The `TDesktop` or `Account` you want to convert from.
session (`str`, `Session`, default=`None`):
The file name of the `session file` to be used, if `None` then the session will not be saved.\
Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).
flag (`LoginFlag`, default=`CreateNewSession`):
The login flag. Read more `[here](LoginFlag)`.
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification password if needed.
### Returns:
- Return an instance of `TelegramClient` on success
### Examples:
Create a telethon session using tdata folder:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old_tdata")
tdesk = TDesktop("old_tdata", api=oldAPI)
# We can safely authorize the new client with a different API.
newAPI = API.TelegramAndroid.Generate(unique_id="new.session")
client = await TelegramClient.FromTDesktop(tdesk, session="new.session", flag=CreateNewSession, api=newAPI)
await client.connect()
await client.PrintSessions()
``` | src/tl/telethon.py | FromTDesktop | annihilatorrrr/opentele | 30 | python | @typing.overload
@staticmethod
async def FromTDesktop(account: Union[(td.TDesktop, td.Account)], session: Union[(str, Session)]=None, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n \n ### Arguments:\n account (`TDesktop`, `Account`):\n The `TDesktop` or `Account` you want to convert from.\n \n session (`str`, `Session`, default=`None`):\n The file name of the `session file` to be used, if `None` then the session will not be saved.\\\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n \n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n \n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n \n password (`str`, default=`None`):\n Two-step verification password if needed.\n \n ### Returns:\n - Return an instance of `TelegramClient` on success\n \n ### Examples:\n Create a telethon session using tdata folder:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old_tdata")\n tdesk = TDesktop("old_tdata", api=oldAPI)\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n client = await TelegramClient.FromTDesktop(tdesk, session="new.session", flag=CreateNewSession, api=newAPI)\n await client.connect()\n await client.PrintSessions()\n ```\n ' | @typing.overload
@staticmethod
async def FromTDesktop(account: Union[(td.TDesktop, td.Account)], session: Union[(str, Session)]=None, flag: Type[LoginFlag]=CreateNewSession, api: Union[(Type[APIData], APIData)]=API.TelegramDesktop, password: str=None) -> TelegramClient:
'\n \n ### Arguments:\n account (`TDesktop`, `Account`):\n The `TDesktop` or `Account` you want to convert from.\n \n session (`str`, `Session`, default=`None`):\n The file name of the `session file` to be used, if `None` then the session will not be saved.\\\n Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).\n \n flag (`LoginFlag`, default=`CreateNewSession`):\n The login flag. Read more `[here](LoginFlag)`.\n \n api (`API`, default=`TelegramDesktop`):\n Which API to use. Read more `[here](API)`.\n \n password (`str`, default=`None`):\n Two-step verification password if needed.\n \n ### Returns:\n - Return an instance of `TelegramClient` on success\n \n ### Examples:\n Create a telethon session using tdata folder:\n ```python\n # Using the API that we\'ve generated before. Please refer to method API.Generate() to learn more.\n oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old_tdata")\n tdesk = TDesktop("old_tdata", api=oldAPI)\n\n # We can safely authorize the new client with a different API.\n newAPI = API.TelegramAndroid.Generate(unique_id="new.session")\n client = await TelegramClient.FromTDesktop(tdesk, session="new.session", flag=CreateNewSession, api=newAPI)\n await client.connect()\n await client.PrintSessions()\n ```\n '<|docstring|>### Arguments:
account (`TDesktop`, `Account`):
The `TDesktop` or `Account` you want to convert from.
session (`str`, `Session`, default=`None`):
The file name of the `session file` to be used, if `None` then the session will not be saved.\
Read more [here](https://docs.telethon.dev/en/latest/concepts/sessions.html?highlight=session#what-are-sessions).
flag (`LoginFlag`, default=`CreateNewSession`):
The login flag. Read more `[here](LoginFlag)`.
api (`API`, default=`TelegramDesktop`):
Which API to use. Read more `[here](API)`.
password (`str`, default=`None`):
Two-step verification password if needed.
### Returns:
- Return an instance of `TelegramClient` on success
### Examples:
Create a telethon session using tdata folder:
```python
# Using the API that we've generated before. Please refer to method API.Generate() to learn more.
oldAPI = API.TelegramDesktop.Generate(system="windows", unique_id="old_tdata")
tdesk = TDesktop("old_tdata", api=oldAPI)
# We can safely authorize the new client with a different API.
newAPI = API.TelegramAndroid.Generate(unique_id="new.session")
client = await TelegramClient.FromTDesktop(tdesk, session="new.session", flag=CreateNewSession, api=newAPI)
await client.connect()
await client.PrintSessions()
```<|endoftext|> |
ea7f05052f226c15a3053444b6ce74c9954c981fb02f6102e7f0f6d89df5f314 | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator | :param yaml_path: path to yaml file
:param default_separator: default value separator for path-mode | sitri/contrib/yaml.py | __init__ | gitter-badger/sitri | 0 | python | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator<|docstring|>:param yaml_path: path to yaml file
:param default_separator: default value separator for path-mode<|endoftext|> |
b0aeb439df3dac193e61bf7ce4430da17890466e69bcd0e4da77b5b6d25c8af2 | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local | Retrieve value from a dictionary using a list of keys.
:param path: string with separated keys | sitri/contrib/yaml.py | _get_by_path | gitter-badger/sitri | 0 | python | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local<|docstring|>Retrieve value from a dictionary using a list of keys.
:param path: string with separated keys<|endoftext|> |
0c8c9c7cade0339dd1551f00635e991d1a080ecc185d1143882f29983a325680 | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from json\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None | Retrieve value from a dictionary using a key.
:param key: key from json | sitri/contrib/yaml.py | _get_by_key | gitter-badger/sitri | 0 | python | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from json\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from json\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None<|docstring|>Retrieve value from a dictionary using a key.
:param key: key from json<|endoftext|> |
0780bd8ab03ba7a68113b3accb7d72514c0a64741b821994692d52410f97a324 | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key) | Get value from json
:param key: key or path for search
:param path_mode: boolean mode switcher
:param separator: separator for path keys in path mode | sitri/contrib/yaml.py | get | gitter-badger/sitri | 0 | python | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key) | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key)<|docstring|>Get value from json
:param key: key or path for search
:param path_mode: boolean mode switcher
:param separator: separator for path keys in path mode<|endoftext|> |
2fb08d773578a9462082448a7d8ae85e0b53072b13a498f9fbfab97c6d7249b1 | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!') | Keys in json
:param path_mode: [future] path mode for keys list
:param separator: [future] separators for keys in path mode | sitri/contrib/yaml.py | keys | gitter-badger/sitri | 0 | python | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!') | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!')<|docstring|>Keys in json
:param path_mode: [future] path mode for keys list
:param separator: [future] separators for keys in path mode<|endoftext|> |
ea7f05052f226c15a3053444b6ce74c9954c981fb02f6102e7f0f6d89df5f314 | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator | :param yaml_path: path to yaml file
:param default_separator: default value separator for path-mode | sitri/contrib/yaml.py | __init__ | gitter-badger/sitri | 0 | python | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator | def __init__(self, yaml_path: str='./data.yaml', default_separator: str='.'):
'\n\n :param yaml_path: path to yaml file\n :param default_separator: default value separator for path-mode\n '
self._yaml = yaml.safe_load(open(os.path.abspath(yaml_path)))
self.separator = default_separator<|docstring|>:param yaml_path: path to yaml file
:param default_separator: default value separator for path-mode<|endoftext|> |
b0aeb439df3dac193e61bf7ce4430da17890466e69bcd0e4da77b5b6d25c8af2 | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local | Retrieve value from a dictionary using a list of keys.
:param path: string with separated keys | sitri/contrib/yaml.py | _get_by_path | gitter-badger/sitri | 0 | python | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local | def _get_by_path(self, path: str, separator: str) -> typing.Any:
'Retrieve value from a dictionary using a list of keys.\n\n :param path: string with separated keys\n '
dict_local = self._yaml.copy()
keys = path.split(separator)
for key in keys:
try:
dict_local = (dict_local[int(key)] if key.isdigit() else dict_local[key])
except Exception:
if (key not in dict_local):
return None
dict_local = dict_local[key]
return dict_local<|docstring|>Retrieve value from a dictionary using a list of keys.
:param path: string with separated keys<|endoftext|> |
54d7076fa6be673eadc9c64bf417358f2e07548f12c9b6a96a033ed08081deb9 | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from yaml\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None | Retrieve value from a dictionary using a key.
:param key: key from yaml | sitri/contrib/yaml.py | _get_by_key | gitter-badger/sitri | 0 | python | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from yaml\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None | def _get_by_key(self, key: str) -> typing.Any:
'Retrieve value from a dictionary using a key.\n\n :param key: key from yaml\n '
if (key in self._yaml):
return self._yaml[key]
else:
return None<|docstring|>Retrieve value from a dictionary using a key.
:param key: key from yaml<|endoftext|> |
0780bd8ab03ba7a68113b3accb7d72514c0a64741b821994692d52410f97a324 | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key) | Get value from json
:param key: key or path for search
:param path_mode: boolean mode switcher
:param separator: separator for path keys in path mode | sitri/contrib/yaml.py | get | gitter-badger/sitri | 0 | python | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key) | def get(self, key: str, path_mode: bool=False, separator: str=None) -> typing.Optional[typing.Any]:
'Get value from json\n\n :param key: key or path for search\n :param path_mode: boolean mode switcher\n :param separator: separator for path keys in path mode\n '
separator = (separator if separator else self.separator)
if path_mode:
return self._get_by_path(key, separator=separator)
return self._get_by_key(key)<|docstring|>Get value from json
:param key: key or path for search
:param path_mode: boolean mode switcher
:param separator: separator for path keys in path mode<|endoftext|> |
2fb08d773578a9462082448a7d8ae85e0b53072b13a498f9fbfab97c6d7249b1 | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!') | Keys in json
:param path_mode: [future] path mode for keys list
:param separator: [future] separators for keys in path mode | sitri/contrib/yaml.py | keys | gitter-badger/sitri | 0 | python | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!') | def keys(self, path_mode: bool=False, separator: str=None) -> typing.List[str]:
'Keys in json\n\n :param path_mode: [future] path mode for keys list\n :param separator: [future] separators for keys in path mode\n '
if (not path_mode):
return self._yaml.keys()
else:
raise NotImplementedError('Path-mode not implemented!')<|docstring|>Keys in json
:param path_mode: [future] path mode for keys list
:param separator: [future] separators for keys in path mode<|endoftext|> |
d5b9bceea05d8951feec908370aff3e1570db1521177a769a3c05e64f4d2c767 | def __init__(self, xknx: XKNX, udp_client: UDPClient, communication_channel_id: int, route_back: bool=False):
'Initialize ConnectionState class.'
self.udp_client = udp_client
self.route_back = route_back
super().__init__(xknx, self.udp_client, ConnectionStateResponse, timeout_in_seconds=CONNECTIONSTATE_REQUEST_TIMEOUT)
self.communication_channel_id = communication_channel_id | Initialize ConnectionState class. | xknx/io/request_response/connectionstate.py | __init__ | magicbear/xknx | 179 | python | def __init__(self, xknx: XKNX, udp_client: UDPClient, communication_channel_id: int, route_back: bool=False):
self.udp_client = udp_client
self.route_back = route_back
super().__init__(xknx, self.udp_client, ConnectionStateResponse, timeout_in_seconds=CONNECTIONSTATE_REQUEST_TIMEOUT)
self.communication_channel_id = communication_channel_id | def __init__(self, xknx: XKNX, udp_client: UDPClient, communication_channel_id: int, route_back: bool=False):
self.udp_client = udp_client
self.route_back = route_back
super().__init__(xknx, self.udp_client, ConnectionStateResponse, timeout_in_seconds=CONNECTIONSTATE_REQUEST_TIMEOUT)
self.communication_channel_id = communication_channel_id<|docstring|>Initialize ConnectionState class.<|endoftext|> |
9d6ba18d4716c5b984815b616727373261d096addd0fb1bf8455d742910eaa09 | def create_knxipframe(self) -> KNXIPFrame:
'Create KNX/IP Frame object to be sent to device.'
if self.route_back:
endpoint = HPAI()
else:
(local_addr, local_port) = self.udpclient.getsockname()
endpoint = HPAI(ip_addr=local_addr, port=local_port)
connectionstate_request = ConnectionStateRequest(self.xknx, communication_channel_id=self.communication_channel_id, control_endpoint=endpoint)
return KNXIPFrame.init_from_body(connectionstate_request) | Create KNX/IP Frame object to be sent to device. | xknx/io/request_response/connectionstate.py | create_knxipframe | magicbear/xknx | 179 | python | def create_knxipframe(self) -> KNXIPFrame:
if self.route_back:
endpoint = HPAI()
else:
(local_addr, local_port) = self.udpclient.getsockname()
endpoint = HPAI(ip_addr=local_addr, port=local_port)
connectionstate_request = ConnectionStateRequest(self.xknx, communication_channel_id=self.communication_channel_id, control_endpoint=endpoint)
return KNXIPFrame.init_from_body(connectionstate_request) | def create_knxipframe(self) -> KNXIPFrame:
if self.route_back:
endpoint = HPAI()
else:
(local_addr, local_port) = self.udpclient.getsockname()
endpoint = HPAI(ip_addr=local_addr, port=local_port)
connectionstate_request = ConnectionStateRequest(self.xknx, communication_channel_id=self.communication_channel_id, control_endpoint=endpoint)
return KNXIPFrame.init_from_body(connectionstate_request)<|docstring|>Create KNX/IP Frame object to be sent to device.<|endoftext|> |
cbbabce2b8831c32513da0bf957a2bb6b43e7537c038d2219e37768944129f06 | def ids_tensor(shape, vocab_size, rng=None, name=None):
'Creates a random int32 tensor of the shape within the vocab size.'
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, (vocab_size - 1)))
return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous() | Creates a random int32 tensor of the shape within the vocab size. | tests/test_modeling_common.py | ids_tensor | mmaybeno/transformers | 83 | python | def ids_tensor(shape, vocab_size, rng=None, name=None):
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, (vocab_size - 1)))
return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous() | def ids_tensor(shape, vocab_size, rng=None, name=None):
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, (vocab_size - 1)))
return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous()<|docstring|>Creates a random int32 tensor of the shape within the vocab size.<|endoftext|> |
84249e4ccaba3f5b8c46ef63a733261cf83e6c008b9e8718d24a3605ffcce7c5 | def floats_tensor(shape, scale=1.0, rng=None, name=None):
'Creates a random float32 tensor of the shape within the vocab size.'
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append((rng.random() * scale))
return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous() | Creates a random float32 tensor of the shape within the vocab size. | tests/test_modeling_common.py | floats_tensor | mmaybeno/transformers | 83 | python | def floats_tensor(shape, scale=1.0, rng=None, name=None):
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append((rng.random() * scale))
return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous() | def floats_tensor(shape, scale=1.0, rng=None, name=None):
if (rng is None):
rng = global_rng
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append((rng.random() * scale))
return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous()<|docstring|>Creates a random float32 tensor of the shape within the vocab size.<|endoftext|> |
e3f42f523e627c40134588b1d5409db6a20ffd8b784de62594a251a74995a5be | def __init__(self, config=None):
"\n Constructor\n\n :param config: [dict] config dictionary of the form {'hyperparameter': {...}, ...}\n "
self._data = {HYPERPARAMETERPATH: {}, SETTINGSPATH: {}}
if (config is not None):
self.set_config(config) | Constructor
:param config: [dict] config dictionary of the form {'hyperparameter': {...}, ...} | hyppopy/HyppopyProject.py | __init__ | MIC-DKFZ/Hyppopy | 26 | python | def __init__(self, config=None):
"\n Constructor\n\n :param config: [dict] config dictionary of the form {'hyperparameter': {...}, ...}\n "
self._data = {HYPERPARAMETERPATH: {}, SETTINGSPATH: {}}
if (config is not None):
self.set_config(config) | def __init__(self, config=None):
"\n Constructor\n\n :param config: [dict] config dictionary of the form {'hyperparameter': {...}, ...}\n "
self._data = {HYPERPARAMETERPATH: {}, SETTINGSPATH: {}}
if (config is not None):
self.set_config(config)<|docstring|>Constructor
:param config: [dict] config dictionary of the form {'hyperparameter': {...}, ...}<|endoftext|> |
453ddd939082824aad192305b48380fd18a2992d527c224718c7e48609370e8f | def __parse_members(self):
'\n The function converts settings into class attributes\n '
for (name, value) in self.settings.items():
if (name not in self.__dict__.keys()):
setattr(self, name, value)
else:
self.__dict__[name] = value | The function converts settings into class attributes | hyppopy/HyppopyProject.py | __parse_members | MIC-DKFZ/Hyppopy | 26 | python | def __parse_members(self):
'\n \n '
for (name, value) in self.settings.items():
if (name not in self.__dict__.keys()):
setattr(self, name, value)
else:
self.__dict__[name] = value | def __parse_members(self):
'\n \n '
for (name, value) in self.settings.items():
if (name not in self.__dict__.keys()):
setattr(self, name, value)
else:
self.__dict__[name] = value<|docstring|>The function converts settings into class attributes<|endoftext|> |
2586a18fd443e6209af5fbecf511cfd0a27684a0d8bf5f7345b7e72c1f070c79 | def set_config(self, config):
'\n Set a config dict\n\n :param config: [dict] configuration dict defining hyperparameter and general settings\n '
assert isinstance(config, dict), 'precondition violation, config needs to be of type dict, got {}'.format(type(config))
confic_cp = copy.deepcopy(config)
if (HYPERPARAMETERPATH in confic_cp.keys()):
self._data[HYPERPARAMETERPATH] = confic_cp[HYPERPARAMETERPATH]
del confic_cp[HYPERPARAMETERPATH]
self._data[SETTINGSPATH] = confic_cp
self.__parse_members() | Set a config dict
:param config: [dict] configuration dict defining hyperparameter and general settings | hyppopy/HyppopyProject.py | set_config | MIC-DKFZ/Hyppopy | 26 | python | def set_config(self, config):
'\n Set a config dict\n\n :param config: [dict] configuration dict defining hyperparameter and general settings\n '
assert isinstance(config, dict), 'precondition violation, config needs to be of type dict, got {}'.format(type(config))
confic_cp = copy.deepcopy(config)
if (HYPERPARAMETERPATH in confic_cp.keys()):
self._data[HYPERPARAMETERPATH] = confic_cp[HYPERPARAMETERPATH]
del confic_cp[HYPERPARAMETERPATH]
self._data[SETTINGSPATH] = confic_cp
self.__parse_members() | def set_config(self, config):
'\n Set a config dict\n\n :param config: [dict] configuration dict defining hyperparameter and general settings\n '
assert isinstance(config, dict), 'precondition violation, config needs to be of type dict, got {}'.format(type(config))
confic_cp = copy.deepcopy(config)
if (HYPERPARAMETERPATH in confic_cp.keys()):
self._data[HYPERPARAMETERPATH] = confic_cp[HYPERPARAMETERPATH]
del confic_cp[HYPERPARAMETERPATH]
self._data[SETTINGSPATH] = confic_cp
self.__parse_members()<|docstring|>Set a config dict
:param config: [dict] configuration dict defining hyperparameter and general settings<|endoftext|> |
f08d1791b9a93f3e8bbecdbd8996d46d21893e047555a4be77d2e20245edb11d | def set_hyperparameter(self, params):
'\n This function can be used to set the hyperparameter description directly by passing the hyperparameter section\n of a config dict (see class description). Alternatively use add_hyperparameter to add one after each other.\n\n :param params: [dict] configuration dict defining hyperparameter\n '
assert isinstance(params, dict), 'precondition violation, params needs to be of type dict, got {}'.format(type(params))
self._data[HYPERPARAMETERPATH] = params | This function can be used to set the hyperparameter description directly by passing the hyperparameter section
of a config dict (see class description). Alternatively use add_hyperparameter to add one after each other.
:param params: [dict] configuration dict defining hyperparameter | hyppopy/HyppopyProject.py | set_hyperparameter | MIC-DKFZ/Hyppopy | 26 | python | def set_hyperparameter(self, params):
'\n This function can be used to set the hyperparameter description directly by passing the hyperparameter section\n of a config dict (see class description). Alternatively use add_hyperparameter to add one after each other.\n\n :param params: [dict] configuration dict defining hyperparameter\n '
assert isinstance(params, dict), 'precondition violation, params needs to be of type dict, got {}'.format(type(params))
self._data[HYPERPARAMETERPATH] = params | def set_hyperparameter(self, params):
'\n This function can be used to set the hyperparameter description directly by passing the hyperparameter section\n of a config dict (see class description). Alternatively use add_hyperparameter to add one after each other.\n\n :param params: [dict] configuration dict defining hyperparameter\n '
assert isinstance(params, dict), 'precondition violation, params needs to be of type dict, got {}'.format(type(params))
self._data[HYPERPARAMETERPATH] = params<|docstring|>This function can be used to set the hyperparameter description directly by passing the hyperparameter section
of a config dict (see class description). Alternatively use add_hyperparameter to add one after each other.
:param params: [dict] configuration dict defining hyperparameter<|endoftext|> |
8bebc6172d315a094e6e80a8ce6f62bdf74cbd4607c35e5ad7e290140289b7bf | def add_hyperparameter(self, name, **kwargs):
"\n This function can be used to set hyperparameter descriptions. Alternatively use set_hyperparameter to set all at\n once.\n\n :param name: [str] hyperparameter name\n :param kwargs: [dict] configuration dict defining a hyperparameter e.g. domain='uniform', data=[1,100], ...\n "
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[HYPERPARAMETERPATH][name] = kwargs | This function can be used to set hyperparameter descriptions. Alternatively use set_hyperparameter to set all at
once.
:param name: [str] hyperparameter name
:param kwargs: [dict] configuration dict defining a hyperparameter e.g. domain='uniform', data=[1,100], ... | hyppopy/HyppopyProject.py | add_hyperparameter | MIC-DKFZ/Hyppopy | 26 | python | def add_hyperparameter(self, name, **kwargs):
"\n This function can be used to set hyperparameter descriptions. Alternatively use set_hyperparameter to set all at\n once.\n\n :param name: [str] hyperparameter name\n :param kwargs: [dict] configuration dict defining a hyperparameter e.g. domain='uniform', data=[1,100], ...\n "
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[HYPERPARAMETERPATH][name] = kwargs | def add_hyperparameter(self, name, **kwargs):
"\n This function can be used to set hyperparameter descriptions. Alternatively use set_hyperparameter to set all at\n once.\n\n :param name: [str] hyperparameter name\n :param kwargs: [dict] configuration dict defining a hyperparameter e.g. domain='uniform', data=[1,100], ...\n "
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[HYPERPARAMETERPATH][name] = kwargs<|docstring|>This function can be used to set hyperparameter descriptions. Alternatively use set_hyperparameter to set all at
once.
:param name: [str] hyperparameter name
:param kwargs: [dict] configuration dict defining a hyperparameter e.g. domain='uniform', data=[1,100], ...<|endoftext|> |
4e7783cac34ccb3504fa5929ab6e81c2baa9a423cc338d703d70e628de5d8b3c | def set_settings(self, **kwargs):
"\n This function can be used to set the general settings directly by passing the settings as name=value pairs.\n Alternatively use add_setting to add one after each other.\n\n :param kwargs: [dict] settings dict e.g. my_setting_1=3.1415, my_setting_2='hello world', ...\n "
self._data[SETTINGSPATH] = kwargs
self.__parse_members() | This function can be used to set the general settings directly by passing the settings as name=value pairs.
Alternatively use add_setting to add one after each other.
:param kwargs: [dict] settings dict e.g. my_setting_1=3.1415, my_setting_2='hello world', ... | hyppopy/HyppopyProject.py | set_settings | MIC-DKFZ/Hyppopy | 26 | python | def set_settings(self, **kwargs):
"\n This function can be used to set the general settings directly by passing the settings as name=value pairs.\n Alternatively use add_setting to add one after each other.\n\n :param kwargs: [dict] settings dict e.g. my_setting_1=3.1415, my_setting_2='hello world', ...\n "
self._data[SETTINGSPATH] = kwargs
self.__parse_members() | def set_settings(self, **kwargs):
"\n This function can be used to set the general settings directly by passing the settings as name=value pairs.\n Alternatively use add_setting to add one after each other.\n\n :param kwargs: [dict] settings dict e.g. my_setting_1=3.1415, my_setting_2='hello world', ...\n "
self._data[SETTINGSPATH] = kwargs
self.__parse_members()<|docstring|>This function can be used to set the general settings directly by passing the settings as name=value pairs.
Alternatively use add_setting to add one after each other.
:param kwargs: [dict] settings dict e.g. my_setting_1=3.1415, my_setting_2='hello world', ...<|endoftext|> |
87ef57eb987d4c4ba23aaf2c978f8610dc73dede3bd676c6dc92d381374e6c42 | def add_setting(self, name, value):
'\n This function can be used to set a general settings. Alternatively use set_settings to set all at once.\n\n :param name: [str] setting name\n :param value: [object] settings value\n '
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[SETTINGSPATH][name] = value
self.__parse_members() | This function can be used to set a general settings. Alternatively use set_settings to set all at once.
:param name: [str] setting name
:param value: [object] settings value | hyppopy/HyppopyProject.py | add_setting | MIC-DKFZ/Hyppopy | 26 | python | def add_setting(self, name, value):
'\n This function can be used to set a general settings. Alternatively use set_settings to set all at once.\n\n :param name: [str] setting name\n :param value: [object] settings value\n '
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[SETTINGSPATH][name] = value
self.__parse_members() | def add_setting(self, name, value):
'\n This function can be used to set a general settings. Alternatively use set_settings to set all at once.\n\n :param name: [str] setting name\n :param value: [object] settings value\n '
assert isinstance(name, str), 'precondition violation, name needs to be of type str, got {}'.format(type(name))
self._data[SETTINGSPATH][name] = value
self.__parse_members()<|docstring|>This function can be used to set a general settings. Alternatively use set_settings to set all at once.
:param name: [str] setting name
:param value: [object] settings value<|endoftext|> |
6b10849e8e34ee870fd803b18b8583e791c3f9979efaeaa860ab3df76883828d | def get_typeof(self, name):
'\n Returns a hyperparameter type by name\n\n :param name: [str] hyperparameter name\n :return: [type] hyperparameter type\n '
if (not (name in self.hyperparameter.keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter {}!".format(name))
if (not ('type' in self.hyperparameter[name].keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter signature type!")
dtype = self.hyperparameter[name]['type']
return dtype | Returns a hyperparameter type by name
:param name: [str] hyperparameter name
:return: [type] hyperparameter type | hyppopy/HyppopyProject.py | get_typeof | MIC-DKFZ/Hyppopy | 26 | python | def get_typeof(self, name):
'\n Returns a hyperparameter type by name\n\n :param name: [str] hyperparameter name\n :return: [type] hyperparameter type\n '
if (not (name in self.hyperparameter.keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter {}!".format(name))
if (not ('type' in self.hyperparameter[name].keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter signature type!")
dtype = self.hyperparameter[name]['type']
return dtype | def get_typeof(self, name):
'\n Returns a hyperparameter type by name\n\n :param name: [str] hyperparameter name\n :return: [type] hyperparameter type\n '
if (not (name in self.hyperparameter.keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter {}!".format(name))
if (not ('type' in self.hyperparameter[name].keys())):
raise LookupError("Typechecking failed, couldn't find hyperparameter signature type!")
dtype = self.hyperparameter[name]['type']
return dtype<|docstring|>Returns a hyperparameter type by name
:param name: [str] hyperparameter name
:return: [type] hyperparameter type<|endoftext|> |
d38576f48c7f7bcd4c93f0d1742dedafc7e4189bbead6ca3b30153b344899dbd | def on(type: str='', rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个基础事件响应器,可自定义类型。\n\n :参数:\n\n * ``type: str``: 事件响应器类型\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new(type, (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | :说明:
注册一个基础事件响应器,可自定义类型。
:参数:
* ``type: str``: 事件响应器类型
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on | SK-415/nonebot2 | 1,757 | python | def on(type: str=, rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个基础事件响应器,可自定义类型。\n\n :参数:\n\n * ``type: str``: 事件响应器类型\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new(type, (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | def on(type: str=, rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个基础事件响应器,可自定义类型。\n\n :参数:\n\n * ``type: str``: 事件响应器类型\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new(type, (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher<|docstring|>:说明:
注册一个基础事件响应器,可自定义类型。
:参数:
* ``type: str``: 事件响应器类型
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
df5d11e3007f7a1dad8665e22cc9ab83faedfcc83e9bdf24dd5ca8c107af0a35 | def on_metaevent(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个元事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('meta_event', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | :说明:
注册一个元事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_metaevent | SK-415/nonebot2 | 1,757 | python | def on_metaevent(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个元事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('meta_event', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | def on_metaevent(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个元事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('meta_event', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher<|docstring|>:说明:
注册一个元事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
38193904d26f2186ec86619a04aaf1e8ccb8e1c16a9eb6430405689dd4d679a1 | def on_message(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=True, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('message', (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | :说明:
注册一个消息事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_message | SK-415/nonebot2 | 1,757 | python | def on_message(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=True, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('message', (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | def on_message(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, permission: Optional[Permission]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=True, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('message', (Rule() & rule), (permission or Permission()), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher<|docstring|>:说明:
注册一个消息事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
0e082eaa155c0fc6a19626c5357e1b9cf0c7d8c9897fbce66339a22afdc1912c | def on_notice(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个通知事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('notice', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | :说明:
注册一个通知事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_notice | SK-415/nonebot2 | 1,757 | python | def on_notice(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个通知事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('notice', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | def on_notice(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个通知事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('notice', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher<|docstring|>:说明:
注册一个通知事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
c3cb7f5202f8ed4942a6f8606c1f616a08bc1b3a95a6ca228ea2289e1599c8de | def on_request(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个请求事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('request', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | :说明:
注册一个请求事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_request | SK-415/nonebot2 | 1,757 | python | def on_request(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个请求事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('request', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher | def on_request(rule: Optional[Union[(Rule, T_RuleChecker)]]=None, *, handlers: Optional[List[Union[(T_Handler, Handler)]]]=None, temp: bool=False, priority: int=1, block: bool=False, state: Optional[T_State]=None, state_factory: Optional[T_StateFactory]=None) -> Type[Matcher]:
'\n :说明:\n\n 注册一个请求事件响应器。\n\n :参数:\n\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
matcher = Matcher.new('request', (Rule() & rule), Permission(), temp=temp, priority=priority, block=block, handlers=handlers, module=_current_plugin.get(), default_state=state, default_state_factory=state_factory)
_store_matcher(matcher)
return matcher<|docstring|>:说明:
注册一个请求事件响应器。
:参数:
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
3e78e5edf025001b431a99ab639120eeaca051f97a886213771cbb8cc1e92542 | def on_startswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((startswith(msg, ignorecase) & rule), **kwargs) | :说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_startswith | SK-415/nonebot2 | 1,757 | python | def on_startswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((startswith(msg, ignorecase) & rule), **kwargs) | def on_startswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((startswith(msg, ignorecase) & rule), **kwargs)<|docstring|>:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息开头内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
78fb5e0d22b14b5327cbb822557ff4a561e08fca44346dc5dd79ed9135d54cfb | def on_endswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((endswith(msg, ignorecase) & rule), **kwargs) | :说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_endswith | SK-415/nonebot2 | 1,757 | python | def on_endswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((endswith(msg, ignorecase) & rule), **kwargs) | def on_endswith(msg: Union[(str, Tuple[(str, ...)])], rule: Optional[Optional[Union[(Rule, T_RuleChecker)]]]=None, ignorecase: bool=False, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。\n\n :参数:\n\n * ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``ignorecase: bool``: 是否忽略大小写\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((endswith(msg, ignorecase) & rule), **kwargs)<|docstring|>:说明:
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
:参数:
* ``msg: Union[str, Tuple[str, ...]]``: 指定消息结尾内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``ignorecase: bool``: 是否忽略大小写
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
84c8a1482cea3304ff94ac2945f0aa141a94b6d664d82dad953f7e6301d34991 | def on_keyword(keywords: Set[str], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。\n\n :参数:\n\n * ``keywords: Set[str]``: 关键词列表\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((keyword(*keywords) & rule), **kwargs) | :说明:
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
:参数:
* ``keywords: Set[str]``: 关键词列表
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_keyword | SK-415/nonebot2 | 1,757 | python | def on_keyword(keywords: Set[str], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。\n\n :参数:\n\n * ``keywords: Set[str]``: 关键词列表\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((keyword(*keywords) & rule), **kwargs) | def on_keyword(keywords: Set[str], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。\n\n :参数:\n\n * ``keywords: Set[str]``: 关键词列表\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((keyword(*keywords) & rule), **kwargs)<|docstring|>:说明:
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
:参数:
* ``keywords: Set[str]``: 关键词列表
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
90f3795a8f29d35d015798966af4823f239b7ad7f304240bfe1c719cecd72d85 | def on_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息以指定命令开头时响应。\n\n 命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
if (len(message) < 1):
return
segment = message.pop(0)
segment_text = str(segment).lstrip()
if (not segment_text.startswith(state['_prefix']['raw_command'])):
return
new_message = message.__class__(segment_text[len(state['_prefix']['raw_command']):].lstrip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((command(*commands) & rule), handlers=handlers, **kwargs) | :说明:
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_command | SK-415/nonebot2 | 1,757 | python | def on_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息以指定命令开头时响应。\n\n 命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
if (len(message) < 1):
return
segment = message.pop(0)
segment_text = str(segment).lstrip()
if (not segment_text.startswith(state['_prefix']['raw_command'])):
return
new_message = message.__class__(segment_text[len(state['_prefix']['raw_command']):].lstrip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((command(*commands) & rule), handlers=handlers, **kwargs) | def on_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息以指定命令开头时响应。\n\n 命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
if (len(message) < 1):
return
segment = message.pop(0)
segment_text = str(segment).lstrip()
if (not segment_text.startswith(state['_prefix']['raw_command'])):
return
new_message = message.__class__(segment_text[len(state['_prefix']['raw_command']):].lstrip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((command(*commands) & rule), handlers=handlers, **kwargs)<|docstring|>:说明:
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
65d96ac7a4fdbe864b73a0cabec9d84cf622e7ef1c066ece046728eccdae5955 | def on_shell_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, parser: Optional[ArgumentParser]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。\n\n 与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。\n\n 并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
segment = message.pop(0)
new_message = message.__class__(str(segment)[len(state['_prefix']['raw_command']):].strip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((shell_command(*commands, parser=parser) & rule), handlers=handlers, **kwargs) | :说明:
注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。
与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_shell_command | SK-415/nonebot2 | 1,757 | python | def on_shell_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, parser: Optional[ArgumentParser]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。\n\n 与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。\n\n 并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
segment = message.pop(0)
new_message = message.__class__(str(segment)[len(state['_prefix']['raw_command']):].strip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((shell_command(*commands, parser=parser) & rule), handlers=handlers, **kwargs) | def on_shell_command(cmd: Union[(str, Tuple[(str, ...)])], rule: Optional[Union[(Rule, T_RuleChecker)]]=None, aliases: Optional[Set[Union[(str, Tuple[(str, ...)])]]]=None, parser: Optional[ArgumentParser]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。\n\n 与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。\n\n 并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中\n\n :参数:\n\n * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名\n * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
async def _strip_cmd(bot: 'Bot', event: 'Event', state: T_State):
message = event.get_message()
segment = message.pop(0)
new_message = message.__class__(str(segment)[len(state['_prefix']['raw_command']):].strip())
for new_segment in reversed(new_message):
message.insert(0, new_segment)
handlers = kwargs.pop('handlers', [])
handlers.insert(0, _strip_cmd)
commands = (set([cmd]) | (aliases or set()))
return on_message((shell_command(*commands, parser=parser) & rule), handlers=handlers, **kwargs)<|docstring|>:说明:
注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。
与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中
:参数:
* ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名
* ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
e14027c6c03ead045fb1086a0a9bf8552b241b7b86e618b3cd932d5905362846 | def on_regex(pattern: str, flags: Union[(int, re.RegexFlag)]=0, rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。\n\n 命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_\n\n :参数:\n\n * ``pattern: str``: 正则表达式\n * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((regex(pattern, flags) & rule), **kwargs) | :说明:
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_
:参数:
* ``pattern: str``: 正则表达式
* ``flags: Union[int, re.RegexFlag]``: 正则匹配标志
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]`` | nonebot/plugin/__init__.py | on_regex | SK-415/nonebot2 | 1,757 | python | def on_regex(pattern: str, flags: Union[(int, re.RegexFlag)]=0, rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。\n\n 命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_\n\n :参数:\n\n * ``pattern: str``: 正则表达式\n * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((regex(pattern, flags) & rule), **kwargs) | def on_regex(pattern: str, flags: Union[(int, re.RegexFlag)]=0, rule: Optional[Union[(Rule, T_RuleChecker)]]=None, **kwargs) -> Type[Matcher]:
'\n :说明:\n\n 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。\n\n 命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_\n\n :参数:\n\n * ``pattern: str``: 正则表达式\n * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志\n * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则\n * ``permission: Optional[Permission]``: 事件响应权限\n * ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表\n * ``temp: bool``: 是否为临时事件响应器(仅执行一次)\n * ``priority: int``: 事件响应器优先级\n * ``block: bool``: 是否阻止事件向更低优先级传递\n * ``state: Optional[T_State]``: 默认 state\n * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数\n\n :返回:\n\n - ``Type[Matcher]``\n '
return on_message((regex(pattern, flags) & rule), **kwargs)<|docstring|>:说明:
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_
:参数:
* ``pattern: str``: 正则表达式
* ``flags: Union[int, re.RegexFlag]``: 正则匹配标志
* ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则
* ``permission: Optional[Permission]``: 事件响应权限
* ``handlers: Optional[List[Union[T_Handler, Handler]]]``: 事件处理函数列表
* ``temp: bool``: 是否为临时事件响应器(仅执行一次)
* ``priority: int``: 事件响应器优先级
* ``block: bool``: 是否阻止事件向更低优先级传递
* ``state: Optional[T_State]``: 默认 state
* ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数
:返回:
- ``Type[Matcher]``<|endoftext|> |
654b67f549ce1b886edd6c4b3cadeb2b4a09be322efceedc025c7efc3e04982d | def load_plugin(module_path: str) -> Optional[Plugin]:
'\n :说明:\n\n 使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。\n\n :参数:\n\n * ``module_path: str``: 插件名称 ``path.to.your.plugin``\n\n :返回:\n\n - ``Optional[Plugin]``\n '
context: Context = copy_context()
manager = PluginManager(PLUGIN_NAMESPACE, plugins=[module_path])
return context.run(_load_plugin, manager, module_path) | :说明:
使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。
:参数:
* ``module_path: str``: 插件名称 ``path.to.your.plugin``
:返回:
- ``Optional[Plugin]`` | nonebot/plugin/__init__.py | load_plugin | SK-415/nonebot2 | 1,757 | python | def load_plugin(module_path: str) -> Optional[Plugin]:
'\n :说明:\n\n 使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。\n\n :参数:\n\n * ``module_path: str``: 插件名称 ``path.to.your.plugin``\n\n :返回:\n\n - ``Optional[Plugin]``\n '
context: Context = copy_context()
manager = PluginManager(PLUGIN_NAMESPACE, plugins=[module_path])
return context.run(_load_plugin, manager, module_path) | def load_plugin(module_path: str) -> Optional[Plugin]:
'\n :说明:\n\n 使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。\n\n :参数:\n\n * ``module_path: str``: 插件名称 ``path.to.your.plugin``\n\n :返回:\n\n - ``Optional[Plugin]``\n '
context: Context = copy_context()
manager = PluginManager(PLUGIN_NAMESPACE, plugins=[module_path])
return context.run(_load_plugin, manager, module_path)<|docstring|>:说明:
使用 ``PluginManager`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。
:参数:
* ``module_path: str``: 插件名称 ``path.to.your.plugin``
:返回:
- ``Optional[Plugin]``<|endoftext|> |
7363e7715de0a4eec35968a7723c11e6873afc24ee4781380a50dd8898cffb14 | def load_plugins(*plugin_dir: str) -> Set[Plugin]:
'\n :说明:\n\n 导入目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``*plugin_dir: str``: 插件路径\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, search_path=plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins | :说明:
导入目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``*plugin_dir: str``: 插件路径
:返回:
- ``Set[Plugin]`` | nonebot/plugin/__init__.py | load_plugins | SK-415/nonebot2 | 1,757 | python | def load_plugins(*plugin_dir: str) -> Set[Plugin]:
'\n :说明:\n\n 导入目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``*plugin_dir: str``: 插件路径\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, search_path=plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins | def load_plugins(*plugin_dir: str) -> Set[Plugin]:
'\n :说明:\n\n 导入目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``*plugin_dir: str``: 插件路径\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, search_path=plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins<|docstring|>:说明:
导入目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``*plugin_dir: str``: 插件路径
:返回:
- ``Set[Plugin]``<|endoftext|> |
41d1a68bb2640852bfe8fed2c875504af86a5ea172cb84b64ac13f951d175675 | def load_all_plugins(module_path: Set[str], plugin_dir: Set[str]) -> Set[Plugin]:
'\n :说明:\n\n 导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``module_path: Set[str]``: 指定插件集合\n - ``plugin_dir: Set[str]``: 指定插件路径集合\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, module_path, plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins | :说明:
导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``module_path: Set[str]``: 指定插件集合
- ``plugin_dir: Set[str]``: 指定插件路径集合
:返回:
- ``Set[Plugin]`` | nonebot/plugin/__init__.py | load_all_plugins | SK-415/nonebot2 | 1,757 | python | def load_all_plugins(module_path: Set[str], plugin_dir: Set[str]) -> Set[Plugin]:
'\n :说明:\n\n 导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``module_path: Set[str]``: 指定插件集合\n - ``plugin_dir: Set[str]``: 指定插件路径集合\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, module_path, plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins | def load_all_plugins(module_path: Set[str], plugin_dir: Set[str]) -> Set[Plugin]:
'\n :说明:\n\n 导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``module_path: Set[str]``: 指定插件集合\n - ``plugin_dir: Set[str]``: 指定插件路径集合\n\n :返回:\n\n - ``Set[Plugin]``\n '
loaded_plugins = set()
manager = PluginManager(PLUGIN_NAMESPACE, module_path, plugin_dir)
for plugin_name in manager.list_plugins():
context: Context = copy_context()
result = context.run(_load_plugin, manager, plugin_name)
if result:
loaded_plugins.add(result)
return loaded_plugins<|docstring|>:说明:
导入指定列表中的插件以及指定目录下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``module_path: Set[str]``: 指定插件集合
- ``plugin_dir: Set[str]``: 指定插件路径集合
:返回:
- ``Set[Plugin]``<|endoftext|> |
56e2cfb499db0a5c302289369fd4359568a941cd136c50b869abfc564c16f480 | def load_from_json(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 json 文件路径\n - ``encoding: str``: 指定 json 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = json.load(f)
plugins = data.get('plugins')
plugin_dirs = data.get('plugin_dirs')
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs)) | :说明:
导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``file_path: str``: 指定 json 文件路径
- ``encoding: str``: 指定 json 文件编码
:返回:
- ``Set[Plugin]`` | nonebot/plugin/__init__.py | load_from_json | SK-415/nonebot2 | 1,757 | python | def load_from_json(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 json 文件路径\n - ``encoding: str``: 指定 json 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = json.load(f)
plugins = data.get('plugins')
plugin_dirs = data.get('plugin_dirs')
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs)) | def load_from_json(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 json 文件路径\n - ``encoding: str``: 指定 json 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = json.load(f)
plugins = data.get('plugins')
plugin_dirs = data.get('plugin_dirs')
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs))<|docstring|>:说明:
导入指定 json 文件中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,以 ``_`` 开头的插件不会被导入!
:参数:
- ``file_path: str``: 指定 json 文件路径
- ``encoding: str``: 指定 json 文件编码
:返回:
- ``Set[Plugin]``<|endoftext|> |
5886dffc6292edee1190466a1b14883d929919cd37d02f4843d01fa2afbb919f | def load_from_toml(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 toml 文件 ``[nonebot.plugins]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,\n 以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 toml 文件路径\n - ``encoding: str``: 指定 toml 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = tomlkit.parse(f.read())
nonebot_data = data.get('nonebot', {}).get('plugins')
if (not nonebot_data):
raise ValueError("Cannot find '[nonebot.plugins]' in given toml file!")
plugins = nonebot_data.get('plugins', [])
plugin_dirs = nonebot_data.get('plugin_dirs', [])
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs)) | :说明:
导入指定 toml 文件 ``[nonebot.plugins]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,
以 ``_`` 开头的插件不会被导入!
:参数:
- ``file_path: str``: 指定 toml 文件路径
- ``encoding: str``: 指定 toml 文件编码
:返回:
- ``Set[Plugin]`` | nonebot/plugin/__init__.py | load_from_toml | SK-415/nonebot2 | 1,757 | python | def load_from_toml(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 toml 文件 ``[nonebot.plugins]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,\n 以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 toml 文件路径\n - ``encoding: str``: 指定 toml 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = tomlkit.parse(f.read())
nonebot_data = data.get('nonebot', {}).get('plugins')
if (not nonebot_data):
raise ValueError("Cannot find '[nonebot.plugins]' in given toml file!")
plugins = nonebot_data.get('plugins', [])
plugin_dirs = nonebot_data.get('plugin_dirs', [])
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs)) | def load_from_toml(file_path: str, encoding: str='utf-8') -> Set[Plugin]:
'\n :说明:\n\n 导入指定 toml 文件 ``[nonebot.plugins]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,\n 以 ``_`` 开头的插件不会被导入!\n\n :参数:\n\n - ``file_path: str``: 指定 toml 文件路径\n - ``encoding: str``: 指定 toml 文件编码\n\n :返回:\n\n - ``Set[Plugin]``\n '
with open(file_path, 'r', encoding=encoding) as f:
data = tomlkit.parse(f.read())
nonebot_data = data.get('nonebot', {}).get('plugins')
if (not nonebot_data):
raise ValueError("Cannot find '[nonebot.plugins]' in given toml file!")
plugins = nonebot_data.get('plugins', [])
plugin_dirs = nonebot_data.get('plugin_dirs', [])
assert isinstance(plugins, list), 'plugins must be a list of plugin name'
assert isinstance(plugin_dirs, list), 'plugin_dirs must be a list of directories'
return load_all_plugins(set(plugins), set(plugin_dirs))<|docstring|>:说明:
导入指定 toml 文件 ``[nonebot.plugins]`` 中的 ``plugins`` 以及 ``plugin_dirs`` 下多个插件,
以 ``_`` 开头的插件不会被导入!
:参数:
- ``file_path: str``: 指定 toml 文件路径
- ``encoding: str``: 指定 toml 文件编码
:返回:
- ``Set[Plugin]``<|endoftext|> |
85c7fed6663da8112e4d230d16c6e36094b4d73b4923c481dec0a7f1f6731a6a | def load_builtin_plugins(name: str='echo') -> Optional[Plugin]:
'\n :说明:\n\n 导入 NoneBot 内置插件\n\n :返回:\n\n - ``Plugin``\n '
return load_plugin(f'nonebot.plugins.{name}') | :说明:
导入 NoneBot 内置插件
:返回:
- ``Plugin`` | nonebot/plugin/__init__.py | load_builtin_plugins | SK-415/nonebot2 | 1,757 | python | def load_builtin_plugins(name: str='echo') -> Optional[Plugin]:
'\n :说明:\n\n 导入 NoneBot 内置插件\n\n :返回:\n\n - ``Plugin``\n '
return load_plugin(f'nonebot.plugins.{name}') | def load_builtin_plugins(name: str='echo') -> Optional[Plugin]:
'\n :说明:\n\n 导入 NoneBot 内置插件\n\n :返回:\n\n - ``Plugin``\n '
return load_plugin(f'nonebot.plugins.{name}')<|docstring|>:说明:
导入 NoneBot 内置插件
:返回:
- ``Plugin``<|endoftext|> |
2ff481e086b3a206cf6ced083d14457ab7ae3136da868168c280be93156c651d | def get_plugin(name: str) -> Optional[Plugin]:
'\n :说明:\n\n 获取当前导入的某个插件。\n\n :参数:\n\n * ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。\n\n :返回:\n\n - ``Optional[Plugin]``\n '
return plugins.get(name) | :说明:
获取当前导入的某个插件。
:参数:
* ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。
:返回:
- ``Optional[Plugin]`` | nonebot/plugin/__init__.py | get_plugin | SK-415/nonebot2 | 1,757 | python | def get_plugin(name: str) -> Optional[Plugin]:
'\n :说明:\n\n 获取当前导入的某个插件。\n\n :参数:\n\n * ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。\n\n :返回:\n\n - ``Optional[Plugin]``\n '
return plugins.get(name) | def get_plugin(name: str) -> Optional[Plugin]:
'\n :说明:\n\n 获取当前导入的某个插件。\n\n :参数:\n\n * ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。\n\n :返回:\n\n - ``Optional[Plugin]``\n '
return plugins.get(name)<|docstring|>:说明:
获取当前导入的某个插件。
:参数:
* ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。
:返回:
- ``Optional[Plugin]``<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.