partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
valid | RBAC.has_permission | Return does the current user can access the resource.
Example::
@app.route('/some_url', methods=['GET', 'POST'])
@rbac.allow(['anonymous'], ['GET'])
def a_view_func():
return Response('Blah Blah...')
If you are not logged.
`rbac.has_permission('GET', 'a_view_func')` return True.
`rbac.has_permission('POST', 'a_view_func')` return False.
:param method: The method wait to check.
:param endpoint: The application endpoint.
:param user: user who you need to check. Current user by default. | flask_rbac/__init__.py | def has_permission(self, method, endpoint, user=None):
"""Return does the current user can access the resource.
Example::
@app.route('/some_url', methods=['GET', 'POST'])
@rbac.allow(['anonymous'], ['GET'])
def a_view_func():
return Response('Blah Blah...')
If you are not logged.
`rbac.has_permission('GET', 'a_view_func')` return True.
`rbac.has_permission('POST', 'a_view_func')` return False.
:param method: The method wait to check.
:param endpoint: The application endpoint.
:param user: user who you need to check. Current user by default.
"""
app = self.get_app()
_user = user or self._user_loader()
if not hasattr(_user, 'get_roles'):
roles = [anonymous]
else:
roles = _user.get_roles()
return self._check_permission(roles, method, endpoint) | def has_permission(self, method, endpoint, user=None):
"""Return does the current user can access the resource.
Example::
@app.route('/some_url', methods=['GET', 'POST'])
@rbac.allow(['anonymous'], ['GET'])
def a_view_func():
return Response('Blah Blah...')
If you are not logged.
`rbac.has_permission('GET', 'a_view_func')` return True.
`rbac.has_permission('POST', 'a_view_func')` return False.
:param method: The method wait to check.
:param endpoint: The application endpoint.
:param user: user who you need to check. Current user by default.
"""
app = self.get_app()
_user = user or self._user_loader()
if not hasattr(_user, 'get_roles'):
roles = [anonymous]
else:
roles = _user.get_roles()
return self._check_permission(roles, method, endpoint) | [
"Return",
"does",
"the",
"current",
"user",
"can",
"access",
"the",
"resource",
".",
"Example",
"::"
] | shonenada/flask-rbac | python | https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L233-L257 | [
"def",
"has_permission",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"user",
"=",
"None",
")",
":",
"app",
"=",
"self",
".",
"get_app",
"(",
")",
"_user",
"=",
"user",
"or",
"self",
".",
"_user_loader",
"(",
")",
"if",
"not",
"hasattr",
"(",
"_user",
",",
"'get_roles'",
")",
":",
"roles",
"=",
"[",
"anonymous",
"]",
"else",
":",
"roles",
"=",
"_user",
".",
"get_roles",
"(",
")",
"return",
"self",
".",
"_check_permission",
"(",
"roles",
",",
"method",
",",
"endpoint",
")"
] | e085121ff11825114e2d6f8419f0b6de6f9ba476 |
valid | RBAC.allow | This is a decorator function.
You can allow roles to access the view func with it.
An example::
@app.route('/website/setting', methods=['GET', 'POST'])
@rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])
def website_setting():
return Response('Setting page.')
:param roles: List, each name of roles. Please note that,
`anonymous` is refered to anonymous.
If you add `anonymous` to the rule,
everyone can access the resource,
unless you deny other roles.
:param methods: List, each name of methods.
methods is valid in ['GET', 'POST', 'PUT', 'DELETE']
:param with_children: Whether allow children of roles as well.
True by default. | flask_rbac/__init__.py | def allow(self, roles, methods, with_children=True):
"""This is a decorator function.
You can allow roles to access the view func with it.
An example::
@app.route('/website/setting', methods=['GET', 'POST'])
@rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])
def website_setting():
return Response('Setting page.')
:param roles: List, each name of roles. Please note that,
`anonymous` is refered to anonymous.
If you add `anonymous` to the rule,
everyone can access the resource,
unless you deny other roles.
:param methods: List, each name of methods.
methods is valid in ['GET', 'POST', 'PUT', 'DELETE']
:param with_children: Whether allow children of roles as well.
True by default.
"""
def decorator(view_func):
_methods = [m.upper() for m in methods]
for r, m, v in itertools.product(roles, _methods, [view_func.__name__]):
self.before_acl['allow'].append((r, m, v, with_children))
return view_func
return decorator | def allow(self, roles, methods, with_children=True):
"""This is a decorator function.
You can allow roles to access the view func with it.
An example::
@app.route('/website/setting', methods=['GET', 'POST'])
@rbac.allow(['administrator', 'super_user'], ['GET', 'POST'])
def website_setting():
return Response('Setting page.')
:param roles: List, each name of roles. Please note that,
`anonymous` is refered to anonymous.
If you add `anonymous` to the rule,
everyone can access the resource,
unless you deny other roles.
:param methods: List, each name of methods.
methods is valid in ['GET', 'POST', 'PUT', 'DELETE']
:param with_children: Whether allow children of roles as well.
True by default.
"""
def decorator(view_func):
_methods = [m.upper() for m in methods]
for r, m, v in itertools.product(roles, _methods, [view_func.__name__]):
self.before_acl['allow'].append((r, m, v, with_children))
return view_func
return decorator | [
"This",
"is",
"a",
"decorator",
"function",
"."
] | shonenada/flask-rbac | python | https://github.com/shonenada/flask-rbac/blob/e085121ff11825114e2d6f8419f0b6de6f9ba476/flask_rbac/__init__.py#L259-L286 | [
"def",
"allow",
"(",
"self",
",",
"roles",
",",
"methods",
",",
"with_children",
"=",
"True",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"_methods",
"=",
"[",
"m",
".",
"upper",
"(",
")",
"for",
"m",
"in",
"methods",
"]",
"for",
"r",
",",
"m",
",",
"v",
"in",
"itertools",
".",
"product",
"(",
"roles",
",",
"_methods",
",",
"[",
"view_func",
".",
"__name__",
"]",
")",
":",
"self",
".",
"before_acl",
"[",
"'allow'",
"]",
".",
"append",
"(",
"(",
"r",
",",
"m",
",",
"v",
",",
"with_children",
")",
")",
"return",
"view_func",
"return",
"decorator"
] | e085121ff11825114e2d6f8419f0b6de6f9ba476 |
valid | remove_binaries | Remove all binary files in the adslib directory. | setup.py | def remove_binaries():
"""Remove all binary files in the adslib directory."""
patterns = (
"adslib/*.a",
"adslib/*.o",
"adslib/obj/*.o",
"adslib/*.bin",
"adslib/*.so",
)
for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):
os.remove(f) | def remove_binaries():
"""Remove all binary files in the adslib directory."""
patterns = (
"adslib/*.a",
"adslib/*.o",
"adslib/obj/*.o",
"adslib/*.bin",
"adslib/*.so",
)
for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):
os.remove(f) | [
"Remove",
"all",
"binary",
"files",
"in",
"the",
"adslib",
"directory",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/setup.py#L60-L71 | [
"def",
"remove_binaries",
"(",
")",
":",
"patterns",
"=",
"(",
"\"adslib/*.a\"",
",",
"\"adslib/*.o\"",
",",
"\"adslib/obj/*.o\"",
",",
"\"adslib/*.bin\"",
",",
"\"adslib/*.so\"",
",",
")",
"for",
"f",
"in",
"functools",
".",
"reduce",
"(",
"operator",
".",
"iconcat",
",",
"[",
"glob",
".",
"glob",
"(",
"p",
")",
"for",
"p",
"in",
"patterns",
"]",
")",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | router_function | Raise a runtime error if on Win32 systems.
Decorator.
Decorator for functions that interact with the router for the Linux
implementation of the ADS library.
Unlike the Windows implementation which uses a separate router daemon,
the Linux library manages AMS routing in-process. As such, routing must be
configured programatically via. the provided API. These endpoints are
invalid on Win32 systems, so an exception will be raised. | pyads/pyads_ex.py | def router_function(fn):
# type: (Callable) -> Callable
"""Raise a runtime error if on Win32 systems.
Decorator.
Decorator for functions that interact with the router for the Linux
implementation of the ADS library.
Unlike the Windows implementation which uses a separate router daemon,
the Linux library manages AMS routing in-process. As such, routing must be
configured programatically via. the provided API. These endpoints are
invalid on Win32 systems, so an exception will be raised.
"""
@wraps(fn)
def wrapper(*args, **kwargs):
# type: (Any, Any) -> Callable
if platform_is_windows(): # pragma: no cover, skipt Windows test
raise RuntimeError(
"Router interface is not available on Win32 systems.\n"
"Configure AMS routes using the TwinCAT router service."
)
return fn(*args, **kwargs)
return wrapper | def router_function(fn):
# type: (Callable) -> Callable
"""Raise a runtime error if on Win32 systems.
Decorator.
Decorator for functions that interact with the router for the Linux
implementation of the ADS library.
Unlike the Windows implementation which uses a separate router daemon,
the Linux library manages AMS routing in-process. As such, routing must be
configured programatically via. the provided API. These endpoints are
invalid on Win32 systems, so an exception will be raised.
"""
@wraps(fn)
def wrapper(*args, **kwargs):
# type: (Any, Any) -> Callable
if platform_is_windows(): # pragma: no cover, skipt Windows test
raise RuntimeError(
"Router interface is not available on Win32 systems.\n"
"Configure AMS routes using the TwinCAT router service."
)
return fn(*args, **kwargs)
return wrapper | [
"Raise",
"a",
"runtime",
"error",
"if",
"on",
"Win32",
"systems",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L103-L129 | [
"def",
"router_function",
"(",
"fn",
")",
":",
"# type: (Callable) -> Callable",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Any, Any) -> Callable",
"if",
"platform_is_windows",
"(",
")",
":",
"# pragma: no cover, skipt Windows test",
"raise",
"RuntimeError",
"(",
"\"Router interface is not available on Win32 systems.\\n\"",
"\"Configure AMS routes using the TwinCAT router service.\"",
")",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsAddRoute | Establish a new route in the AMS Router.
:param pyads.structs.SAmsNetId net_id: net id of routing endpoint
:param str ip_address: ip address of the routing endpoint | pyads/pyads_ex.py | def adsAddRoute(net_id, ip_address):
# type: (SAmsNetId, str) -> None
"""Establish a new route in the AMS Router.
:param pyads.structs.SAmsNetId net_id: net id of routing endpoint
:param str ip_address: ip address of the routing endpoint
"""
add_route = _adsDLL.AdsAddRoute
add_route.restype = ctypes.c_long
# Convert ip address to bytes (PY3) and get pointer.
ip_address_p = ctypes.c_char_p(ip_address.encode("utf-8"))
error_code = add_route(net_id, ip_address_p)
if error_code:
raise ADSError(error_code) | def adsAddRoute(net_id, ip_address):
# type: (SAmsNetId, str) -> None
"""Establish a new route in the AMS Router.
:param pyads.structs.SAmsNetId net_id: net id of routing endpoint
:param str ip_address: ip address of the routing endpoint
"""
add_route = _adsDLL.AdsAddRoute
add_route.restype = ctypes.c_long
# Convert ip address to bytes (PY3) and get pointer.
ip_address_p = ctypes.c_char_p(ip_address.encode("utf-8"))
error_code = add_route(net_id, ip_address_p)
if error_code:
raise ADSError(error_code) | [
"Establish",
"a",
"new",
"route",
"in",
"the",
"AMS",
"Router",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L133-L150 | [
"def",
"adsAddRoute",
"(",
"net_id",
",",
"ip_address",
")",
":",
"# type: (SAmsNetId, str) -> None",
"add_route",
"=",
"_adsDLL",
".",
"AdsAddRoute",
"add_route",
".",
"restype",
"=",
"ctypes",
".",
"c_long",
"# Convert ip address to bytes (PY3) and get pointer.",
"ip_address_p",
"=",
"ctypes",
".",
"c_char_p",
"(",
"ip_address",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"error_code",
"=",
"add_route",
"(",
"net_id",
",",
"ip_address_p",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsPortOpenEx | Connect to the TwinCAT message router.
:rtype: int
:return: port number | pyads/pyads_ex.py | def adsPortOpenEx():
# type: () -> int
"""Connect to the TwinCAT message router.
:rtype: int
:return: port number
"""
port_open_ex = _adsDLL.AdsPortOpenEx
port_open_ex.restype = ctypes.c_long
port = port_open_ex()
if port == 0:
raise RuntimeError("Failed to open port on AMS router.")
return port | def adsPortOpenEx():
# type: () -> int
"""Connect to the TwinCAT message router.
:rtype: int
:return: port number
"""
port_open_ex = _adsDLL.AdsPortOpenEx
port_open_ex.restype = ctypes.c_long
port = port_open_ex()
if port == 0:
raise RuntimeError("Failed to open port on AMS router.")
return port | [
"Connect",
"to",
"the",
"TwinCAT",
"message",
"router",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L166-L181 | [
"def",
"adsPortOpenEx",
"(",
")",
":",
"# type: () -> int",
"port_open_ex",
"=",
"_adsDLL",
".",
"AdsPortOpenEx",
"port_open_ex",
".",
"restype",
"=",
"ctypes",
".",
"c_long",
"port",
"=",
"port_open_ex",
"(",
")",
"if",
"port",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Failed to open port on AMS router.\"",
")",
"return",
"port"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsPortCloseEx | Close the connection to the TwinCAT message router. | pyads/pyads_ex.py | def adsPortCloseEx(port):
# type: (int) -> None
"""Close the connection to the TwinCAT message router."""
port_close_ex = _adsDLL.AdsPortCloseEx
port_close_ex.restype = ctypes.c_long
error_code = port_close_ex(port)
if error_code:
raise ADSError(error_code) | def adsPortCloseEx(port):
# type: (int) -> None
"""Close the connection to the TwinCAT message router."""
port_close_ex = _adsDLL.AdsPortCloseEx
port_close_ex.restype = ctypes.c_long
error_code = port_close_ex(port)
if error_code:
raise ADSError(error_code) | [
"Close",
"the",
"connection",
"to",
"the",
"TwinCAT",
"message",
"router",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L184-L192 | [
"def",
"adsPortCloseEx",
"(",
"port",
")",
":",
"# type: (int) -> None",
"port_close_ex",
"=",
"_adsDLL",
".",
"AdsPortCloseEx",
"port_close_ex",
".",
"restype",
"=",
"ctypes",
".",
"c_long",
"error_code",
"=",
"port_close_ex",
"(",
"port",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsGetLocalAddressEx | Return the local AMS-address and the port number.
:rtype: pyads.structs.AmsAddr
:return: AMS-address | pyads/pyads_ex.py | def adsGetLocalAddressEx(port):
# type: (int) -> AmsAddr
"""Return the local AMS-address and the port number.
:rtype: pyads.structs.AmsAddr
:return: AMS-address
"""
get_local_address_ex = _adsDLL.AdsGetLocalAddressEx
ams_address_struct = SAmsAddr()
error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))
if error_code:
raise ADSError(error_code)
local_ams_address = AmsAddr()
local_ams_address._ams_addr = ams_address_struct
return local_ams_address | def adsGetLocalAddressEx(port):
# type: (int) -> AmsAddr
"""Return the local AMS-address and the port number.
:rtype: pyads.structs.AmsAddr
:return: AMS-address
"""
get_local_address_ex = _adsDLL.AdsGetLocalAddressEx
ams_address_struct = SAmsAddr()
error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))
if error_code:
raise ADSError(error_code)
local_ams_address = AmsAddr()
local_ams_address._ams_addr = ams_address_struct
return local_ams_address | [
"Return",
"the",
"local",
"AMS",
"-",
"address",
"and",
"the",
"port",
"number",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L195-L213 | [
"def",
"adsGetLocalAddressEx",
"(",
"port",
")",
":",
"# type: (int) -> AmsAddr",
"get_local_address_ex",
"=",
"_adsDLL",
".",
"AdsGetLocalAddressEx",
"ams_address_struct",
"=",
"SAmsAddr",
"(",
")",
"error_code",
"=",
"get_local_address_ex",
"(",
"port",
",",
"ctypes",
".",
"pointer",
"(",
"ams_address_struct",
")",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")",
"local_ams_address",
"=",
"AmsAddr",
"(",
")",
"local_ams_address",
".",
"_ams_addr",
"=",
"ams_address_struct",
"return",
"local_ams_address"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncReadStateReqEx | Read the current ADS-state and the machine-state.
Read the current ADS-state and the machine-state from the
ADS-server.
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: (int, int)
:return: ads_state, device_state | pyads/pyads_ex.py | def adsSyncReadStateReqEx(port, address):
# type: (int, AmsAddr) -> Tuple[int, int]
"""Read the current ADS-state and the machine-state.
Read the current ADS-state and the machine-state from the
ADS-server.
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: (int, int)
:return: ads_state, device_state
"""
sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx
# C pointer to ams address struct
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
# Current ADS status and corresponding pointer
ads_state = ctypes.c_int()
ads_state_pointer = ctypes.pointer(ads_state)
# Current device status and corresponding pointer
device_state = ctypes.c_int()
device_state_pointer = ctypes.pointer(device_state)
error_code = sync_read_state_request(
port, ams_address_pointer, ads_state_pointer, device_state_pointer
)
if error_code:
raise ADSError(error_code)
return (ads_state.value, device_state.value) | def adsSyncReadStateReqEx(port, address):
# type: (int, AmsAddr) -> Tuple[int, int]
"""Read the current ADS-state and the machine-state.
Read the current ADS-state and the machine-state from the
ADS-server.
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: (int, int)
:return: ads_state, device_state
"""
sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx
# C pointer to ams address struct
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
# Current ADS status and corresponding pointer
ads_state = ctypes.c_int()
ads_state_pointer = ctypes.pointer(ads_state)
# Current device status and corresponding pointer
device_state = ctypes.c_int()
device_state_pointer = ctypes.pointer(device_state)
error_code = sync_read_state_request(
port, ams_address_pointer, ads_state_pointer, device_state_pointer
)
if error_code:
raise ADSError(error_code)
return (ads_state.value, device_state.value) | [
"Read",
"the",
"current",
"ADS",
"-",
"state",
"and",
"the",
"machine",
"-",
"state",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L228-L260 | [
"def",
"adsSyncReadStateReqEx",
"(",
"port",
",",
"address",
")",
":",
"# type: (int, AmsAddr) -> Tuple[int, int]",
"sync_read_state_request",
"=",
"_adsDLL",
".",
"AdsSyncReadStateReqEx",
"# C pointer to ams address struct",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"# Current ADS status and corresponding pointer",
"ads_state",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"ads_state_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"ads_state",
")",
"# Current device status and corresponding pointer",
"device_state",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"device_state_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"device_state",
")",
"error_code",
"=",
"sync_read_state_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"ads_state_pointer",
",",
"device_state_pointer",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")",
"return",
"(",
"ads_state",
".",
"value",
",",
"device_state",
".",
"value",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncReadDeviceInfoReqEx | Read the name and the version number of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: string, AdsVersion
:return: device name, version | pyads/pyads_ex.py | def adsSyncReadDeviceInfoReqEx(port, address):
# type: (int, AmsAddr) -> Tuple[str, AdsVersion]
"""Read the name and the version number of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: string, AdsVersion
:return: device name, version
"""
sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx
# Get pointer to the target AMS address
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
# Create buffer to be filled with device name, get pointer to said buffer
device_name_buffer = ctypes.create_string_buffer(20)
device_name_pointer = ctypes.pointer(device_name_buffer)
# Create ADS Version struct and get pointer.
ads_version = SAdsVersion()
ads_version_pointer = ctypes.pointer(ads_version)
error_code = sync_read_device_info_request(
port, ams_address_pointer, device_name_pointer, ads_version_pointer
)
if error_code:
raise ADSError(error_code)
return (device_name_buffer.value.decode(), AdsVersion(ads_version)) | def adsSyncReadDeviceInfoReqEx(port, address):
# type: (int, AmsAddr) -> Tuple[str, AdsVersion]
"""Read the name and the version number of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:rtype: string, AdsVersion
:return: device name, version
"""
sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx
# Get pointer to the target AMS address
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
# Create buffer to be filled with device name, get pointer to said buffer
device_name_buffer = ctypes.create_string_buffer(20)
device_name_pointer = ctypes.pointer(device_name_buffer)
# Create ADS Version struct and get pointer.
ads_version = SAdsVersion()
ads_version_pointer = ctypes.pointer(ads_version)
error_code = sync_read_device_info_request(
port, ams_address_pointer, device_name_pointer, ads_version_pointer
)
if error_code:
raise ADSError(error_code)
return (device_name_buffer.value.decode(), AdsVersion(ads_version)) | [
"Read",
"the",
"name",
"and",
"the",
"version",
"number",
"of",
"the",
"ADS",
"-",
"server",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L263-L293 | [
"def",
"adsSyncReadDeviceInfoReqEx",
"(",
"port",
",",
"address",
")",
":",
"# type: (int, AmsAddr) -> Tuple[str, AdsVersion]",
"sync_read_device_info_request",
"=",
"_adsDLL",
".",
"AdsSyncReadDeviceInfoReqEx",
"# Get pointer to the target AMS address",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"# Create buffer to be filled with device name, get pointer to said buffer",
"device_name_buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"20",
")",
"device_name_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"device_name_buffer",
")",
"# Create ADS Version struct and get pointer.",
"ads_version",
"=",
"SAdsVersion",
"(",
")",
"ads_version_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"ads_version",
")",
"error_code",
"=",
"sync_read_device_info_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"device_name_pointer",
",",
"ads_version_pointer",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")",
"return",
"(",
"device_name_buffer",
".",
"value",
".",
"decode",
"(",
")",
",",
"AdsVersion",
"(",
"ads_version",
")",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncWriteControlReqEx | Change the ADS state and the machine-state of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_data_type: plc datatype, according to PLCTYPE constants | pyads/pyads_ex.py | def adsSyncWriteControlReqEx(
port, address, ads_state, device_state, data, plc_data_type
):
# type: (int, AmsAddr, int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_data_type: plc datatype, according to PLCTYPE constants
"""
sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
ads_state_c = ctypes.c_ulong(ads_state)
device_state_c = ctypes.c_ulong(device_state)
if plc_data_type == PLCTYPE_STRING:
data = ctypes.c_char_p(data.encode("utf-8"))
data_pointer = data
data_length = len(data_pointer.value) + 1
else:
data = plc_data_type(data)
data_pointer = ctypes.pointer(data)
data_length = ctypes.sizeof(data)
error_code = sync_write_control_request(
port,
ams_address_pointer,
ads_state_c,
device_state_c,
data_length,
data_pointer,
)
if error_code:
raise ADSError(error_code) | def adsSyncWriteControlReqEx(
port, address, ads_state, device_state, data, plc_data_type
):
# type: (int, AmsAddr, int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_data_type: plc datatype, according to PLCTYPE constants
"""
sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
ads_state_c = ctypes.c_ulong(ads_state)
device_state_c = ctypes.c_ulong(device_state)
if plc_data_type == PLCTYPE_STRING:
data = ctypes.c_char_p(data.encode("utf-8"))
data_pointer = data
data_length = len(data_pointer.value) + 1
else:
data = plc_data_type(data)
data_pointer = ctypes.pointer(data)
data_length = ctypes.sizeof(data)
error_code = sync_write_control_request(
port,
ams_address_pointer,
ads_state_c,
device_state_c,
data_length,
data_pointer,
)
if error_code:
raise ADSError(error_code) | [
"Change",
"the",
"ADS",
"state",
"and",
"the",
"machine",
"-",
"state",
"of",
"the",
"ADS",
"-",
"server",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L296-L335 | [
"def",
"adsSyncWriteControlReqEx",
"(",
"port",
",",
"address",
",",
"ads_state",
",",
"device_state",
",",
"data",
",",
"plc_data_type",
")",
":",
"# type: (int, AmsAddr, int, int, Any, Type) -> None",
"sync_write_control_request",
"=",
"_adsDLL",
".",
"AdsSyncWriteControlReqEx",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"ads_state_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"ads_state",
")",
"device_state_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"device_state",
")",
"if",
"plc_data_type",
"==",
"PLCTYPE_STRING",
":",
"data",
"=",
"ctypes",
".",
"c_char_p",
"(",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"data_pointer",
"=",
"data",
"data_length",
"=",
"len",
"(",
"data_pointer",
".",
"value",
")",
"+",
"1",
"else",
":",
"data",
"=",
"plc_data_type",
"(",
"data",
")",
"data_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"data",
")",
"data_length",
"=",
"ctypes",
".",
"sizeof",
"(",
"data",
")",
"error_code",
"=",
"sync_write_control_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"ads_state_c",
",",
"device_state_c",
",",
"data_length",
",",
"data_pointer",
",",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncWriteReqEx | Send data synchronous to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int indexGroup: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_data_type: type of the data given to the PLC,
according to PLCTYPE constants | pyads/pyads_ex.py | def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):
# type: (int, AmsAddr, int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int indexGroup: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_data_type: type of the data given to the PLC,
according to PLCTYPE constants
"""
sync_write_request = _adsDLL.AdsSyncWriteReqEx
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if plc_data_type == PLCTYPE_STRING:
data = ctypes.c_char_p(value.encode("utf-8"))
data_pointer = data # type: Union[ctypes.c_char_p, ctypes.pointer]
data_length = len(data_pointer.value) + 1 # type: ignore
else:
if type(plc_data_type).__name__ == "PyCArrayType":
data = plc_data_type(*value)
else:
data = plc_data_type(value)
data_pointer = ctypes.pointer(data)
data_length = ctypes.sizeof(data)
error_code = sync_write_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
data_length,
data_pointer,
)
if error_code:
raise ADSError(error_code) | def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):
# type: (int, AmsAddr, int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int indexGroup: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_data_type: type of the data given to the PLC,
according to PLCTYPE constants
"""
sync_write_request = _adsDLL.AdsSyncWriteReqEx
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if plc_data_type == PLCTYPE_STRING:
data = ctypes.c_char_p(value.encode("utf-8"))
data_pointer = data # type: Union[ctypes.c_char_p, ctypes.pointer]
data_length = len(data_pointer.value) + 1 # type: ignore
else:
if type(plc_data_type).__name__ == "PyCArrayType":
data = plc_data_type(*value)
else:
data = plc_data_type(value)
data_pointer = ctypes.pointer(data)
data_length = ctypes.sizeof(data)
error_code = sync_write_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
data_length,
data_pointer,
)
if error_code:
raise ADSError(error_code) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L338-L382 | [
"def",
"adsSyncWriteReqEx",
"(",
"port",
",",
"address",
",",
"index_group",
",",
"index_offset",
",",
"value",
",",
"plc_data_type",
")",
":",
"# type: (int, AmsAddr, int, int, Any, Type) -> None",
"sync_write_request",
"=",
"_adsDLL",
".",
"AdsSyncWriteReqEx",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"index_group_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_group",
")",
"index_offset_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_offset",
")",
"if",
"plc_data_type",
"==",
"PLCTYPE_STRING",
":",
"data",
"=",
"ctypes",
".",
"c_char_p",
"(",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"data_pointer",
"=",
"data",
"# type: Union[ctypes.c_char_p, ctypes.pointer]",
"data_length",
"=",
"len",
"(",
"data_pointer",
".",
"value",
")",
"+",
"1",
"# type: ignore",
"else",
":",
"if",
"type",
"(",
"plc_data_type",
")",
".",
"__name__",
"==",
"\"PyCArrayType\"",
":",
"data",
"=",
"plc_data_type",
"(",
"*",
"value",
")",
"else",
":",
"data",
"=",
"plc_data_type",
"(",
"value",
")",
"data_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"data",
")",
"data_length",
"=",
"ctypes",
".",
"sizeof",
"(",
"data",
")",
"error_code",
"=",
"sync_write_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"index_group_c",
",",
"index_offset_c",
",",
"data_length",
",",
"data_pointer",
",",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncReadWriteReqEx2 | Read and write data synchronous from/to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type read_data_type: type of the data given to the PLC to respond to,
according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type write_data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: read_data_type
:return: value: value read from PLC | pyads/pyads_ex.py | def adsSyncReadWriteReqEx2(
port,
address,
index_group,
index_offset,
read_data_type,
value,
write_data_type,
return_ctypes=False,
):
# type: (int, AmsAddr, int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type read_data_type: type of the data given to the PLC to respond to,
according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type write_data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: read_data_type
:return: value: value read from PLC
"""
sync_read_write_request = _adsDLL.AdsSyncReadWriteReqEx2
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if read_data_type == PLCTYPE_STRING:
read_data = (STRING_BUFFER * PLCTYPE_STRING)()
else:
read_data = read_data_type()
read_data_pointer = ctypes.pointer(read_data)
read_length = ctypes.c_ulong(ctypes.sizeof(read_data))
bytes_read = ctypes.c_ulong()
bytes_read_pointer = ctypes.pointer(bytes_read)
if write_data_type == PLCTYPE_STRING:
# Get pointer to string
write_data_pointer = ctypes.c_char_p(
value.encode("utf-8")
) # type: Union[ctypes.c_char_p, ctypes.pointer] # noqa: E501
# Add an extra byte to the data length for the null terminator
write_length = len(value) + 1
else:
if type(write_data_type).__name__ == "PyCArrayType":
write_data = write_data_type(*value)
else:
write_data = write_data_type(value)
write_data_pointer = ctypes.pointer(write_data)
write_length = ctypes.sizeof(write_data)
err_code = sync_read_write_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
read_length,
read_data_pointer,
write_length,
write_data_pointer,
bytes_read_pointer,
)
if err_code:
raise ADSError(err_code)
# If we're reading a value of predetermined size (anything but a string),
# validate that the correct number of bytes were read
if read_data_type != PLCTYPE_STRING and bytes_read.value != read_length.value:
raise RuntimeError(
"Insufficient data (expected {0} bytes, {1} were read).".format(
read_length.value, bytes_read.value
)
)
if return_ctypes:
return read_data
if read_data_type == PLCTYPE_STRING:
return read_data.value.decode("utf-8")
if type(read_data_type).__name__ == "PyCArrayType":
return [i for i in read_data]
if hasattr(read_data, "value"):
return read_data.value
return read_data | def adsSyncReadWriteReqEx2(
port,
address,
index_group,
index_offset,
read_data_type,
value,
write_data_type,
return_ctypes=False,
):
# type: (int, AmsAddr, int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type read_data_type: type of the data given to the PLC to respond to,
according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type write_data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: read_data_type
:return: value: value read from PLC
"""
sync_read_write_request = _adsDLL.AdsSyncReadWriteReqEx2
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if read_data_type == PLCTYPE_STRING:
read_data = (STRING_BUFFER * PLCTYPE_STRING)()
else:
read_data = read_data_type()
read_data_pointer = ctypes.pointer(read_data)
read_length = ctypes.c_ulong(ctypes.sizeof(read_data))
bytes_read = ctypes.c_ulong()
bytes_read_pointer = ctypes.pointer(bytes_read)
if write_data_type == PLCTYPE_STRING:
# Get pointer to string
write_data_pointer = ctypes.c_char_p(
value.encode("utf-8")
) # type: Union[ctypes.c_char_p, ctypes.pointer] # noqa: E501
# Add an extra byte to the data length for the null terminator
write_length = len(value) + 1
else:
if type(write_data_type).__name__ == "PyCArrayType":
write_data = write_data_type(*value)
else:
write_data = write_data_type(value)
write_data_pointer = ctypes.pointer(write_data)
write_length = ctypes.sizeof(write_data)
err_code = sync_read_write_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
read_length,
read_data_pointer,
write_length,
write_data_pointer,
bytes_read_pointer,
)
if err_code:
raise ADSError(err_code)
# If we're reading a value of predetermined size (anything but a string),
# validate that the correct number of bytes were read
if read_data_type != PLCTYPE_STRING and bytes_read.value != read_length.value:
raise RuntimeError(
"Insufficient data (expected {0} bytes, {1} were read).".format(
read_length.value, bytes_read.value
)
)
if return_ctypes:
return read_data
if read_data_type == PLCTYPE_STRING:
return read_data.value.decode("utf-8")
if type(read_data_type).__name__ == "PyCArrayType":
return [i for i in read_data]
if hasattr(read_data, "value"):
return read_data.value
return read_data | [
"Read",
"and",
"write",
"data",
"synchronous",
"from",
"/",
"to",
"an",
"ADS",
"-",
"device",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L385-L482 | [
"def",
"adsSyncReadWriteReqEx2",
"(",
"port",
",",
"address",
",",
"index_group",
",",
"index_offset",
",",
"read_data_type",
",",
"value",
",",
"write_data_type",
",",
"return_ctypes",
"=",
"False",
",",
")",
":",
"# type: (int, AmsAddr, int, int, Type, Any, Type, bool) -> Any",
"sync_read_write_request",
"=",
"_adsDLL",
".",
"AdsSyncReadWriteReqEx2",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"index_group_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_group",
")",
"index_offset_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_offset",
")",
"if",
"read_data_type",
"==",
"PLCTYPE_STRING",
":",
"read_data",
"=",
"(",
"STRING_BUFFER",
"*",
"PLCTYPE_STRING",
")",
"(",
")",
"else",
":",
"read_data",
"=",
"read_data_type",
"(",
")",
"read_data_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"read_data",
")",
"read_length",
"=",
"ctypes",
".",
"c_ulong",
"(",
"ctypes",
".",
"sizeof",
"(",
"read_data",
")",
")",
"bytes_read",
"=",
"ctypes",
".",
"c_ulong",
"(",
")",
"bytes_read_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"bytes_read",
")",
"if",
"write_data_type",
"==",
"PLCTYPE_STRING",
":",
"# Get pointer to string",
"write_data_pointer",
"=",
"ctypes",
".",
"c_char_p",
"(",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# type: Union[ctypes.c_char_p, ctypes.pointer] # noqa: E501",
"# Add an extra byte to the data length for the null terminator",
"write_length",
"=",
"len",
"(",
"value",
")",
"+",
"1",
"else",
":",
"if",
"type",
"(",
"write_data_type",
")",
".",
"__name__",
"==",
"\"PyCArrayType\"",
":",
"write_data",
"=",
"write_data_type",
"(",
"*",
"value",
")",
"else",
":",
"write_data",
"=",
"write_data_type",
"(",
"value",
")",
"write_data_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"write_data",
")",
"write_length",
"=",
"ctypes",
".",
"sizeof",
"(",
"write_data",
")",
"err_code",
"=",
"sync_read_write_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"index_group_c",
",",
"index_offset_c",
",",
"read_length",
",",
"read_data_pointer",
",",
"write_length",
",",
"write_data_pointer",
",",
"bytes_read_pointer",
",",
")",
"if",
"err_code",
":",
"raise",
"ADSError",
"(",
"err_code",
")",
"# If we're reading a value of predetermined size (anything but a string),",
"# validate that the correct number of bytes were read",
"if",
"read_data_type",
"!=",
"PLCTYPE_STRING",
"and",
"bytes_read",
".",
"value",
"!=",
"read_length",
".",
"value",
":",
"raise",
"RuntimeError",
"(",
"\"Insufficient data (expected {0} bytes, {1} were read).\"",
".",
"format",
"(",
"read_length",
".",
"value",
",",
"bytes_read",
".",
"value",
")",
")",
"if",
"return_ctypes",
":",
"return",
"read_data",
"if",
"read_data_type",
"==",
"PLCTYPE_STRING",
":",
"return",
"read_data",
".",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"type",
"(",
"read_data_type",
")",
".",
"__name__",
"==",
"\"PyCArrayType\"",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"read_data",
"]",
"if",
"hasattr",
"(",
"read_data",
",",
"\"value\"",
")",
":",
"return",
"read_data",
".",
"value",
"return",
"read_data"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncReadReqEx2 | Read data synchronous from an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value** | pyads/pyads_ex.py | def adsSyncReadReqEx2(
port, address, index_group, index_offset, data_type, return_ctypes=False
):
# type: (int, AmsAddr, int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value**
"""
sync_read_request = _adsDLL.AdsSyncReadReqEx2
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if data_type == PLCTYPE_STRING:
data = (STRING_BUFFER * PLCTYPE_STRING)()
else:
data = data_type()
data_pointer = ctypes.pointer(data)
data_length = ctypes.c_ulong(ctypes.sizeof(data))
bytes_read = ctypes.c_ulong()
bytes_read_pointer = ctypes.pointer(bytes_read)
error_code = sync_read_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
data_length,
data_pointer,
bytes_read_pointer,
)
if error_code:
raise ADSError(error_code)
# If we're reading a value of predetermined size (anything but a string),
# validate that the correct number of bytes were read
if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:
raise RuntimeError(
"Insufficient data (expected {0} bytes, {1} were read).".format(
data_length.value, bytes_read.value
)
)
if return_ctypes:
return data
if data_type == PLCTYPE_STRING:
return data.value.decode("utf-8")
if type(data_type).__name__ == "PyCArrayType":
return [i for i in data]
if hasattr(data, "value"):
return data.value
return data | def adsSyncReadReqEx2(
port, address, index_group, index_offset, data_type, return_ctypes=False
):
# type: (int, AmsAddr, int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value**
"""
sync_read_request = _adsDLL.AdsSyncReadReqEx2
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_offset)
if data_type == PLCTYPE_STRING:
data = (STRING_BUFFER * PLCTYPE_STRING)()
else:
data = data_type()
data_pointer = ctypes.pointer(data)
data_length = ctypes.c_ulong(ctypes.sizeof(data))
bytes_read = ctypes.c_ulong()
bytes_read_pointer = ctypes.pointer(bytes_read)
error_code = sync_read_request(
port,
ams_address_pointer,
index_group_c,
index_offset_c,
data_length,
data_pointer,
bytes_read_pointer,
)
if error_code:
raise ADSError(error_code)
# If we're reading a value of predetermined size (anything but a string),
# validate that the correct number of bytes were read
if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:
raise RuntimeError(
"Insufficient data (expected {0} bytes, {1} were read).".format(
data_length.value, bytes_read.value
)
)
if return_ctypes:
return data
if data_type == PLCTYPE_STRING:
return data.value.decode("utf-8")
if type(data_type).__name__ == "PyCArrayType":
return [i for i in data]
if hasattr(data, "value"):
return data.value
return data | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L485-L555 | [
"def",
"adsSyncReadReqEx2",
"(",
"port",
",",
"address",
",",
"index_group",
",",
"index_offset",
",",
"data_type",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (int, AmsAddr, int, int, Type, bool) -> Any",
"sync_read_request",
"=",
"_adsDLL",
".",
"AdsSyncReadReqEx2",
"ams_address_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"address",
".",
"amsAddrStruct",
"(",
")",
")",
"index_group_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_group",
")",
"index_offset_c",
"=",
"ctypes",
".",
"c_ulong",
"(",
"index_offset",
")",
"if",
"data_type",
"==",
"PLCTYPE_STRING",
":",
"data",
"=",
"(",
"STRING_BUFFER",
"*",
"PLCTYPE_STRING",
")",
"(",
")",
"else",
":",
"data",
"=",
"data_type",
"(",
")",
"data_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"data",
")",
"data_length",
"=",
"ctypes",
".",
"c_ulong",
"(",
"ctypes",
".",
"sizeof",
"(",
"data",
")",
")",
"bytes_read",
"=",
"ctypes",
".",
"c_ulong",
"(",
")",
"bytes_read_pointer",
"=",
"ctypes",
".",
"pointer",
"(",
"bytes_read",
")",
"error_code",
"=",
"sync_read_request",
"(",
"port",
",",
"ams_address_pointer",
",",
"index_group_c",
",",
"index_offset_c",
",",
"data_length",
",",
"data_pointer",
",",
"bytes_read_pointer",
",",
")",
"if",
"error_code",
":",
"raise",
"ADSError",
"(",
"error_code",
")",
"# If we're reading a value of predetermined size (anything but a string),",
"# validate that the correct number of bytes were read",
"if",
"data_type",
"!=",
"PLCTYPE_STRING",
"and",
"bytes_read",
".",
"value",
"!=",
"data_length",
".",
"value",
":",
"raise",
"RuntimeError",
"(",
"\"Insufficient data (expected {0} bytes, {1} were read).\"",
".",
"format",
"(",
"data_length",
".",
"value",
",",
"bytes_read",
".",
"value",
")",
")",
"if",
"return_ctypes",
":",
"return",
"data",
"if",
"data_type",
"==",
"PLCTYPE_STRING",
":",
"return",
"data",
".",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"type",
"(",
"data_type",
")",
".",
"__name__",
"==",
"\"PyCArrayType\"",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"data",
"]",
"if",
"hasattr",
"(",
"data",
",",
"\"value\"",
")",
":",
"return",
"data",
".",
"value",
"return",
"data"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncReadByNameEx | Read data synchronous from an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: data name
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value** | pyads/pyads_ex.py | def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):
# type: (int, AmsAddr, str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: data name
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value**
"""
# Get the handle of the PLC-variable
handle = adsSyncReadWriteReqEx2(
port,
address,
ADSIGRP_SYM_HNDBYNAME,
0x0,
PLCTYPE_UDINT,
data_name,
PLCTYPE_STRING,
)
# Read the value of a PLC-variable, via handle
value = adsSyncReadReqEx2(
port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes
)
# Release the handle of the PLC-variable
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)
return value | def adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):
# type: (int, AmsAddr, str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: data name
:param Type data_type: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: data_type
:return: value: **value**
"""
# Get the handle of the PLC-variable
handle = adsSyncReadWriteReqEx2(
port,
address,
ADSIGRP_SYM_HNDBYNAME,
0x0,
PLCTYPE_UDINT,
data_name,
PLCTYPE_STRING,
)
# Read the value of a PLC-variable, via handle
value = adsSyncReadReqEx2(
port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes
)
# Release the handle of the PLC-variable
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)
return value | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L558-L592 | [
"def",
"adsSyncReadByNameEx",
"(",
"port",
",",
"address",
",",
"data_name",
",",
"data_type",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (int, AmsAddr, str, Type, bool) -> Any",
"# Get the handle of the PLC-variable",
"handle",
"=",
"adsSyncReadWriteReqEx2",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_HNDBYNAME",
",",
"0x0",
",",
"PLCTYPE_UDINT",
",",
"data_name",
",",
"PLCTYPE_STRING",
",",
")",
"# Read the value of a PLC-variable, via handle",
"value",
"=",
"adsSyncReadReqEx2",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_VALBYHND",
",",
"handle",
",",
"data_type",
",",
"return_ctypes",
")",
"# Release the handle of the PLC-variable",
"adsSyncWriteReqEx",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_RELEASEHND",
",",
"0",
",",
"handle",
",",
"PLCTYPE_UDINT",
")",
"return",
"value"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncWriteByNameEx | Send data synchronous to an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type data_type: type of the data given to the PLC,
according to PLCTYPE constants | pyads/pyads_ex.py | def adsSyncWriteByNameEx(port, address, data_name, value, data_type):
# type: (int, AmsAddr, str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type data_type: type of the data given to the PLC,
according to PLCTYPE constants
"""
# Get the handle of the PLC-variable
handle = adsSyncReadWriteReqEx2(
port,
address,
ADSIGRP_SYM_HNDBYNAME,
0x0,
PLCTYPE_UDINT,
data_name,
PLCTYPE_STRING,
)
# Write the value of a PLC-variable, via handle
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)
# Release the handle of the PLC-variable
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT) | def adsSyncWriteByNameEx(port, address, data_name, value, data_type):
# type: (int, AmsAddr, str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type data_type: type of the data given to the PLC,
according to PLCTYPE constants
"""
# Get the handle of the PLC-variable
handle = adsSyncReadWriteReqEx2(
port,
address,
ADSIGRP_SYM_HNDBYNAME,
0x0,
PLCTYPE_UDINT,
data_name,
PLCTYPE_STRING,
)
# Write the value of a PLC-variable, via handle
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)
# Release the handle of the PLC-variable
adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L595-L622 | [
"def",
"adsSyncWriteByNameEx",
"(",
"port",
",",
"address",
",",
"data_name",
",",
"value",
",",
"data_type",
")",
":",
"# type: (int, AmsAddr, str, Any, Type) -> None",
"# Get the handle of the PLC-variable",
"handle",
"=",
"adsSyncReadWriteReqEx2",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_HNDBYNAME",
",",
"0x0",
",",
"PLCTYPE_UDINT",
",",
"data_name",
",",
"PLCTYPE_STRING",
",",
")",
"# Write the value of a PLC-variable, via handle",
"adsSyncWriteReqEx",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_VALBYHND",
",",
"handle",
",",
"value",
",",
"data_type",
")",
"# Release the handle of the PLC-variable",
"adsSyncWriteReqEx",
"(",
"port",
",",
"address",
",",
"ADSIGRP_SYM_RELEASEHND",
",",
"0",
",",
"handle",
",",
"PLCTYPE_UDINT",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncAddDeviceNotificationReqEx | Add a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
:param callback: Callback function to handle notification
:param user_handle: User Handle
:rtype: (int, int)
:returns: notification handle, user handle | pyads/pyads_ex.py | def adsSyncAddDeviceNotificationReqEx(
port, adr, data_name, pNoteAttrib, callback, user_handle=None
):
# type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]
"""Add a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
:param callback: Callback function to handle notification
:param user_handle: User Handle
:rtype: (int, int)
:returns: notification handle, user handle
"""
global callback_store
if NOTEFUNC is None:
raise TypeError("Callback function type can't be None")
adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx
pAmsAddr = ctypes.pointer(adr.amsAddrStruct())
hnl = adsSyncReadWriteReqEx2(
port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING
)
nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)
nIndexOffset = ctypes.c_ulong(hnl)
attrib = pNoteAttrib.notificationAttribStruct()
pNotification = ctypes.c_ulong()
nHUser = ctypes.c_ulong(hnl)
if user_handle is not None:
nHUser = ctypes.c_ulong(user_handle)
adsSyncAddDeviceNotificationReqFct.argtypes = [
ctypes.c_ulong,
ctypes.POINTER(SAmsAddr),
ctypes.c_ulong,
ctypes.c_ulong,
ctypes.POINTER(SAdsNotificationAttrib),
NOTEFUNC,
ctypes.c_ulong,
ctypes.POINTER(ctypes.c_ulong),
]
adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long
def wrapper(addr, notification, user):
# type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]
return callback(notification, data_name)
c_callback = NOTEFUNC(wrapper)
err_code = adsSyncAddDeviceNotificationReqFct(
port,
pAmsAddr,
nIndexGroup,
nIndexOffset,
ctypes.byref(attrib),
c_callback,
nHUser,
ctypes.byref(pNotification),
)
if err_code:
raise ADSError(err_code)
callback_store[pNotification.value] = c_callback
return (pNotification.value, hnl) | def adsSyncAddDeviceNotificationReqEx(
port, adr, data_name, pNoteAttrib, callback, user_handle=None
):
# type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]
"""Add a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
:param callback: Callback function to handle notification
:param user_handle: User Handle
:rtype: (int, int)
:returns: notification handle, user handle
"""
global callback_store
if NOTEFUNC is None:
raise TypeError("Callback function type can't be None")
adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx
pAmsAddr = ctypes.pointer(adr.amsAddrStruct())
hnl = adsSyncReadWriteReqEx2(
port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING
)
nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)
nIndexOffset = ctypes.c_ulong(hnl)
attrib = pNoteAttrib.notificationAttribStruct()
pNotification = ctypes.c_ulong()
nHUser = ctypes.c_ulong(hnl)
if user_handle is not None:
nHUser = ctypes.c_ulong(user_handle)
adsSyncAddDeviceNotificationReqFct.argtypes = [
ctypes.c_ulong,
ctypes.POINTER(SAmsAddr),
ctypes.c_ulong,
ctypes.c_ulong,
ctypes.POINTER(SAdsNotificationAttrib),
NOTEFUNC,
ctypes.c_ulong,
ctypes.POINTER(ctypes.c_ulong),
]
adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long
def wrapper(addr, notification, user):
# type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]
return callback(notification, data_name)
c_callback = NOTEFUNC(wrapper)
err_code = adsSyncAddDeviceNotificationReqFct(
port,
pAmsAddr,
nIndexGroup,
nIndexOffset,
ctypes.byref(attrib),
c_callback,
nHUser,
ctypes.byref(pNotification),
)
if err_code:
raise ADSError(err_code)
callback_store[pNotification.value] = c_callback
return (pNotification.value, hnl) | [
"Add",
"a",
"device",
"notification",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L625-L693 | [
"def",
"adsSyncAddDeviceNotificationReqEx",
"(",
"port",
",",
"adr",
",",
"data_name",
",",
"pNoteAttrib",
",",
"callback",
",",
"user_handle",
"=",
"None",
")",
":",
"# type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]",
"global",
"callback_store",
"if",
"NOTEFUNC",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Callback function type can't be None\"",
")",
"adsSyncAddDeviceNotificationReqFct",
"=",
"_adsDLL",
".",
"AdsSyncAddDeviceNotificationReqEx",
"pAmsAddr",
"=",
"ctypes",
".",
"pointer",
"(",
"adr",
".",
"amsAddrStruct",
"(",
")",
")",
"hnl",
"=",
"adsSyncReadWriteReqEx2",
"(",
"port",
",",
"adr",
",",
"ADSIGRP_SYM_HNDBYNAME",
",",
"0x0",
",",
"PLCTYPE_UDINT",
",",
"data_name",
",",
"PLCTYPE_STRING",
")",
"nIndexGroup",
"=",
"ctypes",
".",
"c_ulong",
"(",
"ADSIGRP_SYM_VALBYHND",
")",
"nIndexOffset",
"=",
"ctypes",
".",
"c_ulong",
"(",
"hnl",
")",
"attrib",
"=",
"pNoteAttrib",
".",
"notificationAttribStruct",
"(",
")",
"pNotification",
"=",
"ctypes",
".",
"c_ulong",
"(",
")",
"nHUser",
"=",
"ctypes",
".",
"c_ulong",
"(",
"hnl",
")",
"if",
"user_handle",
"is",
"not",
"None",
":",
"nHUser",
"=",
"ctypes",
".",
"c_ulong",
"(",
"user_handle",
")",
"adsSyncAddDeviceNotificationReqFct",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"POINTER",
"(",
"SAmsAddr",
")",
",",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"POINTER",
"(",
"SAdsNotificationAttrib",
")",
",",
"NOTEFUNC",
",",
"ctypes",
".",
"c_ulong",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_ulong",
")",
",",
"]",
"adsSyncAddDeviceNotificationReqFct",
".",
"restype",
"=",
"ctypes",
".",
"c_long",
"def",
"wrapper",
"(",
"addr",
",",
"notification",
",",
"user",
")",
":",
"# type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]",
"return",
"callback",
"(",
"notification",
",",
"data_name",
")",
"c_callback",
"=",
"NOTEFUNC",
"(",
"wrapper",
")",
"err_code",
"=",
"adsSyncAddDeviceNotificationReqFct",
"(",
"port",
",",
"pAmsAddr",
",",
"nIndexGroup",
",",
"nIndexOffset",
",",
"ctypes",
".",
"byref",
"(",
"attrib",
")",
",",
"c_callback",
",",
"nHUser",
",",
"ctypes",
".",
"byref",
"(",
"pNotification",
")",
",",
")",
"if",
"err_code",
":",
"raise",
"ADSError",
"(",
"err_code",
")",
"callback_store",
"[",
"pNotification",
".",
"value",
"]",
"=",
"c_callback",
"return",
"(",
"pNotification",
".",
"value",
",",
"hnl",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncDelDeviceNotificationReqEx | Remove a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int notification_handle: Notification Handle
:param int user_handle: User Handle | pyads/pyads_ex.py | def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):
# type: (int, AmsAddr, int, int) -> None
"""Remove a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int notification_handle: Notification Handle
:param int user_handle: User Handle
"""
adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx
pAmsAddr = ctypes.pointer(adr.amsAddrStruct())
nHNotification = ctypes.c_ulong(notification_handle)
err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)
callback_store.pop(notification_handle, None)
if err_code:
raise ADSError(err_code)
adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, 0, user_handle, PLCTYPE_UDINT) | def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):
# type: (int, AmsAddr, int, int) -> None
"""Remove a device notification.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int notification_handle: Notification Handle
:param int user_handle: User Handle
"""
adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx
pAmsAddr = ctypes.pointer(adr.amsAddrStruct())
nHNotification = ctypes.c_ulong(notification_handle)
err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)
callback_store.pop(notification_handle, None)
if err_code:
raise ADSError(err_code)
adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, 0, user_handle, PLCTYPE_UDINT) | [
"Remove",
"a",
"device",
"notification",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L696-L715 | [
"def",
"adsSyncDelDeviceNotificationReqEx",
"(",
"port",
",",
"adr",
",",
"notification_handle",
",",
"user_handle",
")",
":",
"# type: (int, AmsAddr, int, int) -> None",
"adsSyncDelDeviceNotificationReqFct",
"=",
"_adsDLL",
".",
"AdsSyncDelDeviceNotificationReqEx",
"pAmsAddr",
"=",
"ctypes",
".",
"pointer",
"(",
"adr",
".",
"amsAddrStruct",
"(",
")",
")",
"nHNotification",
"=",
"ctypes",
".",
"c_ulong",
"(",
"notification_handle",
")",
"err_code",
"=",
"adsSyncDelDeviceNotificationReqFct",
"(",
"port",
",",
"pAmsAddr",
",",
"nHNotification",
")",
"callback_store",
".",
"pop",
"(",
"notification_handle",
",",
"None",
")",
"if",
"err_code",
":",
"raise",
"ADSError",
"(",
"err_code",
")",
"adsSyncWriteReqEx",
"(",
"port",
",",
"adr",
",",
"ADSIGRP_SYM_RELEASEHND",
",",
"0",
",",
"user_handle",
",",
"PLCTYPE_UDINT",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | adsSyncSetTimeoutEx | Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms | pyads/pyads_ex.py | def adsSyncSetTimeoutEx(port, nMs):
# type: (int, int) -> None
"""Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms
"""
adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx
cms = ctypes.c_long(nMs)
err_code = adsSyncSetTimeoutFct(port, cms)
if err_code:
raise ADSError(err_code) | def adsSyncSetTimeoutEx(port, nMs):
# type: (int, int) -> None
"""Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms
"""
adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx
cms = ctypes.c_long(nMs)
err_code = adsSyncSetTimeoutFct(port, cms)
if err_code:
raise ADSError(err_code) | [
"Set",
"Timeout",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L718-L730 | [
"def",
"adsSyncSetTimeoutEx",
"(",
"port",
",",
"nMs",
")",
":",
"# type: (int, int) -> None",
"adsSyncSetTimeoutFct",
"=",
"_adsDLL",
".",
"AdsSyncSetTimeoutEx",
"cms",
"=",
"ctypes",
".",
"c_long",
"(",
"nMs",
")",
"err_code",
"=",
"adsSyncSetTimeoutFct",
"(",
"port",
",",
"cms",
")",
"if",
"err_code",
":",
"raise",
"ADSError",
"(",
"err_code",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | _parse_ams_netid | Parse an AmsNetId from *str* to *SAmsNetId*.
:param str ams_netid: NetId as a string
:rtype: SAmsNetId
:return: NetId as a struct | pyads/ads.py | def _parse_ams_netid(ams_netid):
# type: (str) -> SAmsNetId
"""Parse an AmsNetId from *str* to *SAmsNetId*.
:param str ams_netid: NetId as a string
:rtype: SAmsNetId
:return: NetId as a struct
"""
try:
id_numbers = list(map(int, ams_netid.split(".")))
except ValueError:
raise ValueError("no valid netid")
if len(id_numbers) != 6:
raise ValueError("no valid netid")
# Fill the netId struct with data
ams_netid_st = SAmsNetId()
ams_netid_st.b = (c_ubyte * 6)(*id_numbers)
return ams_netid_st | def _parse_ams_netid(ams_netid):
# type: (str) -> SAmsNetId
"""Parse an AmsNetId from *str* to *SAmsNetId*.
:param str ams_netid: NetId as a string
:rtype: SAmsNetId
:return: NetId as a struct
"""
try:
id_numbers = list(map(int, ams_netid.split(".")))
except ValueError:
raise ValueError("no valid netid")
if len(id_numbers) != 6:
raise ValueError("no valid netid")
# Fill the netId struct with data
ams_netid_st = SAmsNetId()
ams_netid_st.b = (c_ubyte * 6)(*id_numbers)
return ams_netid_st | [
"Parse",
"an",
"AmsNetId",
"from",
"*",
"str",
"*",
"to",
"*",
"SAmsNetId",
"*",
".",
":",
"param",
"str",
"ams_netid",
":",
"NetId",
"as",
"a",
"string",
":",
"rtype",
":",
"SAmsNetId",
":",
"return",
":",
"NetId",
"as",
"a",
"struct"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L66-L86 | [
"def",
"_parse_ams_netid",
"(",
"ams_netid",
")",
":",
"# type: (str) -> SAmsNetId\r",
"try",
":",
"id_numbers",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"ams_netid",
".",
"split",
"(",
"\".\"",
")",
")",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"no valid netid\"",
")",
"if",
"len",
"(",
"id_numbers",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"\"no valid netid\"",
")",
"# Fill the netId struct with data\r",
"ams_netid_st",
"=",
"SAmsNetId",
"(",
")",
"ams_netid_st",
".",
"b",
"=",
"(",
"c_ubyte",
"*",
"6",
")",
"(",
"*",
"id_numbers",
")",
"return",
"ams_netid_st"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | set_local_address | Set the local NetID (**Linux only**).
:param str: new AmsNetID
:rtype: None
**Usage:**
>>> import pyads
>>> pyads.open_port()
>>> pyads.set_local_address('0.0.0.0.1.1') | pyads/ads.py | def set_local_address(ams_netid):
# type: (Union[str, SAmsNetId]) -> None
"""Set the local NetID (**Linux only**).
:param str: new AmsNetID
:rtype: None
**Usage:**
>>> import pyads
>>> pyads.open_port()
>>> pyads.set_local_address('0.0.0.0.1.1')
"""
if isinstance(ams_netid, str):
ams_netid_st = _parse_ams_netid(ams_netid)
else:
ams_netid_st = ams_netid
assert isinstance(ams_netid_st, SAmsNetId)
if linux:
return adsSetLocalAddress(ams_netid_st)
else:
raise ADSError(
text="SetLocalAddress is not supported for Windows clients."
) | def set_local_address(ams_netid):
# type: (Union[str, SAmsNetId]) -> None
"""Set the local NetID (**Linux only**).
:param str: new AmsNetID
:rtype: None
**Usage:**
>>> import pyads
>>> pyads.open_port()
>>> pyads.set_local_address('0.0.0.0.1.1')
"""
if isinstance(ams_netid, str):
ams_netid_st = _parse_ams_netid(ams_netid)
else:
ams_netid_st = ams_netid
assert isinstance(ams_netid_st, SAmsNetId)
if linux:
return adsSetLocalAddress(ams_netid_st)
else:
raise ADSError(
text="SetLocalAddress is not supported for Windows clients."
) | [
"Set",
"the",
"local",
"NetID",
"(",
"**",
"Linux",
"only",
"**",
")",
".",
":",
"param",
"str",
":",
"new",
"AmsNetID",
":",
"rtype",
":",
"None",
"**",
"Usage",
":",
"**",
">>>",
"import",
"pyads",
">>>",
"pyads",
".",
"open_port",
"()",
">>>",
"pyads",
".",
"set_local_address",
"(",
"0",
".",
"0",
".",
"0",
".",
"0",
".",
"1",
".",
"1",
")"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L126-L152 | [
"def",
"set_local_address",
"(",
"ams_netid",
")",
":",
"# type: (Union[str, SAmsNetId]) -> None\r",
"if",
"isinstance",
"(",
"ams_netid",
",",
"str",
")",
":",
"ams_netid_st",
"=",
"_parse_ams_netid",
"(",
"ams_netid",
")",
"else",
":",
"ams_netid_st",
"=",
"ams_netid",
"assert",
"isinstance",
"(",
"ams_netid_st",
",",
"SAmsNetId",
")",
"if",
"linux",
":",
"return",
"adsSetLocalAddress",
"(",
"ams_netid_st",
")",
"else",
":",
"raise",
"ADSError",
"(",
"text",
"=",
"\"SetLocalAddress is not supported for Windows clients.\"",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | write_control | Change the ADS state and the machine-state of the ADS-server.
:param AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is possible
to send additional data to the ADS-server. For current ADS-devices
additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices.
There is a difference between the device-state and the state of the
ADS-interface (AdsState). The possible states of an ADS-interface
are defined in the ADS-specification. | pyads/ads.py | def write_control(adr, ads_state, device_state, data, plc_datatype):
# type: (AmsAddr, int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is possible
to send additional data to the ADS-server. For current ADS-devices
additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices.
There is a difference between the device-state and the state of the
ADS-interface (AdsState). The possible states of an ADS-interface
are defined in the ADS-specification.
"""
if port is not None:
return adsSyncWriteControlReqEx(
port, adr, ads_state, device_state, data, plc_datatype
) | def write_control(adr, ads_state, device_state, data, plc_datatype):
# type: (AmsAddr, int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is possible
to send additional data to the ADS-server. For current ADS-devices
additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices.
There is a difference between the device-state and the state of the
ADS-interface (AdsState). The possible states of an ADS-interface
are defined in the ADS-specification.
"""
if port is not None:
return adsSyncWriteControlReqEx(
port, adr, ads_state, device_state, data, plc_datatype
) | [
"Change",
"the",
"ADS",
"state",
"and",
"the",
"machine",
"-",
"state",
"of",
"the",
"ADS",
"-",
"server",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"int",
"ads_state",
":",
"new",
"ADS",
"-",
"state",
"according",
"to",
"ADSTATE",
"constants",
":",
"param",
"int",
"device_state",
":",
"new",
"machine",
"-",
"state",
":",
"param",
"data",
":",
"additional",
"data",
":",
"param",
"int",
"plc_datatype",
":",
"datatype",
"according",
"to",
"PLCTYPE",
"constants",
":",
"note",
":",
"Despite",
"changing",
"the",
"ADS",
"-",
"state",
"and",
"the",
"machine",
"-",
"state",
"it",
"is",
"possible",
"to",
"send",
"additional",
"data",
"to",
"the",
"ADS",
"-",
"server",
".",
"For",
"current",
"ADS",
"-",
"devices",
"additional",
"data",
"is",
"not",
"progressed",
".",
"Every",
"ADS",
"-",
"device",
"is",
"able",
"to",
"communicate",
"its",
"current",
"state",
"to",
"other",
"devices",
".",
"There",
"is",
"a",
"difference",
"between",
"the",
"device",
"-",
"state",
"and",
"the",
"state",
"of",
"the",
"ADS",
"-",
"interface",
"(",
"AdsState",
")",
".",
"The",
"possible",
"states",
"of",
"an",
"ADS",
"-",
"interface",
"are",
"defined",
"in",
"the",
"ADS",
"-",
"specification",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L173-L196 | [
"def",
"write_control",
"(",
"adr",
",",
"ads_state",
",",
"device_state",
",",
"data",
",",
"plc_datatype",
")",
":",
"# type: (AmsAddr, int, int, Any, Type) -> None\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncWriteControlReqEx",
"(",
"port",
",",
"adr",
",",
"ads_state",
",",
"device_state",
",",
"data",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | write | Send data synchronous to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants | pyads/ads.py | def write(adr, index_group, index_offset, value, plc_datatype):
# type: (AmsAddr, int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if port is not None:
return adsSyncWriteReqEx(
port, adr, index_group, index_offset, value, plc_datatype
) | def write(adr, index_group, index_offset, value, plc_datatype):
# type: (AmsAddr, int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param Type plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if port is not None:
return adsSyncWriteReqEx(
port, adr, index_group, index_offset, value, plc_datatype
) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"Type",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L214-L230 | [
"def",
"write",
"(",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"value",
",",
"plc_datatype",
")",
":",
"# type: (AmsAddr, int, int, Any, Type) -> None\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncWriteReqEx",
"(",
"port",
",",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"value",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | read_write | Read and write data synchronous from/to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type plc_read_datatype: type of the data given to the PLC to respond
to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type plc_write_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: PLCTYPE
:return: value: **value** | pyads/ads.py | def read_write(
adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes=False,
):
# type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type plc_read_datatype: type of the data given to the PLC to respond
to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type plc_write_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: PLCTYPE
:return: value: **value**
"""
if port is not None:
return adsSyncReadWriteReqEx2(
port,
adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes,
)
return None | def read_write(
adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes=False,
):
# type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param Type plc_read_datatype: type of the data given to the PLC to respond
to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param Type plc_write_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:rtype: PLCTYPE
:return: value: **value**
"""
if port is not None:
return adsSyncReadWriteReqEx2(
port,
adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes,
)
return None | [
"Read",
"and",
"write",
"data",
"synchronous",
"from",
"/",
"to",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"Type",
"plc_read_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"to",
"respond",
"to",
"according",
"to",
"PLCTYPE",
"constants",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"Type",
"plc_write_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")",
":",
"rtype",
":",
"PLCTYPE",
":",
"return",
":",
"value",
":",
"**",
"value",
"**"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L233-L272 | [
"def",
"read_write",
"(",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_read_datatype",
",",
"value",
",",
"plc_write_datatype",
",",
"return_ctypes",
"=",
"False",
",",
")",
":",
"# type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncReadWriteReqEx2",
"(",
"port",
",",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_read_datatype",
",",
"value",
",",
"plc_write_datatype",
",",
"return_ctypes",
",",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | read | Read data synchronous from an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value** | pyads/ads.py | def read(adr, index_group, index_offset, plc_datatype, return_ctypes=False):
# type: (AmsAddr, int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if port is not None:
return adsSyncReadReqEx2(
port, adr, index_group, index_offset, plc_datatype, return_ctypes
)
return None | def read(adr, index_group, index_offset, plc_datatype, return_ctypes=False):
# type: (AmsAddr, int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param AmsAddr adr: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if port is not None:
return adsSyncReadReqEx2(
port, adr, index_group, index_offset, plc_datatype, return_ctypes
)
return None | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")",
":",
"return",
":",
"value",
":",
"**",
"value",
"**"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L275-L295 | [
"def",
"read",
"(",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_datatype",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (AmsAddr, int, int, Type, bool) -> Any\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncReadReqEx2",
"(",
"port",
",",
"adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_datatype",
",",
"return_ctypes",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | read_by_name | Read data synchronous from an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value** | pyads/ads.py | def read_by_name(adr, data_name, plc_datatype, return_ctypes=False):
# type: (AmsAddr, str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if port is not None:
return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)
return None | def read_by_name(adr, data_name, plc_datatype, return_ctypes=False):
# type: (AmsAddr, str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according to
PLCTYPE constants
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if port is not None:
return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)
return None | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"string",
"data_name",
":",
"data",
"name",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")",
":",
"return",
":",
"value",
":",
"**",
"value",
"**"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L298-L314 | [
"def",
"read_by_name",
"(",
"adr",
",",
"data_name",
",",
"plc_datatype",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (AmsAddr, str, Type, bool) -> Any\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncReadByNameEx",
"(",
"port",
",",
"adr",
",",
"data_name",
",",
"plc_datatype",
",",
"return_ctypes",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | write_by_name | Send data synchronous to an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants | pyads/ads.py | def write_by_name(adr, data_name, value, plc_datatype):
# type: (AmsAddr, str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if port is not None:
return adsSyncWriteByNameEx(port, adr, data_name, value, plc_datatype) | def write_by_name(adr, data_name, value, plc_datatype):
# type: (AmsAddr, str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param AmsAddr adr: local or remote AmsAddr
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if port is not None:
return adsSyncWriteByNameEx(port, adr, data_name, value, plc_datatype) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
".",
":",
"param",
"AmsAddr",
"adr",
":",
"local",
"or",
"remote",
"AmsAddr",
":",
"param",
"string",
"data_name",
":",
"PLC",
"storage",
"address",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L317-L329 | [
"def",
"write_by_name",
"(",
"adr",
",",
"data_name",
",",
"value",
",",
"plc_datatype",
")",
":",
"# type: (AmsAddr, str, Any, Type) -> None\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncWriteByNameEx",
"(",
"port",
",",
"adr",
",",
"data_name",
",",
"value",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | add_device_notification | Add a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code. | pyads/ads.py | def add_device_notification(adr, data_name, attr, callback, user_handle=None):
# type: (AmsAddr, str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]] # noqa: E501
"""Add a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code.
"""
if port is not None:
return adsSyncAddDeviceNotificationReqEx(
port, adr, data_name, attr, callback, user_handle
)
return None | def add_device_notification(adr, data_name, attr, callback, user_handle=None):
# type: (AmsAddr, str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]] # noqa: E501
"""Add a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code.
"""
if port is not None:
return adsSyncAddDeviceNotificationReqEx(
port, adr, data_name, attr, callback, user_handle
)
return None | [
"Add",
"a",
"device",
"notification",
".",
":",
"param",
"pyads",
".",
"structs",
".",
"AmsAddr",
"adr",
":",
"AMS",
"Address",
"associated",
"with",
"the",
"routing",
"entry",
"which",
"is",
"to",
"be",
"removed",
"from",
"the",
"router",
".",
":",
"param",
"str",
"data_name",
":",
"PLC",
"storage",
"address",
":",
"param",
"pyads",
".",
"structs",
".",
"NotificationAttrib",
"attr",
":",
"object",
"that",
"contains",
"all",
"the",
"attributes",
"for",
"the",
"definition",
"of",
"a",
"notification",
":",
"param",
"callback",
":",
"callback",
"function",
"that",
"gets",
"executed",
"on",
"in",
"the",
"event",
"of",
"a",
"notification",
":",
"rtype",
":",
"(",
"int",
"int",
")",
":",
"returns",
":",
"notification",
"handle",
"user",
"handle",
"Save",
"the",
"notification",
"handle",
"and",
"the",
"user",
"handle",
"on",
"creating",
"a",
"notification",
"if",
"you",
"want",
"to",
"be",
"able",
"to",
"remove",
"the",
"notification",
"later",
"in",
"your",
"code",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L352-L377 | [
"def",
"add_device_notification",
"(",
"adr",
",",
"data_name",
",",
"attr",
",",
"callback",
",",
"user_handle",
"=",
"None",
")",
":",
"# type: (AmsAddr, str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]] # noqa: E501\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncAddDeviceNotificationReqEx",
"(",
"port",
",",
"adr",
",",
"data_name",
",",
"attr",
",",
"callback",
",",
"user_handle",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | del_device_notification | Remove a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle | pyads/ads.py | def del_device_notification(adr, notification_handle, user_handle):
# type: (AmsAddr, int, int) -> None
"""Remove a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle
"""
if port is not None:
return adsSyncDelDeviceNotificationReqEx(
port, adr, notification_handle, user_handle
) | def del_device_notification(adr, notification_handle, user_handle):
# type: (AmsAddr, int, int) -> None
"""Remove a device notification.
:param pyads.structs.AmsAddr adr: AMS Address associated with the routing
entry which is to be removed from the router.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle
"""
if port is not None:
return adsSyncDelDeviceNotificationReqEx(
port, adr, notification_handle, user_handle
) | [
"Remove",
"a",
"device",
"notification",
".",
":",
"param",
"pyads",
".",
"structs",
".",
"AmsAddr",
"adr",
":",
"AMS",
"Address",
"associated",
"with",
"the",
"routing",
"entry",
"which",
"is",
"to",
"be",
"removed",
"from",
"the",
"router",
".",
":",
"param",
"notification_handle",
":",
"address",
"of",
"the",
"variable",
"that",
"contains",
"the",
"handle",
"of",
"the",
"notification",
":",
"param",
"user_handle",
":",
"user",
"handle"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L380-L394 | [
"def",
"del_device_notification",
"(",
"adr",
",",
"notification_handle",
",",
"user_handle",
")",
":",
"# type: (AmsAddr, int, int) -> None\r",
"if",
"port",
"is",
"not",
"None",
":",
"return",
"adsSyncDelDeviceNotificationReqEx",
"(",
"port",
",",
"adr",
",",
"notification_handle",
",",
"user_handle",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.open | Connect to the TwinCAT message router. | pyads/ads.py | def open(self):
# type: () -> None
"""Connect to the TwinCAT message router."""
if self._open:
return
self._port = adsPortOpenEx()
if linux:
adsAddRoute(self._adr.netIdStruct(), self.ip_address)
self._open = True | def open(self):
# type: () -> None
"""Connect to the TwinCAT message router."""
if self._open:
return
self._port = adsPortOpenEx()
if linux:
adsAddRoute(self._adr.netIdStruct(), self.ip_address)
self._open = True | [
"Connect",
"to",
"the",
"TwinCAT",
"message",
"router",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L438-L449 | [
"def",
"open",
"(",
"self",
")",
":",
"# type: () -> None\r",
"if",
"self",
".",
"_open",
":",
"return",
"self",
".",
"_port",
"=",
"adsPortOpenEx",
"(",
")",
"if",
"linux",
":",
"adsAddRoute",
"(",
"self",
".",
"_adr",
".",
"netIdStruct",
"(",
")",
",",
"self",
".",
"ip_address",
")",
"self",
".",
"_open",
"=",
"True"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.close | :summary: Close the connection to the TwinCAT message router. | pyads/ads.py | def close(self):
# type: () -> None
""":summary: Close the connection to the TwinCAT message router."""
if not self._open:
return
if linux:
adsDelRoute(self._adr.netIdStruct())
if self._port is not None:
adsPortCloseEx(self._port)
self._port = None
self._open = False | def close(self):
# type: () -> None
""":summary: Close the connection to the TwinCAT message router."""
if not self._open:
return
if linux:
adsDelRoute(self._adr.netIdStruct())
if self._port is not None:
adsPortCloseEx(self._port)
self._port = None
self._open = False | [
":",
"summary",
":",
"Close",
"the",
"connection",
"to",
"the",
"TwinCAT",
"message",
"router",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L451-L464 | [
"def",
"close",
"(",
"self",
")",
":",
"# type: () -> None\r",
"if",
"not",
"self",
".",
"_open",
":",
"return",
"if",
"linux",
":",
"adsDelRoute",
"(",
"self",
".",
"_adr",
".",
"netIdStruct",
"(",
")",
")",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"adsPortCloseEx",
"(",
"self",
".",
"_port",
")",
"self",
".",
"_port",
"=",
"None",
"self",
".",
"_open",
"=",
"False"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.write_control | Change the ADS state and the machine-state of the ADS-server.
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is
possible to send additional data to the ADS-server. For current
ADS-devices additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices. There is a difference between the device-state and the
state of the ADS-interface (AdsState). The possible states of an
ADS-interface are defined in the ADS-specification. | pyads/ads.py | def write_control(self, ads_state, device_state, data, plc_datatype):
# type: (int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is
possible to send additional data to the ADS-server. For current
ADS-devices additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices. There is a difference between the device-state and the
state of the ADS-interface (AdsState). The possible states of an
ADS-interface are defined in the ADS-specification.
"""
if self._port is not None:
return adsSyncWriteControlReqEx(
self._port, self._adr, ads_state, device_state, data, plc_datatype
) | def write_control(self, ads_state, device_state, data, plc_datatype):
# type: (int, int, Any, Type) -> None
"""Change the ADS state and the machine-state of the ADS-server.
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:param data: additional data
:param int plc_datatype: datatype, according to PLCTYPE constants
:note: Despite changing the ADS-state and the machine-state it is
possible to send additional data to the ADS-server. For current
ADS-devices additional data is not progressed.
Every ADS-device is able to communicate its current state to other
devices. There is a difference between the device-state and the
state of the ADS-interface (AdsState). The possible states of an
ADS-interface are defined in the ADS-specification.
"""
if self._port is not None:
return adsSyncWriteControlReqEx(
self._port, self._adr, ads_state, device_state, data, plc_datatype
) | [
"Change",
"the",
"ADS",
"state",
"and",
"the",
"machine",
"-",
"state",
"of",
"the",
"ADS",
"-",
"server",
".",
":",
"param",
"int",
"ads_state",
":",
"new",
"ADS",
"-",
"state",
"according",
"to",
"ADSTATE",
"constants",
":",
"param",
"int",
"device_state",
":",
"new",
"machine",
"-",
"state",
":",
"param",
"data",
":",
"additional",
"data",
":",
"param",
"int",
"plc_datatype",
":",
"datatype",
"according",
"to",
"PLCTYPE",
"constants",
":",
"note",
":",
"Despite",
"changing",
"the",
"ADS",
"-",
"state",
"and",
"the",
"machine",
"-",
"state",
"it",
"is",
"possible",
"to",
"send",
"additional",
"data",
"to",
"the",
"ADS",
"-",
"server",
".",
"For",
"current",
"ADS",
"-",
"devices",
"additional",
"data",
"is",
"not",
"progressed",
".",
"Every",
"ADS",
"-",
"device",
"is",
"able",
"to",
"communicate",
"its",
"current",
"state",
"to",
"other",
"devices",
".",
"There",
"is",
"a",
"difference",
"between",
"the",
"device",
"-",
"state",
"and",
"the",
"state",
"of",
"the",
"ADS",
"-",
"interface",
"(",
"AdsState",
")",
".",
"The",
"possible",
"states",
"of",
"an",
"ADS",
"-",
"interface",
"are",
"defined",
"in",
"the",
"ADS",
"-",
"specification",
"."
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L493-L514 | [
"def",
"write_control",
"(",
"self",
",",
"ads_state",
",",
"device_state",
",",
"data",
",",
"plc_datatype",
")",
":",
"# type: (int, int, Any, Type) -> None\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"return",
"adsSyncWriteControlReqEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"ads_state",
",",
"device_state",
",",
"data",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.write | Send data synchronous to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants | pyads/ads.py | def write(self, index_group, index_offset, value, plc_datatype):
# type: (int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if self._port is not None:
return adsSyncWriteReqEx(
self._port, self._adr, index_group, index_offset, value, plc_datatype
) | def write(self, index_group, index_offset, value, plc_datatype):
# type: (int, int, Any, Type) -> None
"""Send data synchronous to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if self._port is not None:
return adsSyncWriteReqEx(
self._port, self._adr, index_group, index_offset, value, plc_datatype
) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L529-L544 | [
"def",
"write",
"(",
"self",
",",
"index_group",
",",
"index_offset",
",",
"value",
",",
"plc_datatype",
")",
":",
"# type: (int, int, Any, Type) -> None\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"return",
"adsSyncWriteReqEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"index_group",
",",
"index_offset",
",",
"value",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.read_write | Read and write data synchronous from/to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_read_datatype: type of the data given to the PLC to
respond to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param plc_write_datatype: type of the data given to the PLC,
according to PLCTYPE constants
:rtype: PLCTYPE
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value** | pyads/ads.py | def read_write(
self,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes=False,
):
# type: (int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_read_datatype: type of the data given to the PLC to
respond to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param plc_write_datatype: type of the data given to the PLC,
according to PLCTYPE constants
:rtype: PLCTYPE
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if self._port is not None:
return adsSyncReadWriteReqEx2(
self._port,
self._adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes,
)
return None | def read_write(
self,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes=False,
):
# type: (int, int, Type, Any, Type, bool) -> Any
"""Read and write data synchronous from/to an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_read_datatype: type of the data given to the PLC to
respond to, according to PLCTYPE constants
:param value: value to write to the storage address of the PLC
:param plc_write_datatype: type of the data given to the PLC,
according to PLCTYPE constants
:rtype: PLCTYPE
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
:return: value: **value**
"""
if self._port is not None:
return adsSyncReadWriteReqEx2(
self._port,
self._adr,
index_group,
index_offset,
plc_read_datatype,
value,
plc_write_datatype,
return_ctypes,
)
return None | [
"Read",
"and",
"write",
"data",
"synchronous",
"from",
"/",
"to",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"int",
"plc_read_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"to",
"respond",
"to",
"according",
"to",
"PLCTYPE",
"constants",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"plc_write_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"rtype",
":",
"PLCTYPE",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")",
":",
"return",
":",
"value",
":",
"**",
"value",
"**"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L546-L584 | [
"def",
"read_write",
"(",
"self",
",",
"index_group",
",",
"index_offset",
",",
"plc_read_datatype",
",",
"value",
",",
"plc_write_datatype",
",",
"return_ctypes",
"=",
"False",
",",
")",
":",
"# type: (int, int, Type, Any, Type, bool) -> Any\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"return",
"adsSyncReadWriteReqEx2",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_read_datatype",
",",
"value",
",",
"plc_write_datatype",
",",
"return_ctypes",
",",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.read | Read data synchronous from an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False) | pyads/ads.py | def read(self, index_group, index_offset, plc_datatype, return_ctypes=False):
# type: (int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
"""
if self._port is not None:
return adsSyncReadReqEx2(
self._port, self._adr, index_group, index_offset, plc_datatype, return_ctypes
)
return None | def read(self, index_group, index_offset, plc_datatype, return_ctypes=False):
# type: (int, int, Type, bool) -> Any
"""Read data synchronous from an ADS-device.
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
"""
if self._port is not None:
return adsSyncReadReqEx2(
self._port, self._adr, index_group, index_offset, plc_datatype, return_ctypes
)
return None | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
".",
":",
"param",
"int",
"index_group",
":",
"PLC",
"storage",
"area",
"according",
"to",
"the",
"INDEXGROUP",
"constants",
":",
"param",
"int",
"index_offset",
":",
"PLC",
"storage",
"address",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"return",
":",
"value",
":",
"**",
"value",
"**",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L586-L605 | [
"def",
"read",
"(",
"self",
",",
"index_group",
",",
"index_offset",
",",
"plc_datatype",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (int, int, Type, bool) -> Any\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"return",
"adsSyncReadReqEx2",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"index_group",
",",
"index_offset",
",",
"plc_datatype",
",",
"return_ctypes",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.read_by_name | Read data synchronous from an ADS-device from data name.
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False) | pyads/ads.py | def read_by_name(self, data_name, plc_datatype, return_ctypes=False):
# type: (str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
"""
if self._port:
return adsSyncReadByNameEx(self._port, self._adr, data_name, plc_datatype, return_ctypes)
return None | def read_by_name(self, data_name, plc_datatype, return_ctypes=False):
# type: (str, Type, bool) -> Any
"""Read data synchronous from an ADS-device from data name.
:param string data_name: data name
:param int plc_datatype: type of the data given to the PLC, according
to PLCTYPE constants
:return: value: **value**
:param bool return_ctypes: return ctypes instead of python types if True
(default: False)
"""
if self._port:
return adsSyncReadByNameEx(self._port, self._adr, data_name, plc_datatype, return_ctypes)
return None | [
"Read",
"data",
"synchronous",
"from",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
".",
":",
"param",
"string",
"data_name",
":",
"data",
"name",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants",
":",
"return",
":",
"value",
":",
"**",
"value",
"**",
":",
"param",
"bool",
"return_ctypes",
":",
"return",
"ctypes",
"instead",
"of",
"python",
"types",
"if",
"True",
"(",
"default",
":",
"False",
")"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L607-L622 | [
"def",
"read_by_name",
"(",
"self",
",",
"data_name",
",",
"plc_datatype",
",",
"return_ctypes",
"=",
"False",
")",
":",
"# type: (str, Type, bool) -> Any\r",
"if",
"self",
".",
"_port",
":",
"return",
"adsSyncReadByNameEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"data_name",
",",
"plc_datatype",
",",
"return_ctypes",
")",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.write_by_name | Send data synchronous to an ADS-device from data name.
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants | pyads/ads.py | def write_by_name(self, data_name, value, plc_datatype):
# type: (str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if self._port:
return adsSyncWriteByNameEx(
self._port, self._adr, data_name, value, plc_datatype
) | def write_by_name(self, data_name, value, plc_datatype):
# type: (str, Any, Type) -> None
"""Send data synchronous to an ADS-device from data name.
:param string data_name: PLC storage address
:param value: value to write to the storage address of the PLC
:param int plc_datatype: type of the data given to the PLC,
according to PLCTYPE constants
"""
if self._port:
return adsSyncWriteByNameEx(
self._port, self._adr, data_name, value, plc_datatype
) | [
"Send",
"data",
"synchronous",
"to",
"an",
"ADS",
"-",
"device",
"from",
"data",
"name",
".",
":",
"param",
"string",
"data_name",
":",
"PLC",
"storage",
"address",
":",
"param",
"value",
":",
"value",
"to",
"write",
"to",
"the",
"storage",
"address",
"of",
"the",
"PLC",
":",
"param",
"int",
"plc_datatype",
":",
"type",
"of",
"the",
"data",
"given",
"to",
"the",
"PLC",
"according",
"to",
"PLCTYPE",
"constants"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L624-L637 | [
"def",
"write_by_name",
"(",
"self",
",",
"data_name",
",",
"value",
",",
"plc_datatype",
")",
":",
"# type: (str, Any, Type) -> None\r",
"if",
"self",
".",
"_port",
":",
"return",
"adsSyncWriteByNameEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"data_name",
",",
"value",
",",
"plc_datatype",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.add_device_notification | Add a device notification.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code.
**Usage**:
>>> import pyads
>>> from ctypes import size_of
>>>
>>> # Connect to the local TwinCAT PLC
>>> plc = pyads.Connection('127.0.0.1.1.1', 851)
>>>
>>> # Create callback function that prints the value
>>> def mycallback(adr, notification, user):
>>> contents = notification.contents
>>> value = next(
>>> map(int,
>>> bytearray(contents.data)[0:contents.cbSampleSize])
>>> )
>>> print(value)
>>>
>>> with plc:
>>> # Add notification with default settings
>>> attr = pyads.NotificationAttrib(size_of(pyads.PLCTYPE_INT))
>>>
>>> hnotification, huser = plc.add_device_notification(
>>> adr, attr, mycallback)
>>>
>>> # Remove notification
>>> plc.del_device_notification(hnotification, huser) | pyads/ads.py | def add_device_notification(self, data_name, attr, callback, user_handle=None):
# type: (str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]]
"""Add a device notification.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code.
**Usage**:
>>> import pyads
>>> from ctypes import size_of
>>>
>>> # Connect to the local TwinCAT PLC
>>> plc = pyads.Connection('127.0.0.1.1.1', 851)
>>>
>>> # Create callback function that prints the value
>>> def mycallback(adr, notification, user):
>>> contents = notification.contents
>>> value = next(
>>> map(int,
>>> bytearray(contents.data)[0:contents.cbSampleSize])
>>> )
>>> print(value)
>>>
>>> with plc:
>>> # Add notification with default settings
>>> attr = pyads.NotificationAttrib(size_of(pyads.PLCTYPE_INT))
>>>
>>> hnotification, huser = plc.add_device_notification(
>>> adr, attr, mycallback)
>>>
>>> # Remove notification
>>> plc.del_device_notification(hnotification, huser)
"""
if self._port is not None:
notification_handle, user_handle = adsSyncAddDeviceNotificationReqEx(
self._port, self._adr, data_name, attr, callback, user_handle
)
return notification_handle, user_handle
return None | def add_device_notification(self, data_name, attr, callback, user_handle=None):
# type: (str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]]
"""Add a device notification.
:param str data_name: PLC storage address
:param pyads.structs.NotificationAttrib attr: object that contains
all the attributes for the definition of a notification
:param callback: callback function that gets executed on in the event
of a notification
:rtype: (int, int)
:returns: notification handle, user handle
Save the notification handle and the user handle on creating a
notification if you want to be able to remove the notification
later in your code.
**Usage**:
>>> import pyads
>>> from ctypes import size_of
>>>
>>> # Connect to the local TwinCAT PLC
>>> plc = pyads.Connection('127.0.0.1.1.1', 851)
>>>
>>> # Create callback function that prints the value
>>> def mycallback(adr, notification, user):
>>> contents = notification.contents
>>> value = next(
>>> map(int,
>>> bytearray(contents.data)[0:contents.cbSampleSize])
>>> )
>>> print(value)
>>>
>>> with plc:
>>> # Add notification with default settings
>>> attr = pyads.NotificationAttrib(size_of(pyads.PLCTYPE_INT))
>>>
>>> hnotification, huser = plc.add_device_notification(
>>> adr, attr, mycallback)
>>>
>>> # Remove notification
>>> plc.del_device_notification(hnotification, huser)
"""
if self._port is not None:
notification_handle, user_handle = adsSyncAddDeviceNotificationReqEx(
self._port, self._adr, data_name, attr, callback, user_handle
)
return notification_handle, user_handle
return None | [
"Add",
"a",
"device",
"notification",
".",
":",
"param",
"str",
"data_name",
":",
"PLC",
"storage",
"address",
":",
"param",
"pyads",
".",
"structs",
".",
"NotificationAttrib",
"attr",
":",
"object",
"that",
"contains",
"all",
"the",
"attributes",
"for",
"the",
"definition",
"of",
"a",
"notification",
":",
"param",
"callback",
":",
"callback",
"function",
"that",
"gets",
"executed",
"on",
"in",
"the",
"event",
"of",
"a",
"notification",
":",
"rtype",
":",
"(",
"int",
"int",
")",
":",
"returns",
":",
"notification",
"handle",
"user",
"handle",
"Save",
"the",
"notification",
"handle",
"and",
"the",
"user",
"handle",
"on",
"creating",
"a",
"notification",
"if",
"you",
"want",
"to",
"be",
"able",
"to",
"remove",
"the",
"notification",
"later",
"in",
"your",
"code",
".",
"**",
"Usage",
"**",
":",
">>>",
"import",
"pyads",
">>>",
"from",
"ctypes",
"import",
"size_of",
">>>",
">>>",
"#",
"Connect",
"to",
"the",
"local",
"TwinCAT",
"PLC",
">>>",
"plc",
"=",
"pyads",
".",
"Connection",
"(",
"127",
".",
"0",
".",
"0",
".",
"1",
".",
"1",
".",
"1",
"851",
")",
">>>",
">>>",
"#",
"Create",
"callback",
"function",
"that",
"prints",
"the",
"value",
">>>",
"def",
"mycallback",
"(",
"adr",
"notification",
"user",
")",
":",
">>>",
"contents",
"=",
"notification",
".",
"contents",
">>>",
"value",
"=",
"next",
"(",
">>>",
"map",
"(",
"int",
">>>",
"bytearray",
"(",
"contents",
".",
"data",
")",
"[",
"0",
":",
"contents",
".",
"cbSampleSize",
"]",
")",
">>>",
")",
">>>",
"print",
"(",
"value",
")",
">>>",
">>>",
"with",
"plc",
":",
">>>",
"#",
"Add",
"notification",
"with",
"default",
"settings",
">>>",
"attr",
"=",
"pyads",
".",
"NotificationAttrib",
"(",
"size_of",
"(",
"pyads",
".",
"PLCTYPE_INT",
"))",
">>>",
">>>",
"hnotification",
"huser",
"=",
"plc",
".",
"add_device_notification",
"(",
">>>",
"adr",
"attr",
"mycallback",
")",
">>>",
">>>",
"#",
"Remove",
"notification",
">>>",
"plc",
".",
"del_device_notification",
"(",
"hnotification",
"huser",
")"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L639-L690 | [
"def",
"add_device_notification",
"(",
"self",
",",
"data_name",
",",
"attr",
",",
"callback",
",",
"user_handle",
"=",
"None",
")",
":",
"# type: (str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]]\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"notification_handle",
",",
"user_handle",
"=",
"adsSyncAddDeviceNotificationReqEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"data_name",
",",
"attr",
",",
"callback",
",",
"user_handle",
")",
"return",
"notification_handle",
",",
"user_handle",
"return",
"None"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.del_device_notification | Remove a device notification.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle | pyads/ads.py | def del_device_notification(self, notification_handle, user_handle):
# type: (int, int) -> None
"""Remove a device notification.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle
"""
if self._port is not None:
adsSyncDelDeviceNotificationReqEx(
self._port, self._adr, notification_handle, user_handle
) | def del_device_notification(self, notification_handle, user_handle):
# type: (int, int) -> None
"""Remove a device notification.
:param notification_handle: address of the variable that contains
the handle of the notification
:param user_handle: user handle
"""
if self._port is not None:
adsSyncDelDeviceNotificationReqEx(
self._port, self._adr, notification_handle, user_handle
) | [
"Remove",
"a",
"device",
"notification",
".",
":",
"param",
"notification_handle",
":",
"address",
"of",
"the",
"variable",
"that",
"contains",
"the",
"handle",
"of",
"the",
"notification",
":",
"param",
"user_handle",
":",
"user",
"handle"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L692-L704 | [
"def",
"del_device_notification",
"(",
"self",
",",
"notification_handle",
",",
"user_handle",
")",
":",
"# type: (int, int) -> None\r",
"if",
"self",
".",
"_port",
"is",
"not",
"None",
":",
"adsSyncDelDeviceNotificationReqEx",
"(",
"self",
".",
"_port",
",",
"self",
".",
"_adr",
",",
"notification_handle",
",",
"user_handle",
")"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | Connection.notification | Decorate a callback function.
**Decorator**.
A decorator that can be used for callback functions in order to
convert the data of the NotificationHeader into the fitting
Python type.
:param plc_datatype: The PLC datatype that needs to be converted. This can
be any basic PLC datatype or a `ctypes.Structure`.
The callback functions need to be of the following type:
>>> def callback(handle, name, timestamp, value)
* `handle`: the notification handle
* `name`: the variable name
* `timestamp`: the timestamp as datetime value
* `value`: the converted value of the variable
**Usage**:
>>> import pyads
>>>
>>> plc = pyads.Connection('172.18.3.25.1.1', 851)
>>>
>>>
>>> @plc.notification(pyads.PLCTYPE_STRING)
>>> def callback(handle, name, timestamp, value):
>>> print(handle, name, timestamp, value)
>>>
>>>
>>> with plc:
>>> attr = pyads.NotificationAttrib(20,
>>> pyads.ADSTRANS_SERVERCYCLE)
>>> handles = plc.add_device_notification('GVL.test', attr,
>>> callback)
>>> while True:
>>> pass | pyads/ads.py | def notification(self, plc_datatype=None):
# type: (Optional[Type[Any]]) -> Callable
"""Decorate a callback function.
**Decorator**.
A decorator that can be used for callback functions in order to
convert the data of the NotificationHeader into the fitting
Python type.
:param plc_datatype: The PLC datatype that needs to be converted. This can
be any basic PLC datatype or a `ctypes.Structure`.
The callback functions need to be of the following type:
>>> def callback(handle, name, timestamp, value)
* `handle`: the notification handle
* `name`: the variable name
* `timestamp`: the timestamp as datetime value
* `value`: the converted value of the variable
**Usage**:
>>> import pyads
>>>
>>> plc = pyads.Connection('172.18.3.25.1.1', 851)
>>>
>>>
>>> @plc.notification(pyads.PLCTYPE_STRING)
>>> def callback(handle, name, timestamp, value):
>>> print(handle, name, timestamp, value)
>>>
>>>
>>> with plc:
>>> attr = pyads.NotificationAttrib(20,
>>> pyads.ADSTRANS_SERVERCYCLE)
>>> handles = plc.add_device_notification('GVL.test', attr,
>>> callback)
>>> while True:
>>> pass
"""
def notification_decorator(func):
# type: (Callable[[int, str, datetime, Any], None]) -> Callable[[Any, str], None] # noqa: E501
def func_wrapper(notification, data_name):
# type: (Any, str) -> None
contents = notification.contents
data = contents.data
data_size = contents.cbSampleSize
datatype_map = {
PLCTYPE_BOOL: "<?",
PLCTYPE_BYTE: "<c",
PLCTYPE_DINT: "<i",
PLCTYPE_DWORD: "<I",
PLCTYPE_INT: "<h",
PLCTYPE_LREAL: "<d",
PLCTYPE_REAL: "<f",
PLCTYPE_SINT: "<b",
PLCTYPE_UDINT: "<L",
PLCTYPE_UINT: "<H",
PLCTYPE_USINT: "<B",
PLCTYPE_WORD: "<H",
} # type: Dict[Type, str]
if plc_datatype == PLCTYPE_STRING:
dest = (c_ubyte * data_size)()
memmove(addressof(dest), addressof(data), data_size)
# read only until null-termination character
value = bytearray(dest).split(b"\0", 1)[0].decode("utf-8")
elif issubclass(plc_datatype, Structure):
value = plc_datatype()
fit_size = min(data_size, sizeof(value))
memmove(addressof(value), addressof(data), fit_size)
elif plc_datatype not in datatype_map:
value = data
else:
value = struct.unpack(
datatype_map[plc_datatype], bytearray(data)[:data_size]
)[0]
dt = filetime_to_dt(contents.nTimeStamp)
return func(contents.hNotification, data_name, dt, value)
return func_wrapper
return notification_decorator | def notification(self, plc_datatype=None):
# type: (Optional[Type[Any]]) -> Callable
"""Decorate a callback function.
**Decorator**.
A decorator that can be used for callback functions in order to
convert the data of the NotificationHeader into the fitting
Python type.
:param plc_datatype: The PLC datatype that needs to be converted. This can
be any basic PLC datatype or a `ctypes.Structure`.
The callback functions need to be of the following type:
>>> def callback(handle, name, timestamp, value)
* `handle`: the notification handle
* `name`: the variable name
* `timestamp`: the timestamp as datetime value
* `value`: the converted value of the variable
**Usage**:
>>> import pyads
>>>
>>> plc = pyads.Connection('172.18.3.25.1.1', 851)
>>>
>>>
>>> @plc.notification(pyads.PLCTYPE_STRING)
>>> def callback(handle, name, timestamp, value):
>>> print(handle, name, timestamp, value)
>>>
>>>
>>> with plc:
>>> attr = pyads.NotificationAttrib(20,
>>> pyads.ADSTRANS_SERVERCYCLE)
>>> handles = plc.add_device_notification('GVL.test', attr,
>>> callback)
>>> while True:
>>> pass
"""
def notification_decorator(func):
# type: (Callable[[int, str, datetime, Any], None]) -> Callable[[Any, str], None] # noqa: E501
def func_wrapper(notification, data_name):
# type: (Any, str) -> None
contents = notification.contents
data = contents.data
data_size = contents.cbSampleSize
datatype_map = {
PLCTYPE_BOOL: "<?",
PLCTYPE_BYTE: "<c",
PLCTYPE_DINT: "<i",
PLCTYPE_DWORD: "<I",
PLCTYPE_INT: "<h",
PLCTYPE_LREAL: "<d",
PLCTYPE_REAL: "<f",
PLCTYPE_SINT: "<b",
PLCTYPE_UDINT: "<L",
PLCTYPE_UINT: "<H",
PLCTYPE_USINT: "<B",
PLCTYPE_WORD: "<H",
} # type: Dict[Type, str]
if plc_datatype == PLCTYPE_STRING:
dest = (c_ubyte * data_size)()
memmove(addressof(dest), addressof(data), data_size)
# read only until null-termination character
value = bytearray(dest).split(b"\0", 1)[0].decode("utf-8")
elif issubclass(plc_datatype, Structure):
value = plc_datatype()
fit_size = min(data_size, sizeof(value))
memmove(addressof(value), addressof(data), fit_size)
elif plc_datatype not in datatype_map:
value = data
else:
value = struct.unpack(
datatype_map[plc_datatype], bytearray(data)[:data_size]
)[0]
dt = filetime_to_dt(contents.nTimeStamp)
return func(contents.hNotification, data_name, dt, value)
return func_wrapper
return notification_decorator | [
"Decorate",
"a",
"callback",
"function",
".",
"**",
"Decorator",
"**",
".",
"A",
"decorator",
"that",
"can",
"be",
"used",
"for",
"callback",
"functions",
"in",
"order",
"to",
"convert",
"the",
"data",
"of",
"the",
"NotificationHeader",
"into",
"the",
"fitting",
"Python",
"type",
".",
":",
"param",
"plc_datatype",
":",
"The",
"PLC",
"datatype",
"that",
"needs",
"to",
"be",
"converted",
".",
"This",
"can",
"be",
"any",
"basic",
"PLC",
"datatype",
"or",
"a",
"ctypes",
".",
"Structure",
".",
"The",
"callback",
"functions",
"need",
"to",
"be",
"of",
"the",
"following",
"type",
":",
">>>",
"def",
"callback",
"(",
"handle",
"name",
"timestamp",
"value",
")",
"*",
"handle",
":",
"the",
"notification",
"handle",
"*",
"name",
":",
"the",
"variable",
"name",
"*",
"timestamp",
":",
"the",
"timestamp",
"as",
"datetime",
"value",
"*",
"value",
":",
"the",
"converted",
"value",
"of",
"the",
"variable",
"**",
"Usage",
"**",
":",
">>>",
"import",
"pyads",
">>>",
">>>",
"plc",
"=",
"pyads",
".",
"Connection",
"(",
"172",
".",
"18",
".",
"3",
".",
"25",
".",
"1",
".",
"1",
"851",
")",
">>>",
">>>",
">>>"
] | stlehmann/pyads | python | https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/ads.py#L722-L815 | [
"def",
"notification",
"(",
"self",
",",
"plc_datatype",
"=",
"None",
")",
":",
"# type: (Optional[Type[Any]]) -> Callable\r",
"def",
"notification_decorator",
"(",
"func",
")",
":",
"# type: (Callable[[int, str, datetime, Any], None]) -> Callable[[Any, str], None] # noqa: E501\r",
"def",
"func_wrapper",
"(",
"notification",
",",
"data_name",
")",
":",
"# type: (Any, str) -> None\r",
"contents",
"=",
"notification",
".",
"contents",
"data",
"=",
"contents",
".",
"data",
"data_size",
"=",
"contents",
".",
"cbSampleSize",
"datatype_map",
"=",
"{",
"PLCTYPE_BOOL",
":",
"\"<?\"",
",",
"PLCTYPE_BYTE",
":",
"\"<c\"",
",",
"PLCTYPE_DINT",
":",
"\"<i\"",
",",
"PLCTYPE_DWORD",
":",
"\"<I\"",
",",
"PLCTYPE_INT",
":",
"\"<h\"",
",",
"PLCTYPE_LREAL",
":",
"\"<d\"",
",",
"PLCTYPE_REAL",
":",
"\"<f\"",
",",
"PLCTYPE_SINT",
":",
"\"<b\"",
",",
"PLCTYPE_UDINT",
":",
"\"<L\"",
",",
"PLCTYPE_UINT",
":",
"\"<H\"",
",",
"PLCTYPE_USINT",
":",
"\"<B\"",
",",
"PLCTYPE_WORD",
":",
"\"<H\"",
",",
"}",
"# type: Dict[Type, str]\r",
"if",
"plc_datatype",
"==",
"PLCTYPE_STRING",
":",
"dest",
"=",
"(",
"c_ubyte",
"*",
"data_size",
")",
"(",
")",
"memmove",
"(",
"addressof",
"(",
"dest",
")",
",",
"addressof",
"(",
"data",
")",
",",
"data_size",
")",
"# read only until null-termination character\r",
"value",
"=",
"bytearray",
"(",
"dest",
")",
".",
"split",
"(",
"b\"\\0\"",
",",
"1",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"\"utf-8\"",
")",
"elif",
"issubclass",
"(",
"plc_datatype",
",",
"Structure",
")",
":",
"value",
"=",
"plc_datatype",
"(",
")",
"fit_size",
"=",
"min",
"(",
"data_size",
",",
"sizeof",
"(",
"value",
")",
")",
"memmove",
"(",
"addressof",
"(",
"value",
")",
",",
"addressof",
"(",
"data",
")",
",",
"fit_size",
")",
"elif",
"plc_datatype",
"not",
"in",
"datatype_map",
":",
"value",
"=",
"data",
"else",
":",
"value",
"=",
"struct",
".",
"unpack",
"(",
"datatype_map",
"[",
"plc_datatype",
"]",
",",
"bytearray",
"(",
"data",
")",
"[",
":",
"data_size",
"]",
")",
"[",
"0",
"]",
"dt",
"=",
"filetime_to_dt",
"(",
"contents",
".",
"nTimeStamp",
")",
"return",
"func",
"(",
"contents",
".",
"hNotification",
",",
"data_name",
",",
"dt",
",",
"value",
")",
"return",
"func_wrapper",
"return",
"notification_decorator"
] | 44bd84394db2785332ac44b2948373916bea0f02 |
valid | xml_extract_text | :param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted text | serenata_toolbox/datasets/helpers.py | def xml_extract_text(node, xpath):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted text
"""
text = node.find(xpath).text
if text is not None:
text = text.strip()
return text | def xml_extract_text(node, xpath):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted text
"""
text = node.find(xpath).text
if text is not None:
text = text.strip()
return text | [
":",
"param",
"node",
":",
"the",
"node",
"to",
"be",
"queried",
":",
"param",
"xpath",
":",
"the",
"path",
"to",
"fetch",
"the",
"child",
"node",
"that",
"has",
"the",
"wanted",
"text"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/datasets/helpers.py#L14-L22 | [
"def",
"xml_extract_text",
"(",
"node",
",",
"xpath",
")",
":",
"text",
"=",
"node",
".",
"find",
"(",
"xpath",
")",
".",
"text",
"if",
"text",
"is",
"not",
"None",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"return",
"text"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | xml_extract_date | :param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted date | serenata_toolbox/datasets/helpers.py | def xml_extract_date(node, xpath, date_format='%d/%m/%Y'):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted date
"""
return datetime.strptime(xml_extract_text(node, xpath), date_format) | def xml_extract_date(node, xpath, date_format='%d/%m/%Y'):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted date
"""
return datetime.strptime(xml_extract_text(node, xpath), date_format) | [
":",
"param",
"node",
":",
"the",
"node",
"to",
"be",
"queried",
":",
"param",
"xpath",
":",
"the",
"path",
"to",
"fetch",
"the",
"child",
"node",
"that",
"has",
"the",
"wanted",
"date"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/datasets/helpers.py#L25-L30 | [
"def",
"xml_extract_date",
"(",
"node",
",",
"xpath",
",",
"date_format",
"=",
"'%d/%m/%Y'",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"xml_extract_text",
"(",
"node",
",",
"xpath",
")",
",",
"date_format",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | xml_extract_datetime | :param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted datetime | serenata_toolbox/datasets/helpers.py | def xml_extract_datetime(node, xpath, datetime_format='%d/%m/%Y %H:%M:%S'):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted datetime
"""
return datetime.strptime(xml_extract_text(node, xpath), datetime_format) | def xml_extract_datetime(node, xpath, datetime_format='%d/%m/%Y %H:%M:%S'):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted datetime
"""
return datetime.strptime(xml_extract_text(node, xpath), datetime_format) | [
":",
"param",
"node",
":",
"the",
"node",
"to",
"be",
"queried",
":",
"param",
"xpath",
":",
"the",
"path",
"to",
"fetch",
"the",
"child",
"node",
"that",
"has",
"the",
"wanted",
"datetime"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/datasets/helpers.py#L33-L38 | [
"def",
"xml_extract_datetime",
"(",
"node",
",",
"xpath",
",",
"datetime_format",
"=",
"'%d/%m/%Y %H:%M:%S'",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"xml_extract_text",
"(",
"node",
",",
"xpath",
")",
",",
"datetime_format",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | translate_column | :param df: (pandas.Dataframe) the dataframe to be translated
:param column: (str) the column to be translated
:param translations: (dict) a dictionary of the strings to be categorized and translated | serenata_toolbox/datasets/helpers.py | def translate_column(df, column, translations):
"""
:param df: (pandas.Dataframe) the dataframe to be translated
:param column: (str) the column to be translated
:param translations: (dict) a dictionary of the strings to be categorized and translated
"""
df[column] = df[column].astype('category')
translations = [translations[cat]
for cat in df[column].cat.categories]
df[column].cat.rename_categories(translations, inplace=True) | def translate_column(df, column, translations):
"""
:param df: (pandas.Dataframe) the dataframe to be translated
:param column: (str) the column to be translated
:param translations: (dict) a dictionary of the strings to be categorized and translated
"""
df[column] = df[column].astype('category')
translations = [translations[cat]
for cat in df[column].cat.categories]
df[column].cat.rename_categories(translations, inplace=True) | [
":",
"param",
"df",
":",
"(",
"pandas",
".",
"Dataframe",
")",
"the",
"dataframe",
"to",
"be",
"translated",
":",
"param",
"column",
":",
"(",
"str",
")",
"the",
"column",
"to",
"be",
"translated",
":",
"param",
"translations",
":",
"(",
"dict",
")",
"a",
"dictionary",
"of",
"the",
"strings",
"to",
"be",
"categorized",
"and",
"translated"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/datasets/helpers.py#L43-L52 | [
"def",
"translate_column",
"(",
"df",
",",
"column",
",",
"translations",
")",
":",
"df",
"[",
"column",
"]",
"=",
"df",
"[",
"column",
"]",
".",
"astype",
"(",
"'category'",
")",
"translations",
"=",
"[",
"translations",
"[",
"cat",
"]",
"for",
"cat",
"in",
"df",
"[",
"column",
"]",
".",
"cat",
".",
"categories",
"]",
"df",
"[",
"column",
"]",
".",
"cat",
".",
"rename_categories",
"(",
"translations",
",",
"inplace",
"=",
"True",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | fetch_speeches | :param data_dir: (str) directory in which the output file will be saved
:param range_start: (str) date in the format dd/mm/yyyy
:param range_end: (str) date in the format dd/mm/yyyy | serenata_toolbox/chamber_of_deputies/speeches_dataset.py | def fetch_speeches(data_dir, range_start, range_end):
"""
:param data_dir: (str) directory in which the output file will be saved
:param range_start: (str) date in the format dd/mm/yyyy
:param range_end: (str) date in the format dd/mm/yyyy
"""
speeches = SpeechesDataset()
df = speeches.fetch(range_start, range_end)
save_to_csv(df, data_dir, "speeches")
return df | def fetch_speeches(data_dir, range_start, range_end):
"""
:param data_dir: (str) directory in which the output file will be saved
:param range_start: (str) date in the format dd/mm/yyyy
:param range_end: (str) date in the format dd/mm/yyyy
"""
speeches = SpeechesDataset()
df = speeches.fetch(range_start, range_end)
save_to_csv(df, data_dir, "speeches")
return df | [
":",
"param",
"data_dir",
":",
"(",
"str",
")",
"directory",
"in",
"which",
"the",
"output",
"file",
"will",
"be",
"saved",
":",
"param",
"range_start",
":",
"(",
"str",
")",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy",
":",
"param",
"range_end",
":",
"(",
"str",
")",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/speeches_dataset.py#L99-L108 | [
"def",
"fetch_speeches",
"(",
"data_dir",
",",
"range_start",
",",
"range_end",
")",
":",
"speeches",
"=",
"SpeechesDataset",
"(",
")",
"df",
"=",
"speeches",
".",
"fetch",
"(",
"range_start",
",",
"range_end",
")",
"save_to_csv",
"(",
"df",
",",
"data_dir",
",",
"\"speeches\"",
")",
"return",
"df"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | SpeechesDataset.fetch | Fetches speeches from the ListarDiscursosPlenario endpoint of the
SessoesReunioes (SessionsReunions) API.
The date range provided should be specified as a string using the
format supported by the API (%d/%m/%Y) | serenata_toolbox/chamber_of_deputies/speeches_dataset.py | def fetch(self, range_start, range_end):
"""
Fetches speeches from the ListarDiscursosPlenario endpoint of the
SessoesReunioes (SessionsReunions) API.
The date range provided should be specified as a string using the
format supported by the API (%d/%m/%Y)
"""
range_dates = {'dataIni': range_start, 'dataFim': range_end}
url = self.URL.format(**range_dates)
xml = urllib.request.urlopen(url)
tree = ET.ElementTree(file=xml)
records = self._parse_speeches(tree.getroot())
return pd.DataFrame(records, columns=[
'session_code',
'session_date',
'session_num',
'phase_code',
'phase_desc',
'speech_speaker_num',
'speech_speaker_name',
'speech_speaker_party',
'speech_speaker_state',
'speech_started_at',
'speech_room_num',
'speech_insertion_num'
]) | def fetch(self, range_start, range_end):
"""
Fetches speeches from the ListarDiscursosPlenario endpoint of the
SessoesReunioes (SessionsReunions) API.
The date range provided should be specified as a string using the
format supported by the API (%d/%m/%Y)
"""
range_dates = {'dataIni': range_start, 'dataFim': range_end}
url = self.URL.format(**range_dates)
xml = urllib.request.urlopen(url)
tree = ET.ElementTree(file=xml)
records = self._parse_speeches(tree.getroot())
return pd.DataFrame(records, columns=[
'session_code',
'session_date',
'session_num',
'phase_code',
'phase_desc',
'speech_speaker_num',
'speech_speaker_name',
'speech_speaker_party',
'speech_speaker_state',
'speech_started_at',
'speech_room_num',
'speech_insertion_num'
]) | [
"Fetches",
"speeches",
"from",
"the",
"ListarDiscursosPlenario",
"endpoint",
"of",
"the",
"SessoesReunioes",
"(",
"SessionsReunions",
")",
"API",
"."
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/speeches_dataset.py#L24-L52 | [
"def",
"fetch",
"(",
"self",
",",
"range_start",
",",
"range_end",
")",
":",
"range_dates",
"=",
"{",
"'dataIni'",
":",
"range_start",
",",
"'dataFim'",
":",
"range_end",
"}",
"url",
"=",
"self",
".",
"URL",
".",
"format",
"(",
"*",
"*",
"range_dates",
")",
"xml",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"tree",
"=",
"ET",
".",
"ElementTree",
"(",
"file",
"=",
"xml",
")",
"records",
"=",
"self",
".",
"_parse_speeches",
"(",
"tree",
".",
"getroot",
"(",
")",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"[",
"'session_code'",
",",
"'session_date'",
",",
"'session_num'",
",",
"'phase_code'",
",",
"'phase_desc'",
",",
"'speech_speaker_num'",
",",
"'speech_speaker_name'",
",",
"'speech_speaker_party'",
",",
"'speech_speaker_state'",
",",
"'speech_started_at'",
",",
"'speech_room_num'",
",",
"'speech_insertion_num'",
"]",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | fetch_presences | :param data_dir: (str) directory in which the output file will be saved
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) a date in the format dd/mm/yyyy
:param date_end: (str) a date in the format dd/mm/yyyy | serenata_toolbox/chamber_of_deputies/presences_dataset.py | def fetch_presences(data_dir, deputies, date_start, date_end):
"""
:param data_dir: (str) directory in which the output file will be saved
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) a date in the format dd/mm/yyyy
:param date_end: (str) a date in the format dd/mm/yyyy
"""
presences = PresencesDataset()
df = presences.fetch(deputies, date_start, date_end)
save_to_csv(df, data_dir, "presences")
log.info("Presence records:", len(df))
log.info("Records of deputies present on a session:", len(df[df.presence == 'Present']))
log.info("Records of deputies absent from a session:", len(df[df.presence == 'Absent']))
return df | def fetch_presences(data_dir, deputies, date_start, date_end):
"""
:param data_dir: (str) directory in which the output file will be saved
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) a date in the format dd/mm/yyyy
:param date_end: (str) a date in the format dd/mm/yyyy
"""
presences = PresencesDataset()
df = presences.fetch(deputies, date_start, date_end)
save_to_csv(df, data_dir, "presences")
log.info("Presence records:", len(df))
log.info("Records of deputies present on a session:", len(df[df.presence == 'Present']))
log.info("Records of deputies absent from a session:", len(df[df.presence == 'Absent']))
return df | [
":",
"param",
"data_dir",
":",
"(",
"str",
")",
"directory",
"in",
"which",
"the",
"output",
"file",
"will",
"be",
"saved",
":",
"param",
"deputies",
":",
"(",
"pandas",
".",
"DataFrame",
")",
"a",
"dataframe",
"with",
"deputies",
"data",
":",
"param",
"date_start",
":",
"(",
"str",
")",
"a",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy",
":",
"param",
"date_end",
":",
"(",
"str",
")",
"a",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/presences_dataset.py#L161-L176 | [
"def",
"fetch_presences",
"(",
"data_dir",
",",
"deputies",
",",
"date_start",
",",
"date_end",
")",
":",
"presences",
"=",
"PresencesDataset",
"(",
")",
"df",
"=",
"presences",
".",
"fetch",
"(",
"deputies",
",",
"date_start",
",",
"date_end",
")",
"save_to_csv",
"(",
"df",
",",
"data_dir",
",",
"\"presences\"",
")",
"log",
".",
"info",
"(",
"\"Presence records:\"",
",",
"len",
"(",
"df",
")",
")",
"log",
".",
"info",
"(",
"\"Records of deputies present on a session:\"",
",",
"len",
"(",
"df",
"[",
"df",
".",
"presence",
"==",
"'Present'",
"]",
")",
")",
"log",
".",
"info",
"(",
"\"Records of deputies absent from a session:\"",
",",
"len",
"(",
"df",
"[",
"df",
".",
"presence",
"==",
"'Absent'",
"]",
")",
")",
"return",
"df"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | PresencesDataset.fetch | :param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) date in the format dd/mm/yyyy
:param date_end: (str) date in the format dd/mm/yyyy | serenata_toolbox/chamber_of_deputies/presences_dataset.py | def fetch(self, deputies, start_date, end_date):
"""
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) date in the format dd/mm/yyyy
:param date_end: (str) date in the format dd/mm/yyyy
"""
log.debug("Fetching data for {} deputies from {} -> {}".format(len(deputies), start_date, end_date))
records = self._all_presences(deputies, start_date, end_date)
df = pd.DataFrame(records, columns=(
'term',
'congressperson_document',
'congressperson_name',
'party',
'state',
'date',
'present_on_day',
'justification',
'session',
'presence'
))
return self._translate(df) | def fetch(self, deputies, start_date, end_date):
"""
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) date in the format dd/mm/yyyy
:param date_end: (str) date in the format dd/mm/yyyy
"""
log.debug("Fetching data for {} deputies from {} -> {}".format(len(deputies), start_date, end_date))
records = self._all_presences(deputies, start_date, end_date)
df = pd.DataFrame(records, columns=(
'term',
'congressperson_document',
'congressperson_name',
'party',
'state',
'date',
'present_on_day',
'justification',
'session',
'presence'
))
return self._translate(df) | [
":",
"param",
"deputies",
":",
"(",
"pandas",
".",
"DataFrame",
")",
"a",
"dataframe",
"with",
"deputies",
"data",
":",
"param",
"date_start",
":",
"(",
"str",
")",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy",
":",
"param",
"date_end",
":",
"(",
"str",
")",
"date",
"in",
"the",
"format",
"dd",
"/",
"mm",
"/",
"yyyy"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/presences_dataset.py#L33-L55 | [
"def",
"fetch",
"(",
"self",
",",
"deputies",
",",
"start_date",
",",
"end_date",
")",
":",
"log",
".",
"debug",
"(",
"\"Fetching data for {} deputies from {} -> {}\"",
".",
"format",
"(",
"len",
"(",
"deputies",
")",
",",
"start_date",
",",
"end_date",
")",
")",
"records",
"=",
"self",
".",
"_all_presences",
"(",
"deputies",
",",
"start_date",
",",
"end_date",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"(",
"'term'",
",",
"'congressperson_document'",
",",
"'congressperson_name'",
",",
"'party'",
",",
"'state'",
",",
"'date'",
",",
"'present_on_day'",
",",
"'justification'",
",",
"'session'",
",",
"'presence'",
")",
")",
"return",
"self",
".",
"_translate",
"(",
"df",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | fetch_official_missions | :param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped | serenata_toolbox/chamber_of_deputies/official_missions_dataset.py | def fetch_official_missions(data_dir, start_date, end_date):
"""
:param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped
"""
official_missions = OfficialMissionsDataset()
df = official_missions.fetch(start_date, end_date)
save_to_csv(df, data_dir, "official-missions")
return df | def fetch_official_missions(data_dir, start_date, end_date):
"""
:param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped
"""
official_missions = OfficialMissionsDataset()
df = official_missions.fetch(start_date, end_date)
save_to_csv(df, data_dir, "official-missions")
return df | [
":",
"param",
"data_dir",
":",
"(",
"str",
")",
"directory",
"in",
"which",
"the",
"output",
"file",
"will",
"be",
"saved",
":",
"param",
"start_date",
":",
"(",
"datetime",
")",
"first",
"date",
"of",
"the",
"range",
"to",
"be",
"scraped",
":",
"param",
"end_date",
":",
"(",
"datetime",
")",
"last",
"date",
"of",
"the",
"range",
"to",
"be",
"scraped"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/official_missions_dataset.py#L119-L129 | [
"def",
"fetch_official_missions",
"(",
"data_dir",
",",
"start_date",
",",
"end_date",
")",
":",
"official_missions",
"=",
"OfficialMissionsDataset",
"(",
")",
"df",
"=",
"official_missions",
".",
"fetch",
"(",
"start_date",
",",
"end_date",
")",
"save_to_csv",
"(",
"df",
",",
"data_dir",
",",
"\"official-missions\"",
")",
"return",
"df"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | OfficialMissionsDataset.fetch | Fetches official missions within the given date range | serenata_toolbox/chamber_of_deputies/official_missions_dataset.py | def fetch(self, start_date, end_date):
"""
Fetches official missions within the given date range
"""
records = []
for two_months_range in self._generate_ranges(start_date, end_date):
log.debug(two_months_range)
for record in self._fetch_missions_for_range(two_months_range[0], two_months_range[1]):
records.append(record)
df = pd.DataFrame(records, columns=[
'participant',
'destination',
'subject',
'start',
'end',
'canceled',
'report_status',
'report_details_link'
])
translate_column(df, 'report_status', {
'DisponΓvel': 'Available',
'Pendente': 'Pending',
'Em anΓ‘lise': 'Analysing',
'NΓ£o se aplica': 'Does not apply'
})
translate_column(df, 'canceled', {
'NΓ£o': 'No',
'Sim': 'Yes'
})
return df.drop_duplicates() | def fetch(self, start_date, end_date):
"""
Fetches official missions within the given date range
"""
records = []
for two_months_range in self._generate_ranges(start_date, end_date):
log.debug(two_months_range)
for record in self._fetch_missions_for_range(two_months_range[0], two_months_range[1]):
records.append(record)
df = pd.DataFrame(records, columns=[
'participant',
'destination',
'subject',
'start',
'end',
'canceled',
'report_status',
'report_details_link'
])
translate_column(df, 'report_status', {
'DisponΓvel': 'Available',
'Pendente': 'Pending',
'Em anΓ‘lise': 'Analysing',
'NΓ£o se aplica': 'Does not apply'
})
translate_column(df, 'canceled', {
'NΓ£o': 'No',
'Sim': 'Yes'
})
return df.drop_duplicates() | [
"Fetches",
"official",
"missions",
"within",
"the",
"given",
"date",
"range"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/official_missions_dataset.py#L28-L61 | [
"def",
"fetch",
"(",
"self",
",",
"start_date",
",",
"end_date",
")",
":",
"records",
"=",
"[",
"]",
"for",
"two_months_range",
"in",
"self",
".",
"_generate_ranges",
"(",
"start_date",
",",
"end_date",
")",
":",
"log",
".",
"debug",
"(",
"two_months_range",
")",
"for",
"record",
"in",
"self",
".",
"_fetch_missions_for_range",
"(",
"two_months_range",
"[",
"0",
"]",
",",
"two_months_range",
"[",
"1",
"]",
")",
":",
"records",
".",
"append",
"(",
"record",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"[",
"'participant'",
",",
"'destination'",
",",
"'subject'",
",",
"'start'",
",",
"'end'",
",",
"'canceled'",
",",
"'report_status'",
",",
"'report_details_link'",
"]",
")",
"translate_column",
"(",
"df",
",",
"'report_status'",
",",
"{",
"'DisponΓvel':",
" ",
"Available',",
"",
"'Pendente'",
":",
"'Pending'",
",",
"'Em anΓ‘lise':",
" ",
"Analysing',",
"",
"'NΓ£o se aplica':",
" ",
"Does not apply'",
"}",
")",
"translate_column",
"(",
"df",
",",
"'canceled'",
",",
"{",
"'NΓ£o':",
" ",
"No',",
"",
"'Sim'",
":",
"'Yes'",
"}",
")",
"return",
"df",
".",
"drop_duplicates",
"(",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | OfficialMissionsDataset._generate_ranges | Generate a list of 2 month ranges for the range requested with an
intersection between months. This is necessary because we can't search
for ranges longer than 3 months and the period searched has to encompass
the whole period of the mission. | serenata_toolbox/chamber_of_deputies/official_missions_dataset.py | def _generate_ranges(start_date, end_date):
"""
Generate a list of 2 month ranges for the range requested with an
intersection between months. This is necessary because we can't search
for ranges longer than 3 months and the period searched has to encompass
the whole period of the mission.
"""
range_start = start_date
while range_start < end_date:
range_end = range_start + timedelta(days=60)
yield (
range_start.strftime("%d/%m/%Y"),
range_end.strftime("%d/%m/%Y")
)
range_start += timedelta(days=30) | def _generate_ranges(start_date, end_date):
"""
Generate a list of 2 month ranges for the range requested with an
intersection between months. This is necessary because we can't search
for ranges longer than 3 months and the period searched has to encompass
the whole period of the mission.
"""
range_start = start_date
while range_start < end_date:
range_end = range_start + timedelta(days=60)
yield (
range_start.strftime("%d/%m/%Y"),
range_end.strftime("%d/%m/%Y")
)
range_start += timedelta(days=30) | [
"Generate",
"a",
"list",
"of",
"2",
"month",
"ranges",
"for",
"the",
"range",
"requested",
"with",
"an",
"intersection",
"between",
"months",
".",
"This",
"is",
"necessary",
"because",
"we",
"can",
"t",
"search",
"for",
"ranges",
"longer",
"than",
"3",
"months",
"and",
"the",
"period",
"searched",
"has",
"to",
"encompass",
"the",
"whole",
"period",
"of",
"the",
"mission",
"."
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/official_missions_dataset.py#L64-L78 | [
"def",
"_generate_ranges",
"(",
"start_date",
",",
"end_date",
")",
":",
"range_start",
"=",
"start_date",
"while",
"range_start",
"<",
"end_date",
":",
"range_end",
"=",
"range_start",
"+",
"timedelta",
"(",
"days",
"=",
"60",
")",
"yield",
"(",
"range_start",
".",
"strftime",
"(",
"\"%d/%m/%Y\"",
")",
",",
"range_end",
".",
"strftime",
"(",
"\"%d/%m/%Y\"",
")",
")",
"range_start",
"+=",
"timedelta",
"(",
"days",
"=",
"30",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | fetch_session_start_times | :param data_dir: (str) directory in which the output file will be saved
:param pivot: (int) congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for | serenata_toolbox/chamber_of_deputies/session_start_times_dataset.py | def fetch_session_start_times(data_dir, pivot, session_dates):
"""
:param data_dir: (str) directory in which the output file will be saved
:param pivot: (int) congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for
"""
session_start_times = SessionStartTimesDataset()
df = session_start_times.fetch(pivot, session_dates)
save_to_csv(df, data_dir, "session-start-times")
log.info("Dates requested:", len(session_dates))
found = pd.to_datetime(df['date'], format="%Y-%m-%d %H:%M:%S").dt.date.unique()
log.info("Dates found:", len(found))
return df | def fetch_session_start_times(data_dir, pivot, session_dates):
"""
:param data_dir: (str) directory in which the output file will be saved
:param pivot: (int) congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for
"""
session_start_times = SessionStartTimesDataset()
df = session_start_times.fetch(pivot, session_dates)
save_to_csv(df, data_dir, "session-start-times")
log.info("Dates requested:", len(session_dates))
found = pd.to_datetime(df['date'], format="%Y-%m-%d %H:%M:%S").dt.date.unique()
log.info("Dates found:", len(found))
return df | [
":",
"param",
"data_dir",
":",
"(",
"str",
")",
"directory",
"in",
"which",
"the",
"output",
"file",
"will",
"be",
"saved",
":",
"param",
"pivot",
":",
"(",
"int",
")",
"congressperson",
"document",
"to",
"use",
"as",
"a",
"pivot",
"for",
"scraping",
"the",
"data",
":",
"param",
"session_dates",
":",
"(",
"list",
")",
"datetime",
"objects",
"to",
"fetch",
"the",
"start",
"times",
"for"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/session_start_times_dataset.py#L49-L62 | [
"def",
"fetch_session_start_times",
"(",
"data_dir",
",",
"pivot",
",",
"session_dates",
")",
":",
"session_start_times",
"=",
"SessionStartTimesDataset",
"(",
")",
"df",
"=",
"session_start_times",
".",
"fetch",
"(",
"pivot",
",",
"session_dates",
")",
"save_to_csv",
"(",
"df",
",",
"data_dir",
",",
"\"session-start-times\"",
")",
"log",
".",
"info",
"(",
"\"Dates requested:\"",
",",
"len",
"(",
"session_dates",
")",
")",
"found",
"=",
"pd",
".",
"to_datetime",
"(",
"df",
"[",
"'date'",
"]",
",",
"format",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
".",
"dt",
".",
"date",
".",
"unique",
"(",
")",
"log",
".",
"info",
"(",
"\"Dates found:\"",
",",
"len",
"(",
"found",
")",
")",
"return",
"df"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | SessionStartTimesDataset.fetch | :param pivot: (int) a congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for | serenata_toolbox/chamber_of_deputies/session_start_times_dataset.py | def fetch(self, pivot, session_dates):
"""
:param pivot: (int) a congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for
"""
records = self._all_start_times(pivot, session_dates)
return pd.DataFrame(records, columns=(
'date',
'session',
'started_at'
)) | def fetch(self, pivot, session_dates):
"""
:param pivot: (int) a congressperson document to use as a pivot for scraping the data
:param session_dates: (list) datetime objects to fetch the start times for
"""
records = self._all_start_times(pivot, session_dates)
return pd.DataFrame(records, columns=(
'date',
'session',
'started_at'
)) | [
":",
"param",
"pivot",
":",
"(",
"int",
")",
"a",
"congressperson",
"document",
"to",
"use",
"as",
"a",
"pivot",
"for",
"scraping",
"the",
"data",
":",
"param",
"session_dates",
":",
"(",
"list",
")",
"datetime",
"objects",
"to",
"fetch",
"the",
"start",
"times",
"for"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/session_start_times_dataset.py#L23-L34 | [
"def",
"fetch",
"(",
"self",
",",
"pivot",
",",
"session_dates",
")",
":",
"records",
"=",
"self",
".",
"_all_start_times",
"(",
"pivot",
",",
"session_dates",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"(",
"'date'",
",",
"'session'",
",",
"'started_at'",
")",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | fetch_deputies | :param data_dir: (str) directory in which the output file will be saved | serenata_toolbox/chamber_of_deputies/deputies_dataset.py | def fetch_deputies(data_dir):
"""
:param data_dir: (str) directory in which the output file will be saved
"""
deputies = DeputiesDataset()
df = deputies.fetch()
save_to_csv(df, data_dir, "deputies")
holders = df.condition == 'Holder'
substitutes = df.condition == 'Substitute'
log.info("Total deputies:", len(df))
log.info("Holder deputies:", len(df[holders]))
log.info("Substitute deputies:", len(df[substitutes]))
return df | def fetch_deputies(data_dir):
"""
:param data_dir: (str) directory in which the output file will be saved
"""
deputies = DeputiesDataset()
df = deputies.fetch()
save_to_csv(df, data_dir, "deputies")
holders = df.condition == 'Holder'
substitutes = df.condition == 'Substitute'
log.info("Total deputies:", len(df))
log.info("Holder deputies:", len(df[holders]))
log.info("Substitute deputies:", len(df[substitutes]))
return df | [
":",
"param",
"data_dir",
":",
"(",
"str",
")",
"directory",
"in",
"which",
"the",
"output",
"file",
"will",
"be",
"saved"
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/deputies_dataset.py#L76-L89 | [
"def",
"fetch_deputies",
"(",
"data_dir",
")",
":",
"deputies",
"=",
"DeputiesDataset",
"(",
")",
"df",
"=",
"deputies",
".",
"fetch",
"(",
")",
"save_to_csv",
"(",
"df",
",",
"data_dir",
",",
"\"deputies\"",
")",
"holders",
"=",
"df",
".",
"condition",
"==",
"'Holder'",
"substitutes",
"=",
"df",
".",
"condition",
"==",
"'Substitute'",
"log",
".",
"info",
"(",
"\"Total deputies:\"",
",",
"len",
"(",
"df",
")",
")",
"log",
".",
"info",
"(",
"\"Holder deputies:\"",
",",
"len",
"(",
"df",
"[",
"holders",
"]",
")",
")",
"log",
".",
"info",
"(",
"\"Substitute deputies:\"",
",",
"len",
"(",
"df",
"[",
"substitutes",
"]",
")",
")",
"return",
"df"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | DeputiesDataset.fetch | Fetches the list of deputies for the current term. | serenata_toolbox/chamber_of_deputies/deputies_dataset.py | def fetch(self):
"""
Fetches the list of deputies for the current term.
"""
xml = urllib.request.urlopen(self.URL)
tree = ET.ElementTree(file=xml)
records = self._parse_deputies(tree.getroot())
df = pd.DataFrame(records, columns=(
'congressperson_id',
'budget_id',
'condition',
'congressperson_document',
'civil_name',
'congressperson_name',
'picture_url',
'gender',
'state',
'party',
'phone_number',
'email'
))
return self._translate(df) | def fetch(self):
"""
Fetches the list of deputies for the current term.
"""
xml = urllib.request.urlopen(self.URL)
tree = ET.ElementTree(file=xml)
records = self._parse_deputies(tree.getroot())
df = pd.DataFrame(records, columns=(
'congressperson_id',
'budget_id',
'condition',
'congressperson_document',
'civil_name',
'congressperson_name',
'picture_url',
'gender',
'state',
'party',
'phone_number',
'email'
))
return self._translate(df) | [
"Fetches",
"the",
"list",
"of",
"deputies",
"for",
"the",
"current",
"term",
"."
] | okfn-brasil/serenata-toolbox | python | https://github.com/okfn-brasil/serenata-toolbox/blob/47b14725e8ed3a53fb52190a2ba5f29182a16959/serenata_toolbox/chamber_of_deputies/deputies_dataset.py#L18-L41 | [
"def",
"fetch",
"(",
"self",
")",
":",
"xml",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"self",
".",
"URL",
")",
"tree",
"=",
"ET",
".",
"ElementTree",
"(",
"file",
"=",
"xml",
")",
"records",
"=",
"self",
".",
"_parse_deputies",
"(",
"tree",
".",
"getroot",
"(",
")",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"records",
",",
"columns",
"=",
"(",
"'congressperson_id'",
",",
"'budget_id'",
",",
"'condition'",
",",
"'congressperson_document'",
",",
"'civil_name'",
",",
"'congressperson_name'",
",",
"'picture_url'",
",",
"'gender'",
",",
"'state'",
",",
"'party'",
",",
"'phone_number'",
",",
"'email'",
")",
")",
"return",
"self",
".",
"_translate",
"(",
"df",
")"
] | 47b14725e8ed3a53fb52190a2ba5f29182a16959 |
valid | HashRing.add_node | Adds a `node` to the hash ring (including a number of replicas). | redis_shard/hashring.py | def add_node(self, node):
"""Adds a `node` to the hash ring (including a number of replicas).
"""
self.nodes.append(node)
for x in xrange(self.replicas):
ring_key = self.hash_method(b("%s:%d" % (node, x)))
self.ring[ring_key] = node
self.sorted_keys.append(ring_key)
self.sorted_keys.sort() | def add_node(self, node):
"""Adds a `node` to the hash ring (including a number of replicas).
"""
self.nodes.append(node)
for x in xrange(self.replicas):
ring_key = self.hash_method(b("%s:%d" % (node, x)))
self.ring[ring_key] = node
self.sorted_keys.append(ring_key)
self.sorted_keys.sort() | [
"Adds",
"a",
"node",
"to",
"the",
"hash",
"ring",
"(",
"including",
"a",
"number",
"of",
"replicas",
")",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/hashring.py#L45-L54 | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"nodes",
".",
"append",
"(",
"node",
")",
"for",
"x",
"in",
"xrange",
"(",
"self",
".",
"replicas",
")",
":",
"ring_key",
"=",
"self",
".",
"hash_method",
"(",
"b",
"(",
"\"%s:%d\"",
"%",
"(",
"node",
",",
"x",
")",
")",
")",
"self",
".",
"ring",
"[",
"ring_key",
"]",
"=",
"node",
"self",
".",
"sorted_keys",
".",
"append",
"(",
"ring_key",
")",
"self",
".",
"sorted_keys",
".",
"sort",
"(",
")"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | HashRing.remove_node | Removes `node` from the hash ring and its replicas. | redis_shard/hashring.py | def remove_node(self, node):
"""Removes `node` from the hash ring and its replicas.
"""
self.nodes.remove(node)
for x in xrange(self.replicas):
ring_key = self.hash_method(b("%s:%d" % (node, x)))
self.ring.pop(ring_key)
self.sorted_keys.remove(ring_key) | def remove_node(self, node):
"""Removes `node` from the hash ring and its replicas.
"""
self.nodes.remove(node)
for x in xrange(self.replicas):
ring_key = self.hash_method(b("%s:%d" % (node, x)))
self.ring.pop(ring_key)
self.sorted_keys.remove(ring_key) | [
"Removes",
"node",
"from",
"the",
"hash",
"ring",
"and",
"its",
"replicas",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/hashring.py#L56-L63 | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"nodes",
".",
"remove",
"(",
"node",
")",
"for",
"x",
"in",
"xrange",
"(",
"self",
".",
"replicas",
")",
":",
"ring_key",
"=",
"self",
".",
"hash_method",
"(",
"b",
"(",
"\"%s:%d\"",
"%",
"(",
"node",
",",
"x",
")",
")",
")",
"self",
".",
"ring",
".",
"pop",
"(",
"ring_key",
")",
"self",
".",
"sorted_keys",
".",
"remove",
"(",
"ring_key",
")"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | HashRing.get_node_pos | Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring.
If the hash ring is empty, (`None`, `None`) is returned. | redis_shard/hashring.py | def get_node_pos(self, key):
"""Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring.
If the hash ring is empty, (`None`, `None`) is returned.
"""
if len(self.ring) == 0:
return [None, None]
crc = self.hash_method(b(key))
idx = bisect.bisect(self.sorted_keys, crc)
# prevents out of range index
idx = min(idx, (self.replicas * len(self.nodes)) - 1)
return [self.ring[self.sorted_keys[idx]], idx] | def get_node_pos(self, key):
"""Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring.
If the hash ring is empty, (`None`, `None`) is returned.
"""
if len(self.ring) == 0:
return [None, None]
crc = self.hash_method(b(key))
idx = bisect.bisect(self.sorted_keys, crc)
# prevents out of range index
idx = min(idx, (self.replicas * len(self.nodes)) - 1)
return [self.ring[self.sorted_keys[idx]], idx] | [
"Given",
"a",
"string",
"key",
"a",
"corresponding",
"node",
"in",
"the",
"hash",
"ring",
"is",
"returned",
"along",
"with",
"it",
"s",
"position",
"in",
"the",
"ring",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/hashring.py#L73-L85 | [
"def",
"get_node_pos",
"(",
"self",
",",
"key",
")",
":",
"if",
"len",
"(",
"self",
".",
"ring",
")",
"==",
"0",
":",
"return",
"[",
"None",
",",
"None",
"]",
"crc",
"=",
"self",
".",
"hash_method",
"(",
"b",
"(",
"key",
")",
")",
"idx",
"=",
"bisect",
".",
"bisect",
"(",
"self",
".",
"sorted_keys",
",",
"crc",
")",
"# prevents out of range index",
"idx",
"=",
"min",
"(",
"idx",
",",
"(",
"self",
".",
"replicas",
"*",
"len",
"(",
"self",
".",
"nodes",
")",
")",
"-",
"1",
")",
"return",
"[",
"self",
".",
"ring",
"[",
"self",
".",
"sorted_keys",
"[",
"idx",
"]",
"]",
",",
"idx",
"]"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | HashRing.iter_nodes | Given a string key it returns the nodes as a generator that can hold the key. | redis_shard/hashring.py | def iter_nodes(self, key):
"""Given a string key it returns the nodes as a generator that can hold the key.
"""
if len(self.ring) == 0:
yield None, None
node, pos = self.get_node_pos(key)
for k in self.sorted_keys[pos:]:
yield k, self.ring[k] | def iter_nodes(self, key):
"""Given a string key it returns the nodes as a generator that can hold the key.
"""
if len(self.ring) == 0:
yield None, None
node, pos = self.get_node_pos(key)
for k in self.sorted_keys[pos:]:
yield k, self.ring[k] | [
"Given",
"a",
"string",
"key",
"it",
"returns",
"the",
"nodes",
"as",
"a",
"generator",
"that",
"can",
"hold",
"the",
"key",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/hashring.py#L87-L94 | [
"def",
"iter_nodes",
"(",
"self",
",",
"key",
")",
":",
"if",
"len",
"(",
"self",
".",
"ring",
")",
"==",
"0",
":",
"yield",
"None",
",",
"None",
"node",
",",
"pos",
"=",
"self",
".",
"get_node_pos",
"(",
"key",
")",
"for",
"k",
"in",
"self",
".",
"sorted_keys",
"[",
"pos",
":",
"]",
":",
"yield",
"k",
",",
"self",
".",
"ring",
"[",
"k",
"]"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | format_servers | :param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','port':12000,'db':0},
]
- url_schema
servers = ['redis://127.0.0.1:10000/0?name=node1',
'redis://127.0.0.1:11000/0?name=node2',
'redis://127.0.0.1:12000/0?name=node3'
] | redis_shard/helpers.py | def format_servers(servers):
"""
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','port':12000,'db':0},
]
- url_schema
servers = ['redis://127.0.0.1:10000/0?name=node1',
'redis://127.0.0.1:11000/0?name=node2',
'redis://127.0.0.1:12000/0?name=node3'
]
"""
configs = []
if not isinstance(servers, list):
raise ValueError("server's config must be list")
_type = type(servers[0])
if _type == dict:
return servers
if (sys.version_info[0] == 3 and _type in [str, bytes]) \
or (sys.version_info[0] == 2 and _type in [str, unicode]):
for config in servers:
configs.append(parse_url(config))
else:
raise ValueError("invalid server config")
return configs | def format_servers(servers):
"""
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','port':12000,'db':0},
]
- url_schema
servers = ['redis://127.0.0.1:10000/0?name=node1',
'redis://127.0.0.1:11000/0?name=node2',
'redis://127.0.0.1:12000/0?name=node3'
]
"""
configs = []
if not isinstance(servers, list):
raise ValueError("server's config must be list")
_type = type(servers[0])
if _type == dict:
return servers
if (sys.version_info[0] == 3 and _type in [str, bytes]) \
or (sys.version_info[0] == 2 and _type in [str, unicode]):
for config in servers:
configs.append(parse_url(config))
else:
raise ValueError("invalid server config")
return configs | [
":",
"param",
"servers",
":",
"server",
"list",
"element",
"in",
"it",
"can",
"have",
"two",
"kinds",
"of",
"format",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/helpers.py#L7-L40 | [
"def",
"format_servers",
"(",
"servers",
")",
":",
"configs",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"servers",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"server's config must be list\"",
")",
"_type",
"=",
"type",
"(",
"servers",
"[",
"0",
"]",
")",
"if",
"_type",
"==",
"dict",
":",
"return",
"servers",
"if",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
"and",
"_type",
"in",
"[",
"str",
",",
"bytes",
"]",
")",
"or",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
"and",
"_type",
"in",
"[",
"str",
",",
"unicode",
"]",
")",
":",
"for",
"config",
"in",
"servers",
":",
"configs",
".",
"append",
"(",
"parse_url",
"(",
"config",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"invalid server config\"",
")",
"return",
"configs"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | RedisShardAPI.mget | Returns a list of values ordered identically to ``keys`` | redis_shard/shard.py | def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
args = list_or_args(keys, args)
server_keys = {}
ret_dict = {}
for key in args:
server_name = self.get_server_name(key)
server_keys[server_name] = server_keys.get(server_name, [])
server_keys[server_name].append(key)
for server_name, sub_keys in iteritems(server_keys):
values = self.connections[server_name].mget(sub_keys)
ret_dict.update(dict(zip(sub_keys, values)))
result = []
for key in args:
result.append(ret_dict.get(key, None))
return result | def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
args = list_or_args(keys, args)
server_keys = {}
ret_dict = {}
for key in args:
server_name = self.get_server_name(key)
server_keys[server_name] = server_keys.get(server_name, [])
server_keys[server_name].append(key)
for server_name, sub_keys in iteritems(server_keys):
values = self.connections[server_name].mget(sub_keys)
ret_dict.update(dict(zip(sub_keys, values)))
result = []
for key in args:
result.append(ret_dict.get(key, None))
return result | [
"Returns",
"a",
"list",
"of",
"values",
"ordered",
"identically",
"to",
"keys"
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/shard.py#L140-L157 | [
"def",
"mget",
"(",
"self",
",",
"keys",
",",
"*",
"args",
")",
":",
"args",
"=",
"list_or_args",
"(",
"keys",
",",
"args",
")",
"server_keys",
"=",
"{",
"}",
"ret_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"args",
":",
"server_name",
"=",
"self",
".",
"get_server_name",
"(",
"key",
")",
"server_keys",
"[",
"server_name",
"]",
"=",
"server_keys",
".",
"get",
"(",
"server_name",
",",
"[",
"]",
")",
"server_keys",
"[",
"server_name",
"]",
".",
"append",
"(",
"key",
")",
"for",
"server_name",
",",
"sub_keys",
"in",
"iteritems",
"(",
"server_keys",
")",
":",
"values",
"=",
"self",
".",
"connections",
"[",
"server_name",
"]",
".",
"mget",
"(",
"sub_keys",
")",
"ret_dict",
".",
"update",
"(",
"dict",
"(",
"zip",
"(",
"sub_keys",
",",
"values",
")",
")",
")",
"result",
"=",
"[",
"]",
"for",
"key",
"in",
"args",
":",
"result",
".",
"append",
"(",
"ret_dict",
".",
"get",
"(",
"key",
",",
"None",
")",
")",
"return",
"result"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | RedisShardAPI.mset | Sets each key in the ``mapping`` dict to its corresponding value | redis_shard/shard.py | def mset(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value
"""
servers = {}
for key, value in mapping.items():
server_name = self.get_server_name(key)
servers.setdefault(server_name, [])
servers[server_name].append((key, value))
for name, items in servers.items():
self.connections[name].mset(dict(items))
return True | def mset(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value
"""
servers = {}
for key, value in mapping.items():
server_name = self.get_server_name(key)
servers.setdefault(server_name, [])
servers[server_name].append((key, value))
for name, items in servers.items():
self.connections[name].mset(dict(items))
return True | [
"Sets",
"each",
"key",
"in",
"the",
"mapping",
"dict",
"to",
"its",
"corresponding",
"value"
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/shard.py#L159-L170 | [
"def",
"mset",
"(",
"self",
",",
"mapping",
")",
":",
"servers",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"server_name",
"=",
"self",
".",
"get_server_name",
"(",
"key",
")",
"servers",
".",
"setdefault",
"(",
"server_name",
",",
"[",
"]",
")",
"servers",
"[",
"server_name",
"]",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"for",
"name",
",",
"items",
"in",
"servers",
".",
"items",
"(",
")",
":",
"self",
".",
"connections",
"[",
"name",
"]",
".",
"mset",
"(",
"dict",
"(",
"items",
")",
")",
"return",
"True"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | RedisShardAPI.lock | Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock. | redis_shard/shard.py | def lock(self, name, timeout=None, sleep=0.1):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
"""
return Lock(self, name, timeout=timeout, sleep=sleep) | def lock(self, name, timeout=None, sleep=0.1):
"""
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.
"""
return Lock(self, name, timeout=timeout, sleep=sleep) | [
"Return",
"a",
"new",
"Lock",
"object",
"using",
"key",
"name",
"that",
"mimics",
"the",
"behavior",
"of",
"threading",
".",
"Lock",
"."
] | zhihu/redis-shard | python | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/shard.py#L177-L189 | [
"def",
"lock",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"None",
",",
"sleep",
"=",
"0.1",
")",
":",
"return",
"Lock",
"(",
"self",
",",
"name",
",",
"timeout",
"=",
"timeout",
",",
"sleep",
"=",
"sleep",
")"
] | 57c166ef7d55f7272b50efc1dedc1f6ed4691137 |
valid | parse_line | Return a language-server diagnostic from a line of the Mypy error report;
optionally, use the whole document to provide more context on it. | pyls_mypy/plugin.py | def parse_line(line, document=None):
'''
Return a language-server diagnostic from a line of the Mypy error report;
optionally, use the whole document to provide more context on it.
'''
result = re.match(line_pattern, line)
if result:
_, lineno, offset, severity, msg = result.groups()
lineno = int(lineno or 1)
offset = int(offset or 0)
errno = 2
if severity == 'error':
errno = 1
diag = {
'source': 'mypy',
'range': {
'start': {'line': lineno - 1, 'character': offset},
# There may be a better solution, but mypy does not provide end
'end': {'line': lineno - 1, 'character': offset + 1}
},
'message': msg,
'severity': errno
}
if document:
# although mypy does not provide the end of the affected range, we
# can make a good guess by highlighting the word that Mypy flagged
word = document.word_at_position(diag['range']['start'])
if word:
diag['range']['end']['character'] = (
diag['range']['start']['character'] + len(word))
return diag | def parse_line(line, document=None):
'''
Return a language-server diagnostic from a line of the Mypy error report;
optionally, use the whole document to provide more context on it.
'''
result = re.match(line_pattern, line)
if result:
_, lineno, offset, severity, msg = result.groups()
lineno = int(lineno or 1)
offset = int(offset or 0)
errno = 2
if severity == 'error':
errno = 1
diag = {
'source': 'mypy',
'range': {
'start': {'line': lineno - 1, 'character': offset},
# There may be a better solution, but mypy does not provide end
'end': {'line': lineno - 1, 'character': offset + 1}
},
'message': msg,
'severity': errno
}
if document:
# although mypy does not provide the end of the affected range, we
# can make a good guess by highlighting the word that Mypy flagged
word = document.word_at_position(diag['range']['start'])
if word:
diag['range']['end']['character'] = (
diag['range']['start']['character'] + len(word))
return diag | [
"Return",
"a",
"language",
"-",
"server",
"diagnostic",
"from",
"a",
"line",
"of",
"the",
"Mypy",
"error",
"report",
";",
"optionally",
"use",
"the",
"whole",
"document",
"to",
"provide",
"more",
"context",
"on",
"it",
"."
] | tomv564/pyls-mypy | python | https://github.com/tomv564/pyls-mypy/blob/e488270437ae444865fdf590ddec8943efbf2332/pyls_mypy/plugin.py#L8-L39 | [
"def",
"parse_line",
"(",
"line",
",",
"document",
"=",
"None",
")",
":",
"result",
"=",
"re",
".",
"match",
"(",
"line_pattern",
",",
"line",
")",
"if",
"result",
":",
"_",
",",
"lineno",
",",
"offset",
",",
"severity",
",",
"msg",
"=",
"result",
".",
"groups",
"(",
")",
"lineno",
"=",
"int",
"(",
"lineno",
"or",
"1",
")",
"offset",
"=",
"int",
"(",
"offset",
"or",
"0",
")",
"errno",
"=",
"2",
"if",
"severity",
"==",
"'error'",
":",
"errno",
"=",
"1",
"diag",
"=",
"{",
"'source'",
":",
"'mypy'",
",",
"'range'",
":",
"{",
"'start'",
":",
"{",
"'line'",
":",
"lineno",
"-",
"1",
",",
"'character'",
":",
"offset",
"}",
",",
"# There may be a better solution, but mypy does not provide end",
"'end'",
":",
"{",
"'line'",
":",
"lineno",
"-",
"1",
",",
"'character'",
":",
"offset",
"+",
"1",
"}",
"}",
",",
"'message'",
":",
"msg",
",",
"'severity'",
":",
"errno",
"}",
"if",
"document",
":",
"# although mypy does not provide the end of the affected range, we",
"# can make a good guess by highlighting the word that Mypy flagged",
"word",
"=",
"document",
".",
"word_at_position",
"(",
"diag",
"[",
"'range'",
"]",
"[",
"'start'",
"]",
")",
"if",
"word",
":",
"diag",
"[",
"'range'",
"]",
"[",
"'end'",
"]",
"[",
"'character'",
"]",
"=",
"(",
"diag",
"[",
"'range'",
"]",
"[",
"'start'",
"]",
"[",
"'character'",
"]",
"+",
"len",
"(",
"word",
")",
")",
"return",
"diag"
] | e488270437ae444865fdf590ddec8943efbf2332 |
valid | WebSocket.connect | Establishes a connection to the Lavalink server. | lavalink/WebSocket.py | async def connect(self):
""" Establishes a connection to the Lavalink server. """
await self._lavalink.bot.wait_until_ready()
if self._ws and self._ws.open:
log.debug('WebSocket still open, closing...')
await self._ws.close()
user_id = self._lavalink.bot.user.id
shard_count = self._lavalink.bot.shard_count or self._shards
headers = {
'Authorization': self._password,
'Num-Shards': shard_count,
'User-Id': str(user_id)
}
log.debug('Preparing to connect to Lavalink')
log.debug(' with URI: {}'.format(self._uri))
log.debug(' with headers: {}'.format(str(headers)))
log.info('Connecting to Lavalink...')
try:
self._ws = await websockets.connect(self._uri, loop=self._loop, extra_headers=headers)
except OSError as error:
log.exception('Failed to connect to Lavalink: {}'.format(str(error)))
else:
log.info('Connected to Lavalink!')
self._loop.create_task(self.listen())
version = self._ws.response_headers.get('Lavalink-Major-Version', 2)
try:
self._lavalink._server_version = int(version)
except ValueError:
self._lavalink._server_version = 2
log.info('Lavalink server version is {}'.format(version))
if self._queue:
log.info('Replaying {} queued events...'.format(len(self._queue)))
for task in self._queue:
await self.send(**task) | async def connect(self):
""" Establishes a connection to the Lavalink server. """
await self._lavalink.bot.wait_until_ready()
if self._ws and self._ws.open:
log.debug('WebSocket still open, closing...')
await self._ws.close()
user_id = self._lavalink.bot.user.id
shard_count = self._lavalink.bot.shard_count or self._shards
headers = {
'Authorization': self._password,
'Num-Shards': shard_count,
'User-Id': str(user_id)
}
log.debug('Preparing to connect to Lavalink')
log.debug(' with URI: {}'.format(self._uri))
log.debug(' with headers: {}'.format(str(headers)))
log.info('Connecting to Lavalink...')
try:
self._ws = await websockets.connect(self._uri, loop=self._loop, extra_headers=headers)
except OSError as error:
log.exception('Failed to connect to Lavalink: {}'.format(str(error)))
else:
log.info('Connected to Lavalink!')
self._loop.create_task(self.listen())
version = self._ws.response_headers.get('Lavalink-Major-Version', 2)
try:
self._lavalink._server_version = int(version)
except ValueError:
self._lavalink._server_version = 2
log.info('Lavalink server version is {}'.format(version))
if self._queue:
log.info('Replaying {} queued events...'.format(len(self._queue)))
for task in self._queue:
await self.send(**task) | [
"Establishes",
"a",
"connection",
"to",
"the",
"Lavalink",
"server",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L36-L73 | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"await",
"self",
".",
"_lavalink",
".",
"bot",
".",
"wait_until_ready",
"(",
")",
"if",
"self",
".",
"_ws",
"and",
"self",
".",
"_ws",
".",
"open",
":",
"log",
".",
"debug",
"(",
"'WebSocket still open, closing...'",
")",
"await",
"self",
".",
"_ws",
".",
"close",
"(",
")",
"user_id",
"=",
"self",
".",
"_lavalink",
".",
"bot",
".",
"user",
".",
"id",
"shard_count",
"=",
"self",
".",
"_lavalink",
".",
"bot",
".",
"shard_count",
"or",
"self",
".",
"_shards",
"headers",
"=",
"{",
"'Authorization'",
":",
"self",
".",
"_password",
",",
"'Num-Shards'",
":",
"shard_count",
",",
"'User-Id'",
":",
"str",
"(",
"user_id",
")",
"}",
"log",
".",
"debug",
"(",
"'Preparing to connect to Lavalink'",
")",
"log",
".",
"debug",
"(",
"' with URI: {}'",
".",
"format",
"(",
"self",
".",
"_uri",
")",
")",
"log",
".",
"debug",
"(",
"' with headers: {}'",
".",
"format",
"(",
"str",
"(",
"headers",
")",
")",
")",
"log",
".",
"info",
"(",
"'Connecting to Lavalink...'",
")",
"try",
":",
"self",
".",
"_ws",
"=",
"await",
"websockets",
".",
"connect",
"(",
"self",
".",
"_uri",
",",
"loop",
"=",
"self",
".",
"_loop",
",",
"extra_headers",
"=",
"headers",
")",
"except",
"OSError",
"as",
"error",
":",
"log",
".",
"exception",
"(",
"'Failed to connect to Lavalink: {}'",
".",
"format",
"(",
"str",
"(",
"error",
")",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"'Connected to Lavalink!'",
")",
"self",
".",
"_loop",
".",
"create_task",
"(",
"self",
".",
"listen",
"(",
")",
")",
"version",
"=",
"self",
".",
"_ws",
".",
"response_headers",
".",
"get",
"(",
"'Lavalink-Major-Version'",
",",
"2",
")",
"try",
":",
"self",
".",
"_lavalink",
".",
"_server_version",
"=",
"int",
"(",
"version",
")",
"except",
"ValueError",
":",
"self",
".",
"_lavalink",
".",
"_server_version",
"=",
"2",
"log",
".",
"info",
"(",
"'Lavalink server version is {}'",
".",
"format",
"(",
"version",
")",
")",
"if",
"self",
".",
"_queue",
":",
"log",
".",
"info",
"(",
"'Replaying {} queued events...'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_queue",
")",
")",
")",
"for",
"task",
"in",
"self",
".",
"_queue",
":",
"await",
"self",
".",
"send",
"(",
"*",
"*",
"task",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | WebSocket._attempt_reconnect | Attempts to reconnect to the Lavalink server.
Returns
-------
bool
``True`` if the reconnection attempt was successful. | lavalink/WebSocket.py | async def _attempt_reconnect(self):
"""
Attempts to reconnect to the Lavalink server.
Returns
-------
bool
``True`` if the reconnection attempt was successful.
"""
log.info('Connection closed; attempting to reconnect in 30 seconds')
for a in range(0, self._ws_retry):
await asyncio.sleep(30)
log.info('Reconnecting... (Attempt {})'.format(a + 1))
await self.connect()
if self._ws.open:
return True
return False | async def _attempt_reconnect(self):
"""
Attempts to reconnect to the Lavalink server.
Returns
-------
bool
``True`` if the reconnection attempt was successful.
"""
log.info('Connection closed; attempting to reconnect in 30 seconds')
for a in range(0, self._ws_retry):
await asyncio.sleep(30)
log.info('Reconnecting... (Attempt {})'.format(a + 1))
await self.connect()
if self._ws.open:
return True
return False | [
"Attempts",
"to",
"reconnect",
"to",
"the",
"Lavalink",
"server",
".",
"Returns",
"-------",
"bool",
"True",
"if",
"the",
"reconnection",
"attempt",
"was",
"successful",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L75-L91 | [
"async",
"def",
"_attempt_reconnect",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Connection closed; attempting to reconnect in 30 seconds'",
")",
"for",
"a",
"in",
"range",
"(",
"0",
",",
"self",
".",
"_ws_retry",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"30",
")",
"log",
".",
"info",
"(",
"'Reconnecting... (Attempt {})'",
".",
"format",
"(",
"a",
"+",
"1",
")",
")",
"await",
"self",
".",
"connect",
"(",
")",
"if",
"self",
".",
"_ws",
".",
"open",
":",
"return",
"True",
"return",
"False"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | WebSocket.listen | Waits to receive a payload from the Lavalink server and processes it. | lavalink/WebSocket.py | async def listen(self):
""" Waits to receive a payload from the Lavalink server and processes it. """
while not self._shutdown:
try:
data = json.loads(await self._ws.recv())
except websockets.ConnectionClosed as error:
log.warning('Disconnected from Lavalink: {}'.format(str(error)))
for g in self._lavalink.players._players.copy().keys():
ws = self._lavalink.bot._connection._get_websocket(int(g))
await ws.voice_state(int(g), None)
self._lavalink.players.clear()
if self._shutdown:
break
if await self._attempt_reconnect():
return
log.warning('Unable to reconnect to Lavalink!')
break
op = data.get('op', None)
log.debug('Received WebSocket data {}'.format(str(data)))
if not op:
return log.debug('Received WebSocket message without op {}'.format(str(data)))
if op == 'event':
log.debug('Received event of type {}'.format(data['type']))
player = self._lavalink.players[int(data['guildId'])]
event = None
if data['type'] == 'TrackEndEvent':
event = TrackEndEvent(player, data['track'], data['reason'])
elif data['type'] == 'TrackExceptionEvent':
event = TrackExceptionEvent(player, data['track'], data['error'])
elif data['type'] == 'TrackStuckEvent':
event = TrackStuckEvent(player, data['track'], data['thresholdMs'])
if event:
await self._lavalink.dispatch_event(event)
elif op == 'playerUpdate':
await self._lavalink.update_state(data)
elif op == 'stats':
self._lavalink.stats._update(data)
await self._lavalink.dispatch_event(StatsUpdateEvent(self._lavalink.stats))
log.debug('Closing WebSocket...')
await self._ws.close() | async def listen(self):
""" Waits to receive a payload from the Lavalink server and processes it. """
while not self._shutdown:
try:
data = json.loads(await self._ws.recv())
except websockets.ConnectionClosed as error:
log.warning('Disconnected from Lavalink: {}'.format(str(error)))
for g in self._lavalink.players._players.copy().keys():
ws = self._lavalink.bot._connection._get_websocket(int(g))
await ws.voice_state(int(g), None)
self._lavalink.players.clear()
if self._shutdown:
break
if await self._attempt_reconnect():
return
log.warning('Unable to reconnect to Lavalink!')
break
op = data.get('op', None)
log.debug('Received WebSocket data {}'.format(str(data)))
if not op:
return log.debug('Received WebSocket message without op {}'.format(str(data)))
if op == 'event':
log.debug('Received event of type {}'.format(data['type']))
player = self._lavalink.players[int(data['guildId'])]
event = None
if data['type'] == 'TrackEndEvent':
event = TrackEndEvent(player, data['track'], data['reason'])
elif data['type'] == 'TrackExceptionEvent':
event = TrackExceptionEvent(player, data['track'], data['error'])
elif data['type'] == 'TrackStuckEvent':
event = TrackStuckEvent(player, data['track'], data['thresholdMs'])
if event:
await self._lavalink.dispatch_event(event)
elif op == 'playerUpdate':
await self._lavalink.update_state(data)
elif op == 'stats':
self._lavalink.stats._update(data)
await self._lavalink.dispatch_event(StatsUpdateEvent(self._lavalink.stats))
log.debug('Closing WebSocket...')
await self._ws.close() | [
"Waits",
"to",
"receive",
"a",
"payload",
"from",
"the",
"Lavalink",
"server",
"and",
"processes",
"it",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L93-L142 | [
"async",
"def",
"listen",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_shutdown",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"await",
"self",
".",
"_ws",
".",
"recv",
"(",
")",
")",
"except",
"websockets",
".",
"ConnectionClosed",
"as",
"error",
":",
"log",
".",
"warning",
"(",
"'Disconnected from Lavalink: {}'",
".",
"format",
"(",
"str",
"(",
"error",
")",
")",
")",
"for",
"g",
"in",
"self",
".",
"_lavalink",
".",
"players",
".",
"_players",
".",
"copy",
"(",
")",
".",
"keys",
"(",
")",
":",
"ws",
"=",
"self",
".",
"_lavalink",
".",
"bot",
".",
"_connection",
".",
"_get_websocket",
"(",
"int",
"(",
"g",
")",
")",
"await",
"ws",
".",
"voice_state",
"(",
"int",
"(",
"g",
")",
",",
"None",
")",
"self",
".",
"_lavalink",
".",
"players",
".",
"clear",
"(",
")",
"if",
"self",
".",
"_shutdown",
":",
"break",
"if",
"await",
"self",
".",
"_attempt_reconnect",
"(",
")",
":",
"return",
"log",
".",
"warning",
"(",
"'Unable to reconnect to Lavalink!'",
")",
"break",
"op",
"=",
"data",
".",
"get",
"(",
"'op'",
",",
"None",
")",
"log",
".",
"debug",
"(",
"'Received WebSocket data {}'",
".",
"format",
"(",
"str",
"(",
"data",
")",
")",
")",
"if",
"not",
"op",
":",
"return",
"log",
".",
"debug",
"(",
"'Received WebSocket message without op {}'",
".",
"format",
"(",
"str",
"(",
"data",
")",
")",
")",
"if",
"op",
"==",
"'event'",
":",
"log",
".",
"debug",
"(",
"'Received event of type {}'",
".",
"format",
"(",
"data",
"[",
"'type'",
"]",
")",
")",
"player",
"=",
"self",
".",
"_lavalink",
".",
"players",
"[",
"int",
"(",
"data",
"[",
"'guildId'",
"]",
")",
"]",
"event",
"=",
"None",
"if",
"data",
"[",
"'type'",
"]",
"==",
"'TrackEndEvent'",
":",
"event",
"=",
"TrackEndEvent",
"(",
"player",
",",
"data",
"[",
"'track'",
"]",
",",
"data",
"[",
"'reason'",
"]",
")",
"elif",
"data",
"[",
"'type'",
"]",
"==",
"'TrackExceptionEvent'",
":",
"event",
"=",
"TrackExceptionEvent",
"(",
"player",
",",
"data",
"[",
"'track'",
"]",
",",
"data",
"[",
"'error'",
"]",
")",
"elif",
"data",
"[",
"'type'",
"]",
"==",
"'TrackStuckEvent'",
":",
"event",
"=",
"TrackStuckEvent",
"(",
"player",
",",
"data",
"[",
"'track'",
"]",
",",
"data",
"[",
"'thresholdMs'",
"]",
")",
"if",
"event",
":",
"await",
"self",
".",
"_lavalink",
".",
"dispatch_event",
"(",
"event",
")",
"elif",
"op",
"==",
"'playerUpdate'",
":",
"await",
"self",
".",
"_lavalink",
".",
"update_state",
"(",
"data",
")",
"elif",
"op",
"==",
"'stats'",
":",
"self",
".",
"_lavalink",
".",
"stats",
".",
"_update",
"(",
"data",
")",
"await",
"self",
".",
"_lavalink",
".",
"dispatch_event",
"(",
"StatsUpdateEvent",
"(",
"self",
".",
"_lavalink",
".",
"stats",
")",
")",
"log",
".",
"debug",
"(",
"'Closing WebSocket...'",
")",
"await",
"self",
".",
"_ws",
".",
"close",
"(",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.connected_channel | Returns the voice channel the player is connected to. | lavalink/PlayerManager.py | def connected_channel(self):
""" Returns the voice channel the player is connected to. """
if not self.channel_id:
return None
return self._lavalink.bot.get_channel(int(self.channel_id)) | def connected_channel(self):
""" Returns the voice channel the player is connected to. """
if not self.channel_id:
return None
return self._lavalink.bot.get_channel(int(self.channel_id)) | [
"Returns",
"the",
"voice",
"channel",
"the",
"player",
"is",
"connected",
"to",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L55-L60 | [
"def",
"connected_channel",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"channel_id",
":",
"return",
"None",
"return",
"self",
".",
"_lavalink",
".",
"bot",
".",
"get_channel",
"(",
"int",
"(",
"self",
".",
"channel_id",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.connect | Connects to a voice channel. | lavalink/PlayerManager.py | async def connect(self, channel_id: int):
""" Connects to a voice channel. """
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guild_id, str(channel_id)) | async def connect(self, channel_id: int):
""" Connects to a voice channel. """
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guild_id, str(channel_id)) | [
"Connects",
"to",
"a",
"voice",
"channel",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L62-L65 | [
"async",
"def",
"connect",
"(",
"self",
",",
"channel_id",
":",
"int",
")",
":",
"ws",
"=",
"self",
".",
"_lavalink",
".",
"bot",
".",
"_connection",
".",
"_get_websocket",
"(",
"int",
"(",
"self",
".",
"guild_id",
")",
")",
"await",
"ws",
".",
"voice_state",
"(",
"self",
".",
"guild_id",
",",
"str",
"(",
"channel_id",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.disconnect | Disconnects from the voice channel, if any. | lavalink/PlayerManager.py | async def disconnect(self):
""" Disconnects from the voice channel, if any. """
if not self.is_connected:
return
await self.stop()
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guild_id, None) | async def disconnect(self):
""" Disconnects from the voice channel, if any. """
if not self.is_connected:
return
await self.stop()
ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))
await ws.voice_state(self.guild_id, None) | [
"Disconnects",
"from",
"the",
"voice",
"channel",
"if",
"any",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L67-L75 | [
"async",
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
":",
"return",
"await",
"self",
".",
"stop",
"(",
")",
"ws",
"=",
"self",
".",
"_lavalink",
".",
"bot",
".",
"_connection",
".",
"_get_websocket",
"(",
"int",
"(",
"self",
".",
"guild_id",
")",
")",
"await",
"ws",
".",
"voice_state",
"(",
"self",
".",
"guild_id",
",",
"None",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.store | Stores custom user data. | lavalink/PlayerManager.py | def store(self, key: object, value: object):
""" Stores custom user data. """
self._user_data.update({key: value}) | def store(self, key: object, value: object):
""" Stores custom user data. """
self._user_data.update({key: value}) | [
"Stores",
"custom",
"user",
"data",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L77-L79 | [
"def",
"store",
"(",
"self",
",",
"key",
":",
"object",
",",
"value",
":",
"object",
")",
":",
"self",
".",
"_user_data",
".",
"update",
"(",
"{",
"key",
":",
"value",
"}",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.fetch | Retrieves the related value from the stored user data. | lavalink/PlayerManager.py | def fetch(self, key: object, default=None):
""" Retrieves the related value from the stored user data. """
return self._user_data.get(key, default) | def fetch(self, key: object, default=None):
""" Retrieves the related value from the stored user data. """
return self._user_data.get(key, default) | [
"Retrieves",
"the",
"related",
"value",
"from",
"the",
"stored",
"user",
"data",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L81-L83 | [
"def",
"fetch",
"(",
"self",
",",
"key",
":",
"object",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_user_data",
".",
"get",
"(",
"key",
",",
"default",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.add | Adds a track to the queue. | lavalink/PlayerManager.py | def add(self, requester: int, track: dict):
""" Adds a track to the queue. """
self.queue.append(AudioTrack().build(track, requester)) | def add(self, requester: int, track: dict):
""" Adds a track to the queue. """
self.queue.append(AudioTrack().build(track, requester)) | [
"Adds",
"a",
"track",
"to",
"the",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L92-L94 | [
"def",
"add",
"(",
"self",
",",
"requester",
":",
"int",
",",
"track",
":",
"dict",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"AudioTrack",
"(",
")",
".",
"build",
"(",
"track",
",",
"requester",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.add_next | Adds a track to beginning of the queue | lavalink/PlayerManager.py | def add_next(self, requester: int, track: dict):
""" Adds a track to beginning of the queue """
self.queue.insert(0, AudioTrack().build(track, requester)) | def add_next(self, requester: int, track: dict):
""" Adds a track to beginning of the queue """
self.queue.insert(0, AudioTrack().build(track, requester)) | [
"Adds",
"a",
"track",
"to",
"beginning",
"of",
"the",
"queue"
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L96-L98 | [
"def",
"add_next",
"(",
"self",
",",
"requester",
":",
"int",
",",
"track",
":",
"dict",
")",
":",
"self",
".",
"queue",
".",
"insert",
"(",
"0",
",",
"AudioTrack",
"(",
")",
".",
"build",
"(",
"track",
",",
"requester",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.add_at | Adds a track at a specific index in the queue. | lavalink/PlayerManager.py | def add_at(self, index: int, requester: int, track: dict):
""" Adds a track at a specific index in the queue. """
self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester)) | def add_at(self, index: int, requester: int, track: dict):
""" Adds a track at a specific index in the queue. """
self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester)) | [
"Adds",
"a",
"track",
"at",
"a",
"specific",
"index",
"in",
"the",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L100-L102 | [
"def",
"add_at",
"(",
"self",
",",
"index",
":",
"int",
",",
"requester",
":",
"int",
",",
"track",
":",
"dict",
")",
":",
"self",
".",
"queue",
".",
"insert",
"(",
"min",
"(",
"index",
",",
"len",
"(",
"self",
".",
"queue",
")",
"-",
"1",
")",
",",
"AudioTrack",
"(",
")",
".",
"build",
"(",
"track",
",",
"requester",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.play | Plays the first track in the queue, if any or plays a track from the specified index in the queue. | lavalink/PlayerManager.py | async def play(self, track_index: int = 0, ignore_shuffle: bool = False):
""" Plays the first track in the queue, if any or plays a track from the specified index in the queue. """
if self.repeat and self.current:
self.queue.append(self.current)
self.previous = self.current
self.current = None
self.position = 0
self.paused = False
if not self.queue:
await self.stop()
await self._lavalink.dispatch_event(QueueEndEvent(self))
else:
if self.shuffle and not ignore_shuffle:
track = self.queue.pop(randrange(len(self.queue)))
else:
track = self.queue.pop(min(track_index, len(self.queue) - 1))
self.current = track
await self._lavalink.ws.send(op='play', guildId=self.guild_id, track=track.track)
await self._lavalink.dispatch_event(TrackStartEvent(self, track)) | async def play(self, track_index: int = 0, ignore_shuffle: bool = False):
""" Plays the first track in the queue, if any or plays a track from the specified index in the queue. """
if self.repeat and self.current:
self.queue.append(self.current)
self.previous = self.current
self.current = None
self.position = 0
self.paused = False
if not self.queue:
await self.stop()
await self._lavalink.dispatch_event(QueueEndEvent(self))
else:
if self.shuffle and not ignore_shuffle:
track = self.queue.pop(randrange(len(self.queue)))
else:
track = self.queue.pop(min(track_index, len(self.queue) - 1))
self.current = track
await self._lavalink.ws.send(op='play', guildId=self.guild_id, track=track.track)
await self._lavalink.dispatch_event(TrackStartEvent(self, track)) | [
"Plays",
"the",
"first",
"track",
"in",
"the",
"queue",
"if",
"any",
"or",
"plays",
"a",
"track",
"from",
"the",
"specified",
"index",
"in",
"the",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L104-L125 | [
"async",
"def",
"play",
"(",
"self",
",",
"track_index",
":",
"int",
"=",
"0",
",",
"ignore_shuffle",
":",
"bool",
"=",
"False",
")",
":",
"if",
"self",
".",
"repeat",
"and",
"self",
".",
"current",
":",
"self",
".",
"queue",
".",
"append",
"(",
"self",
".",
"current",
")",
"self",
".",
"previous",
"=",
"self",
".",
"current",
"self",
".",
"current",
"=",
"None",
"self",
".",
"position",
"=",
"0",
"self",
".",
"paused",
"=",
"False",
"if",
"not",
"self",
".",
"queue",
":",
"await",
"self",
".",
"stop",
"(",
")",
"await",
"self",
".",
"_lavalink",
".",
"dispatch_event",
"(",
"QueueEndEvent",
"(",
"self",
")",
")",
"else",
":",
"if",
"self",
".",
"shuffle",
"and",
"not",
"ignore_shuffle",
":",
"track",
"=",
"self",
".",
"queue",
".",
"pop",
"(",
"randrange",
"(",
"len",
"(",
"self",
".",
"queue",
")",
")",
")",
"else",
":",
"track",
"=",
"self",
".",
"queue",
".",
"pop",
"(",
"min",
"(",
"track_index",
",",
"len",
"(",
"self",
".",
"queue",
")",
"-",
"1",
")",
")",
"self",
".",
"current",
"=",
"track",
"await",
"self",
".",
"_lavalink",
".",
"ws",
".",
"send",
"(",
"op",
"=",
"'play'",
",",
"guildId",
"=",
"self",
".",
"guild_id",
",",
"track",
"=",
"track",
".",
"track",
")",
"await",
"self",
".",
"_lavalink",
".",
"dispatch_event",
"(",
"TrackStartEvent",
"(",
"self",
",",
"track",
")",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.play_now | Add track and play it. | lavalink/PlayerManager.py | async def play_now(self, requester: int, track: dict):
""" Add track and play it. """
self.add_next(requester, track)
await self.play(ignore_shuffle=True) | async def play_now(self, requester: int, track: dict):
""" Add track and play it. """
self.add_next(requester, track)
await self.play(ignore_shuffle=True) | [
"Add",
"track",
"and",
"play",
"it",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L127-L130 | [
"async",
"def",
"play_now",
"(",
"self",
",",
"requester",
":",
"int",
",",
"track",
":",
"dict",
")",
":",
"self",
".",
"add_next",
"(",
"requester",
",",
"track",
")",
"await",
"self",
".",
"play",
"(",
"ignore_shuffle",
"=",
"True",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.play_at | Play the queue from a specific point. Disregards tracks before the index. | lavalink/PlayerManager.py | async def play_at(self, index: int):
""" Play the queue from a specific point. Disregards tracks before the index. """
self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)]
await self.play(ignore_shuffle=True) | async def play_at(self, index: int):
""" Play the queue from a specific point. Disregards tracks before the index. """
self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)]
await self.play(ignore_shuffle=True) | [
"Play",
"the",
"queue",
"from",
"a",
"specific",
"point",
".",
"Disregards",
"tracks",
"before",
"the",
"index",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L132-L135 | [
"async",
"def",
"play_at",
"(",
"self",
",",
"index",
":",
"int",
")",
":",
"self",
".",
"queue",
"=",
"self",
".",
"queue",
"[",
"min",
"(",
"index",
",",
"len",
"(",
"self",
".",
"queue",
")",
"-",
"1",
")",
":",
"len",
"(",
"self",
".",
"queue",
")",
"]",
"await",
"self",
".",
"play",
"(",
"ignore_shuffle",
"=",
"True",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.play_previous | Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. | lavalink/PlayerManager.py | async def play_previous(self):
""" Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. """
if not self.previous:
raise NoPreviousTrack
self.queue.insert(0, self.previous)
await self.play(ignore_shuffle=True) | async def play_previous(self):
""" Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. """
if not self.previous:
raise NoPreviousTrack
self.queue.insert(0, self.previous)
await self.play(ignore_shuffle=True) | [
"Plays",
"previous",
"track",
"if",
"it",
"exist",
"if",
"it",
"doesn",
"t",
"raises",
"a",
"NoPreviousTrack",
"error",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L137-L142 | [
"async",
"def",
"play_previous",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"previous",
":",
"raise",
"NoPreviousTrack",
"self",
".",
"queue",
".",
"insert",
"(",
"0",
",",
"self",
".",
"previous",
")",
"await",
"self",
".",
"play",
"(",
"ignore_shuffle",
"=",
"True",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.stop | Stops the player, if playing. | lavalink/PlayerManager.py | async def stop(self):
""" Stops the player, if playing. """
await self._lavalink.ws.send(op='stop', guildId=self.guild_id)
self.current = None | async def stop(self):
""" Stops the player, if playing. """
await self._lavalink.ws.send(op='stop', guildId=self.guild_id)
self.current = None | [
"Stops",
"the",
"player",
"if",
"playing",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L144-L147 | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"_lavalink",
".",
"ws",
".",
"send",
"(",
"op",
"=",
"'stop'",
",",
"guildId",
"=",
"self",
".",
"guild_id",
")",
"self",
".",
"current",
"=",
"None"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.set_pause | Sets the player's paused state. | lavalink/PlayerManager.py | async def set_pause(self, pause: bool):
""" Sets the player's paused state. """
await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause)
self.paused = pause | async def set_pause(self, pause: bool):
""" Sets the player's paused state. """
await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause)
self.paused = pause | [
"Sets",
"the",
"player",
"s",
"paused",
"state",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L153-L156 | [
"async",
"def",
"set_pause",
"(",
"self",
",",
"pause",
":",
"bool",
")",
":",
"await",
"self",
".",
"_lavalink",
".",
"ws",
".",
"send",
"(",
"op",
"=",
"'pause'",
",",
"guildId",
"=",
"self",
".",
"guild_id",
",",
"pause",
"=",
"pause",
")",
"self",
".",
"paused",
"=",
"pause"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.set_volume | Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version). | lavalink/PlayerManager.py | async def set_volume(self, vol: int):
""" Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version). """
if self._lavalink._server_version <= 2:
self.volume = max(min(vol, 150), 0)
else:
self.volume = max(min(vol, 1000), 0)
await self._lavalink.ws.send(op='volume', guildId=self.guild_id, volume=self.volume) | async def set_volume(self, vol: int):
""" Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version). """
if self._lavalink._server_version <= 2:
self.volume = max(min(vol, 150), 0)
else:
self.volume = max(min(vol, 1000), 0)
await self._lavalink.ws.send(op='volume', guildId=self.guild_id, volume=self.volume) | [
"Sets",
"the",
"player",
"s",
"volume",
"(",
"150%",
"or",
"1000%",
"limit",
"imposed",
"by",
"lavalink",
"depending",
"on",
"the",
"version",
")",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L158-L164 | [
"async",
"def",
"set_volume",
"(",
"self",
",",
"vol",
":",
"int",
")",
":",
"if",
"self",
".",
"_lavalink",
".",
"_server_version",
"<=",
"2",
":",
"self",
".",
"volume",
"=",
"max",
"(",
"min",
"(",
"vol",
",",
"150",
")",
",",
"0",
")",
"else",
":",
"self",
".",
"volume",
"=",
"max",
"(",
"min",
"(",
"vol",
",",
"1000",
")",
",",
"0",
")",
"await",
"self",
".",
"_lavalink",
".",
"ws",
".",
"send",
"(",
"op",
"=",
"'volume'",
",",
"guildId",
"=",
"self",
".",
"guild_id",
",",
"volume",
"=",
"self",
".",
"volume",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.seek | Seeks to a given position in the track. | lavalink/PlayerManager.py | async def seek(self, pos: int):
""" Seeks to a given position in the track. """
await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos) | async def seek(self, pos: int):
""" Seeks to a given position in the track. """
await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos) | [
"Seeks",
"to",
"a",
"given",
"position",
"in",
"the",
"track",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L166-L168 | [
"async",
"def",
"seek",
"(",
"self",
",",
"pos",
":",
"int",
")",
":",
"await",
"self",
".",
"_lavalink",
".",
"ws",
".",
"send",
"(",
"op",
"=",
"'seek'",
",",
"guildId",
"=",
"self",
".",
"guild_id",
",",
"position",
"=",
"pos",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | DefaultPlayer.handle_event | Makes the player play the next song from the queue if a song has finished or an issue occurred. | lavalink/PlayerManager.py | async def handle_event(self, event):
""" Makes the player play the next song from the queue if a song has finished or an issue occurred. """
if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \
isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':
await self.play() | async def handle_event(self, event):
""" Makes the player play the next song from the queue if a song has finished or an issue occurred. """
if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \
isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':
await self.play() | [
"Makes",
"the",
"player",
"play",
"the",
"next",
"song",
"from",
"the",
"queue",
"if",
"a",
"song",
"has",
"finished",
"or",
"an",
"issue",
"occurred",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L170-L174 | [
"async",
"def",
"handle_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"(",
"TrackStuckEvent",
",",
"TrackExceptionEvent",
")",
")",
"or",
"isinstance",
"(",
"event",
",",
"TrackEndEvent",
")",
"and",
"event",
".",
"reason",
"==",
"'FINISHED'",
":",
"await",
"self",
".",
"play",
"(",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | PlayerManager.get | Returns a player from the cache, or creates one if it does not exist. | lavalink/PlayerManager.py | def get(self, guild_id):
""" Returns a player from the cache, or creates one if it does not exist. """
if guild_id not in self._players:
p = self._player(lavalink=self.lavalink, guild_id=guild_id)
self._players[guild_id] = p
return self._players[guild_id] | def get(self, guild_id):
""" Returns a player from the cache, or creates one if it does not exist. """
if guild_id not in self._players:
p = self._player(lavalink=self.lavalink, guild_id=guild_id)
self._players[guild_id] = p
return self._players[guild_id] | [
"Returns",
"a",
"player",
"from",
"the",
"cache",
"or",
"creates",
"one",
"if",
"it",
"does",
"not",
"exist",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L218-L224 | [
"def",
"get",
"(",
"self",
",",
"guild_id",
")",
":",
"if",
"guild_id",
"not",
"in",
"self",
".",
"_players",
":",
"p",
"=",
"self",
".",
"_player",
"(",
"lavalink",
"=",
"self",
".",
"lavalink",
",",
"guild_id",
"=",
"guild_id",
")",
"self",
".",
"_players",
"[",
"guild_id",
"]",
"=",
"p",
"return",
"self",
".",
"_players",
"[",
"guild_id",
"]"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | PlayerManager.remove | Removes a player from the current players. | lavalink/PlayerManager.py | def remove(self, guild_id):
""" Removes a player from the current players. """
if guild_id in self._players:
self._players[guild_id].cleanup()
del self._players[guild_id] | def remove(self, guild_id):
""" Removes a player from the current players. """
if guild_id in self._players:
self._players[guild_id].cleanup()
del self._players[guild_id] | [
"Removes",
"a",
"player",
"from",
"the",
"current",
"players",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/PlayerManager.py#L226-L230 | [
"def",
"remove",
"(",
"self",
",",
"guild_id",
")",
":",
"if",
"guild_id",
"in",
"self",
".",
"_players",
":",
"self",
".",
"_players",
"[",
"guild_id",
"]",
".",
"cleanup",
"(",
")",
"del",
"self",
".",
"_players",
"[",
"guild_id",
"]"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._play | Searches and plays a song from a given query. | examples/music-v2.py | async def _play(self, ctx, *, query: str):
""" Searches and plays a song from a given query. """
player = self.bot.lavalink.players.get(ctx.guild.id)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytsearch:{query}'
tracks = await self.bot.lavalink.get_tracks(query)
if not tracks:
return await ctx.send('Nothing found!')
embed = discord.Embed(color=discord.Color.blurple())
if 'list' in query and 'ytsearch:' not in query:
for track in tracks:
player.add(requester=ctx.author.id, track=track)
embed.title = 'Playlist enqueued!'
embed.description = f'Imported {len(tracks)} tracks from the playlist!'
await ctx.send(embed=embed)
else:
track_title = tracks[0]["info"]["title"]
track_uri = tracks[0]["info"]["uri"]
embed.title = "Track enqueued!"
embed.description = f'[{track_title}]({track_uri})'
player.add(requester=ctx.author.id, track=tracks[0])
if not player.is_playing:
await player.play() | async def _play(self, ctx, *, query: str):
""" Searches and plays a song from a given query. """
player = self.bot.lavalink.players.get(ctx.guild.id)
query = query.strip('<>')
if not url_rx.match(query):
query = f'ytsearch:{query}'
tracks = await self.bot.lavalink.get_tracks(query)
if not tracks:
return await ctx.send('Nothing found!')
embed = discord.Embed(color=discord.Color.blurple())
if 'list' in query and 'ytsearch:' not in query:
for track in tracks:
player.add(requester=ctx.author.id, track=track)
embed.title = 'Playlist enqueued!'
embed.description = f'Imported {len(tracks)} tracks from the playlist!'
await ctx.send(embed=embed)
else:
track_title = tracks[0]["info"]["title"]
track_uri = tracks[0]["info"]["uri"]
embed.title = "Track enqueued!"
embed.description = f'[{track_title}]({track_uri})'
player.add(requester=ctx.author.id, track=tracks[0])
if not player.is_playing:
await player.play() | [
"Searches",
"and",
"plays",
"a",
"song",
"from",
"a",
"given",
"query",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L55-L87 | [
"async",
"def",
"_play",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"query",
":",
"str",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"query",
"=",
"query",
".",
"strip",
"(",
"'<>'",
")",
"if",
"not",
"url_rx",
".",
"match",
"(",
"query",
")",
":",
"query",
"=",
"f'ytsearch:{query}'",
"tracks",
"=",
"await",
"self",
".",
"bot",
".",
"lavalink",
".",
"get_tracks",
"(",
"query",
")",
"if",
"not",
"tracks",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Nothing found!'",
")",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"color",
"=",
"discord",
".",
"Color",
".",
"blurple",
"(",
")",
")",
"if",
"'list'",
"in",
"query",
"and",
"'ytsearch:'",
"not",
"in",
"query",
":",
"for",
"track",
"in",
"tracks",
":",
"player",
".",
"add",
"(",
"requester",
"=",
"ctx",
".",
"author",
".",
"id",
",",
"track",
"=",
"track",
")",
"embed",
".",
"title",
"=",
"'Playlist enqueued!'",
"embed",
".",
"description",
"=",
"f'Imported {len(tracks)} tracks from the playlist!'",
"await",
"ctx",
".",
"send",
"(",
"embed",
"=",
"embed",
")",
"else",
":",
"track_title",
"=",
"tracks",
"[",
"0",
"]",
"[",
"\"info\"",
"]",
"[",
"\"title\"",
"]",
"track_uri",
"=",
"tracks",
"[",
"0",
"]",
"[",
"\"info\"",
"]",
"[",
"\"uri\"",
"]",
"embed",
".",
"title",
"=",
"\"Track enqueued!\"",
"embed",
".",
"description",
"=",
"f'[{track_title}]({track_uri})'",
"player",
".",
"add",
"(",
"requester",
"=",
"ctx",
".",
"author",
".",
"id",
",",
"track",
"=",
"tracks",
"[",
"0",
"]",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"await",
"player",
".",
"play",
"(",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._seek | Seeks to a given position in a track. | examples/music-v2.py | async def _seek(self, ctx, *, time: str):
""" Seeks to a given position in a track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
seconds = time_rx.search(time)
if not seconds:
return await ctx.send('You need to specify the amount of seconds to skip!')
seconds = int(seconds.group()) * 1000
if time.startswith('-'):
seconds *= -1
track_time = player.position + seconds
await player.seek(track_time)
await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**') | async def _seek(self, ctx, *, time: str):
""" Seeks to a given position in a track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
seconds = time_rx.search(time)
if not seconds:
return await ctx.send('You need to specify the amount of seconds to skip!')
seconds = int(seconds.group()) * 1000
if time.startswith('-'):
seconds *= -1
track_time = player.position + seconds
await player.seek(track_time)
await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**') | [
"Seeks",
"to",
"a",
"given",
"position",
"in",
"a",
"track",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L91-L109 | [
"async",
"def",
"_seek",
"(",
"self",
",",
"ctx",
",",
"*",
",",
"time",
":",
"str",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Not playing.'",
")",
"seconds",
"=",
"time_rx",
".",
"search",
"(",
"time",
")",
"if",
"not",
"seconds",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'You need to specify the amount of seconds to skip!'",
")",
"seconds",
"=",
"int",
"(",
"seconds",
".",
"group",
"(",
")",
")",
"*",
"1000",
"if",
"time",
".",
"startswith",
"(",
"'-'",
")",
":",
"seconds",
"*=",
"-",
"1",
"track_time",
"=",
"player",
".",
"position",
"+",
"seconds",
"await",
"player",
".",
"seek",
"(",
"track_time",
")",
"await",
"ctx",
".",
"send",
"(",
"f'Moved track to **{lavalink.Utils.format_time(track_time)}**'",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._skip | Skips the current track. | examples/music-v2.py | async def _skip(self, ctx):
""" Skips the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
await player.skip()
await ctx.send('β | Skipped.') | async def _skip(self, ctx):
""" Skips the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
await player.skip()
await ctx.send('β | Skipped.') | [
"Skips",
"the",
"current",
"track",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L113-L121 | [
"async",
"def",
"_skip",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Not playing.'",
")",
"await",
"player",
".",
"skip",
"(",
")",
"await",
"ctx",
".",
"send",
"(",
"'β | Skipped.')\r",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._stop | Stops the player and clears its queue. | examples/music-v2.py | async def _stop(self, ctx):
""" Stops the player and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
player.queue.clear()
await player.stop()
await ctx.send('βΉ | Stopped.') | async def _stop(self, ctx):
""" Stops the player and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
player.queue.clear()
await player.stop()
await ctx.send('βΉ | Stopped.') | [
"Stops",
"the",
"player",
"and",
"clears",
"its",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L125-L134 | [
"async",
"def",
"_stop",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Not playing.'",
")",
"player",
".",
"queue",
".",
"clear",
"(",
")",
"await",
"player",
".",
"stop",
"(",
")",
"await",
"ctx",
".",
"send",
"(",
"'βΉ | Stopped.')\r",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._now | Shows some stats about the currently playing song. | examples/music-v2.py | async def _now(self, ctx):
""" Shows some stats about the currently playing song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
song = 'Nothing'
if player.current:
position = lavalink.Utils.format_time(player.position)
if player.current.stream:
duration = 'π΄ LIVE'
else:
duration = lavalink.Utils.format_time(player.current.duration)
song = f'**[{player.current.title}]({player.current.uri})**\n({position}/{duration})'
embed = discord.Embed(color=discord.Color.blurple(), title='Now Playing', description=song)
await ctx.send(embed=embed) | async def _now(self, ctx):
""" Shows some stats about the currently playing song. """
player = self.bot.lavalink.players.get(ctx.guild.id)
song = 'Nothing'
if player.current:
position = lavalink.Utils.format_time(player.position)
if player.current.stream:
duration = 'π΄ LIVE'
else:
duration = lavalink.Utils.format_time(player.current.duration)
song = f'**[{player.current.title}]({player.current.uri})**\n({position}/{duration})'
embed = discord.Embed(color=discord.Color.blurple(), title='Now Playing', description=song)
await ctx.send(embed=embed) | [
"Shows",
"some",
"stats",
"about",
"the",
"currently",
"playing",
"song",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L138-L152 | [
"async",
"def",
"_now",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"song",
"=",
"'Nothing'",
"if",
"player",
".",
"current",
":",
"position",
"=",
"lavalink",
".",
"Utils",
".",
"format_time",
"(",
"player",
".",
"position",
")",
"if",
"player",
".",
"current",
".",
"stream",
":",
"duration",
"=",
"'π΄ LIVE'\r",
"else",
":",
"duration",
"=",
"lavalink",
".",
"Utils",
".",
"format_time",
"(",
"player",
".",
"current",
".",
"duration",
")",
"song",
"=",
"f'**[{player.current.title}]({player.current.uri})**\\n({position}/{duration})'",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"color",
"=",
"discord",
".",
"Color",
".",
"blurple",
"(",
")",
",",
"title",
"=",
"'Now Playing'",
",",
"description",
"=",
"song",
")",
"await",
"ctx",
".",
"send",
"(",
"embed",
"=",
"embed",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._queue | Shows the player's queue. | examples/music-v2.py | async def _queue(self, ctx, page: int = 1):
""" Shows the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('There\'s nothing in the queue! Why not queue something?')
items_per_page = 10
pages = math.ceil(len(player.queue) / items_per_page)
start = (page - 1) * items_per_page
end = start + items_per_page
queue_list = ''
for index, track in enumerate(player.queue[start:end], start=start):
queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n'
embed = discord.Embed(colour=discord.Color.blurple(),
description=f'**{len(player.queue)} tracks**\n\n{queue_list}')
embed.set_footer(text=f'Viewing page {page}/{pages}')
await ctx.send(embed=embed) | async def _queue(self, ctx, page: int = 1):
""" Shows the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('There\'s nothing in the queue! Why not queue something?')
items_per_page = 10
pages = math.ceil(len(player.queue) / items_per_page)
start = (page - 1) * items_per_page
end = start + items_per_page
queue_list = ''
for index, track in enumerate(player.queue[start:end], start=start):
queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n'
embed = discord.Embed(colour=discord.Color.blurple(),
description=f'**{len(player.queue)} tracks**\n\n{queue_list}')
embed.set_footer(text=f'Viewing page {page}/{pages}')
await ctx.send(embed=embed) | [
"Shows",
"the",
"player",
"s",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L156-L176 | [
"async",
"def",
"_queue",
"(",
"self",
",",
"ctx",
",",
"page",
":",
"int",
"=",
"1",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"queue",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'There\\'s nothing in the queue! Why not queue something?'",
")",
"items_per_page",
"=",
"10",
"pages",
"=",
"math",
".",
"ceil",
"(",
"len",
"(",
"player",
".",
"queue",
")",
"/",
"items_per_page",
")",
"start",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"items_per_page",
"end",
"=",
"start",
"+",
"items_per_page",
"queue_list",
"=",
"''",
"for",
"index",
",",
"track",
"in",
"enumerate",
"(",
"player",
".",
"queue",
"[",
"start",
":",
"end",
"]",
",",
"start",
"=",
"start",
")",
":",
"queue_list",
"+=",
"f'`{index + 1}.` [**{track.title}**]({track.uri})\\n'",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"colour",
"=",
"discord",
".",
"Color",
".",
"blurple",
"(",
")",
",",
"description",
"=",
"f'**{len(player.queue)} tracks**\\n\\n{queue_list}'",
")",
"embed",
".",
"set_footer",
"(",
"text",
"=",
"f'Viewing page {page}/{pages}'",
")",
"await",
"ctx",
".",
"send",
"(",
"embed",
"=",
"embed",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._pause | Pauses/Resumes the current track. | examples/music-v2.py | async def _pause(self, ctx):
""" Pauses/Resumes the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
if player.paused:
await player.set_pause(False)
await ctx.send('β― | Resumed')
else:
await player.set_pause(True)
await ctx.send('β― | Paused') | async def _pause(self, ctx):
""" Pauses/Resumes the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
if player.paused:
await player.set_pause(False)
await ctx.send('β― | Resumed')
else:
await player.set_pause(True)
await ctx.send('β― | Paused') | [
"Pauses",
"/",
"Resumes",
"the",
"current",
"track",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L180-L192 | [
"async",
"def",
"_pause",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Not playing.'",
")",
"if",
"player",
".",
"paused",
":",
"await",
"player",
".",
"set_pause",
"(",
"False",
")",
"await",
"ctx",
".",
"send",
"(",
"'β― | Resumed')\r",
"",
"else",
":",
"await",
"player",
".",
"set_pause",
"(",
"True",
")",
"await",
"ctx",
".",
"send",
"(",
"'β― | Paused')\r",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._volume | Changes the player's volume. Must be between 0 and 150. Error Handling for that is done by Lavalink. | examples/music-v2.py | async def _volume(self, ctx, volume: int = None):
""" Changes the player's volume. Must be between 0 and 150. Error Handling for that is done by Lavalink. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not volume:
return await ctx.send(f'π | {player.volume}%')
await player.set_volume(volume)
await ctx.send(f'π | Set to {player.volume}%') | async def _volume(self, ctx, volume: int = None):
""" Changes the player's volume. Must be between 0 and 150. Error Handling for that is done by Lavalink. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not volume:
return await ctx.send(f'π | {player.volume}%')
await player.set_volume(volume)
await ctx.send(f'π | Set to {player.volume}%') | [
"Changes",
"the",
"player",
"s",
"volume",
".",
"Must",
"be",
"between",
"0",
"and",
"150",
".",
"Error",
"Handling",
"for",
"that",
"is",
"done",
"by",
"Lavalink",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L196-L204 | [
"async",
"def",
"_volume",
"(",
"self",
",",
"ctx",
",",
"volume",
":",
"int",
"=",
"None",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"volume",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"f'π | {player.volume}%')\r",
"",
"await",
"player",
".",
"set_volume",
"(",
"volume",
")",
"await",
"ctx",
".",
"send",
"(",
"f'π | Set to {player.volume}%')\r",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._shuffle | Shuffles the player's queue. | examples/music-v2.py | async def _shuffle(self, ctx):
""" Shuffles the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.shuffle = not player.shuffle
await ctx.send('π | Shuffle ' + ('enabled' if player.shuffle else 'disabled')) | async def _shuffle(self, ctx):
""" Shuffles the player's queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.shuffle = not player.shuffle
await ctx.send('π | Shuffle ' + ('enabled' if player.shuffle else 'disabled')) | [
"Shuffles",
"the",
"player",
"s",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L208-L216 | [
"async",
"def",
"_shuffle",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Nothing playing.'",
")",
"player",
".",
"shuffle",
"=",
"not",
"player",
".",
"shuffle",
"await",
"ctx",
".",
"send",
"(",
"'π | Shuffle ' + ",
"'",
"n",
"abled' if",
"pl",
"yer.sh",
"u",
"ffle el",
"e 'd",
"sabled'))\r",
"",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._repeat | Repeats the current song until the command is invoked again. | examples/music-v2.py | async def _repeat(self, ctx):
""" Repeats the current song until the command is invoked again. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.repeat = not player.repeat
await ctx.send('π | Repeat ' + ('enabled' if player.repeat else 'disabled')) | async def _repeat(self, ctx):
""" Repeats the current song until the command is invoked again. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Nothing playing.')
player.repeat = not player.repeat
await ctx.send('π | Repeat ' + ('enabled' if player.repeat else 'disabled')) | [
"Repeats",
"the",
"current",
"song",
"until",
"the",
"command",
"is",
"invoked",
"again",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L220-L228 | [
"async",
"def",
"_repeat",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Nothing playing.'",
")",
"player",
".",
"repeat",
"=",
"not",
"player",
".",
"repeat",
"await",
"ctx",
".",
"send",
"(",
"'π | Repeat ' + ",
"'",
"n",
"abled' if",
"pl",
"yer.re",
"p",
"eat el",
"e 'd",
"sabled'))\r",
"",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._remove | Removes an item from the player's queue with the given index. | examples/music-v2.py | async def _remove(self, ctx, index: int):
""" Removes an item from the player's queue with the given index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('Nothing queued.')
if index > len(player.queue) or index < 1:
return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')
index -= 1
removed = player.queue.pop(index)
await ctx.send(f'Removed **{removed.title}** from the queue.') | async def _remove(self, ctx, index: int):
""" Removes an item from the player's queue with the given index. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send('Nothing queued.')
if index > len(player.queue) or index < 1:
return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')
index -= 1
removed = player.queue.pop(index)
await ctx.send(f'Removed **{removed.title}** from the queue.') | [
"Removes",
"an",
"item",
"from",
"the",
"player",
"s",
"queue",
"with",
"the",
"given",
"index",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L232-L245 | [
"async",
"def",
"_remove",
"(",
"self",
",",
"ctx",
",",
"index",
":",
"int",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"queue",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Nothing queued.'",
")",
"if",
"index",
">",
"len",
"(",
"player",
".",
"queue",
")",
"or",
"index",
"<",
"1",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"f'Index has to be **between** 1 and {len(player.queue)}'",
")",
"index",
"-=",
"1",
"removed",
"=",
"player",
".",
"queue",
".",
"pop",
"(",
"index",
")",
"await",
"ctx",
".",
"send",
"(",
"f'Removed **{removed.title}** from the queue.'",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music._disconnect | Disconnects the player from the voice channel and clears its queue. | examples/music-v2.py | async def _disconnect(self, ctx):
""" Disconnects the player from the voice channel and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
return await ctx.send('Not connected.')
if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)):
return await ctx.send('You\'re not in my voicechannel!')
player.queue.clear()
await player.disconnect()
await ctx.send('*β£ | Disconnected.') | async def _disconnect(self, ctx):
""" Disconnects the player from the voice channel and clears its queue. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
return await ctx.send('Not connected.')
if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)):
return await ctx.send('You\'re not in my voicechannel!')
player.queue.clear()
await player.disconnect()
await ctx.send('*β£ | Disconnected.') | [
"Disconnects",
"the",
"player",
"from",
"the",
"voice",
"channel",
"and",
"clears",
"its",
"queue",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L273-L285 | [
"async",
"def",
"_disconnect",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_connected",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Not connected.'",
")",
"if",
"not",
"ctx",
".",
"author",
".",
"voice",
"or",
"(",
"player",
".",
"is_connected",
"and",
"ctx",
".",
"author",
".",
"voice",
".",
"channel",
".",
"id",
"!=",
"int",
"(",
"player",
".",
"channel_id",
")",
")",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'You\\'re not in my voicechannel!'",
")",
"player",
".",
"queue",
".",
"clear",
"(",
")",
"await",
"player",
".",
"disconnect",
"(",
")",
"await",
"ctx",
".",
"send",
"(",
"'*β£ | Disconnected.')\r",
""
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Music.ensure_voice | A few checks to make sure the bot can join a voice channel. | examples/music-v2.py | async def ensure_voice(self, ctx):
""" A few checks to make sure the bot can join a voice channel. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send('You aren\'t connected to any voice channel.')
raise commands.CommandInvokeError('Author not connected to voice channel.')
permissions = ctx.author.voice.channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')
raise commands.CommandInvokeError('Bot has no permissions CONNECT and/or SPEAK')
player.store('channel', ctx.channel.id)
await player.connect(ctx.author.voice.channel.id)
else:
if player.connected_channel.id != ctx.author.voice.channel.id:
return await ctx.send('Join my voice channel!') | async def ensure_voice(self, ctx):
""" A few checks to make sure the bot can join a voice channel. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_connected:
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send('You aren\'t connected to any voice channel.')
raise commands.CommandInvokeError('Author not connected to voice channel.')
permissions = ctx.author.voice.channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')
raise commands.CommandInvokeError('Bot has no permissions CONNECT and/or SPEAK')
player.store('channel', ctx.channel.id)
await player.connect(ctx.author.voice.channel.id)
else:
if player.connected_channel.id != ctx.author.voice.channel.id:
return await ctx.send('Join my voice channel!') | [
"A",
"few",
"checks",
"to",
"make",
"sure",
"the",
"bot",
"can",
"join",
"a",
"voice",
"channel",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L288-L307 | [
"async",
"def",
"ensure_voice",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_connected",
":",
"if",
"not",
"ctx",
".",
"author",
".",
"voice",
"or",
"not",
"ctx",
".",
"author",
".",
"voice",
".",
"channel",
":",
"await",
"ctx",
".",
"send",
"(",
"'You aren\\'t connected to any voice channel.'",
")",
"raise",
"commands",
".",
"CommandInvokeError",
"(",
"'Author not connected to voice channel.'",
")",
"permissions",
"=",
"ctx",
".",
"author",
".",
"voice",
".",
"channel",
".",
"permissions_for",
"(",
"ctx",
".",
"me",
")",
"if",
"not",
"permissions",
".",
"connect",
"or",
"not",
"permissions",
".",
"speak",
":",
"await",
"ctx",
".",
"send",
"(",
"'Missing permissions `CONNECT` and/or `SPEAK`.'",
")",
"raise",
"commands",
".",
"CommandInvokeError",
"(",
"'Bot has no permissions CONNECT and/or SPEAK'",
")",
"player",
".",
"store",
"(",
"'channel'",
",",
"ctx",
".",
"channel",
".",
"id",
")",
"await",
"player",
".",
"connect",
"(",
"ctx",
".",
"author",
".",
"voice",
".",
"channel",
".",
"id",
")",
"else",
":",
"if",
"player",
".",
"connected_channel",
".",
"id",
"!=",
"ctx",
".",
"author",
".",
"voice",
".",
"channel",
".",
"id",
":",
"return",
"await",
"ctx",
".",
"send",
"(",
"'Join my voice channel!'",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
valid | Client.register_hook | Registers a hook. Since this probably is a bit difficult, I'll explain it in detail.
A hook basically is an object of a function you pass. This will append that object to a list and whenever
an event from the Lavalink server is dispatched, the function will be called internally. For declaring the
function that should become a hook, pass ``event` as its sole parameter.
Can be a function but also a coroutine.
Example for a method declaration inside a class:
---------------
self.bot.lavalink.register_hook(my_hook)
async def my_hook(self, event):
channel = self.bot.get_channel(event.player.fetch('channel'))
if not channel:
return
if isinstance(event, lavalink.Events.TrackStartEvent):
await channel.send(embed=discord.Embed(title='Now playing:',
description=event.track.title,
color=discord.Color.blurple()))
---------------
:param func:
The function that should be registered as a hook. | lavalink/Client.py | def register_hook(self, func):
"""
Registers a hook. Since this probably is a bit difficult, I'll explain it in detail.
A hook basically is an object of a function you pass. This will append that object to a list and whenever
an event from the Lavalink server is dispatched, the function will be called internally. For declaring the
function that should become a hook, pass ``event` as its sole parameter.
Can be a function but also a coroutine.
Example for a method declaration inside a class:
---------------
self.bot.lavalink.register_hook(my_hook)
async def my_hook(self, event):
channel = self.bot.get_channel(event.player.fetch('channel'))
if not channel:
return
if isinstance(event, lavalink.Events.TrackStartEvent):
await channel.send(embed=discord.Embed(title='Now playing:',
description=event.track.title,
color=discord.Color.blurple()))
---------------
:param func:
The function that should be registered as a hook.
"""
if func not in self.hooks:
self.hooks.append(func) | def register_hook(self, func):
"""
Registers a hook. Since this probably is a bit difficult, I'll explain it in detail.
A hook basically is an object of a function you pass. This will append that object to a list and whenever
an event from the Lavalink server is dispatched, the function will be called internally. For declaring the
function that should become a hook, pass ``event` as its sole parameter.
Can be a function but also a coroutine.
Example for a method declaration inside a class:
---------------
self.bot.lavalink.register_hook(my_hook)
async def my_hook(self, event):
channel = self.bot.get_channel(event.player.fetch('channel'))
if not channel:
return
if isinstance(event, lavalink.Events.TrackStartEvent):
await channel.send(embed=discord.Embed(title='Now playing:',
description=event.track.title,
color=discord.Color.blurple()))
---------------
:param func:
The function that should be registered as a hook.
"""
if func not in self.hooks:
self.hooks.append(func) | [
"Registers",
"a",
"hook",
".",
"Since",
"this",
"probably",
"is",
"a",
"bit",
"difficult",
"I",
"ll",
"explain",
"it",
"in",
"detail",
".",
"A",
"hook",
"basically",
"is",
"an",
"object",
"of",
"a",
"function",
"you",
"pass",
".",
"This",
"will",
"append",
"that",
"object",
"to",
"a",
"list",
"and",
"whenever",
"an",
"event",
"from",
"the",
"Lavalink",
"server",
"is",
"dispatched",
"the",
"function",
"will",
"be",
"called",
"internally",
".",
"For",
"declaring",
"the",
"function",
"that",
"should",
"become",
"a",
"hook",
"pass",
"event",
"as",
"its",
"sole",
"parameter",
".",
"Can",
"be",
"a",
"function",
"but",
"also",
"a",
"coroutine",
".",
"Example",
"for",
"a",
"method",
"declaration",
"inside",
"a",
"class",
":",
"---------------",
"self",
".",
"bot",
".",
"lavalink",
".",
"register_hook",
"(",
"my_hook",
")",
"async",
"def",
"my_hook",
"(",
"self",
"event",
")",
":",
"channel",
"=",
"self",
".",
"bot",
".",
"get_channel",
"(",
"event",
".",
"player",
".",
"fetch",
"(",
"channel",
"))",
"if",
"not",
"channel",
":",
"return",
"if",
"isinstance",
"(",
"event",
"lavalink",
".",
"Events",
".",
"TrackStartEvent",
")",
":",
"await",
"channel",
".",
"send",
"(",
"embed",
"=",
"discord",
".",
"Embed",
"(",
"title",
"=",
"Now",
"playing",
":",
"description",
"=",
"event",
".",
"track",
".",
"title",
"color",
"=",
"discord",
".",
"Color",
".",
"blurple",
"()",
"))",
"---------------",
":",
"param",
"func",
":",
"The",
"function",
"that",
"should",
"be",
"registered",
"as",
"a",
"hook",
"."
] | Devoxin/Lavalink.py | python | https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/Client.py#L71-L98 | [
"def",
"register_hook",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"not",
"in",
"self",
".",
"hooks",
":",
"self",
".",
"hooks",
".",
"append",
"(",
"func",
")"
] | 63f55c3d726d24c4cfd3674d3cd6aab6f5be110d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.