body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
c2a20a19fc55f0db7615ba0cb0a48ebd9db35c8188574aa3af38c678fcace99a
def _get_local_as(self): '\n Getter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' return self.__local_as
Getter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number) YANG Description: The local autonomous system number that is to be used when establishing sessions with the remote peer or peer group, if this differs from the global BGP router autonomous system number.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_local_as
ckishimo/napalm-yang
64
python
def _get_local_as(self): '\n Getter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' return self.__local_as
def _get_local_as(self): '\n Getter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' return self.__local_as<|docstring|>Getter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number) YANG Description: The local autonomous system number that is to be used when establishing sessions with the remote peer or peer group, if this differs from the global BGP router autonomous system number.<|endoftext|>
e24163c1c8ef1af3799b7391023cb38df0692118bb1d12785a7d8d38eac9c8d0
def _set_local_as(self, v, load=False): '\n Setter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_local_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_local_as() directly.\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='local-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-inet:as-number', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'local_as must be of a type compatible with oc-inet:as-number', 'defined-type': 'oc-inet:as-number', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="local-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-inet:as-number\', is_config=True)'}) self.__local_as = t if hasattr(self, '_set'): self._set()
Setter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number) If this variable is read-only (config: false) in the source YANG file, then _set_local_as is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_local_as() directly. YANG Description: The local autonomous system number that is to be used when establishing sessions with the remote peer or peer group, if this differs from the global BGP router autonomous system number.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_local_as
ckishimo/napalm-yang
64
python
def _set_local_as(self, v, load=False): '\n Setter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_local_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_local_as() directly.\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='local-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-inet:as-number', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'local_as must be of a type compatible with oc-inet:as-number', 'defined-type': 'oc-inet:as-number', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="local-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-inet:as-number\', is_config=True)'}) self.__local_as = t if hasattr(self, '_set'): self._set()
def _set_local_as(self, v, load=False): '\n Setter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_local_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_local_as() directly.\n\n YANG Description: The local autonomous system number that is to be used\nwhen establishing sessions with the remote peer or peer\ngroup, if this differs from the global BGP router\nautonomous system number.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name='local-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-inet:as-number', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'local_as must be of a type compatible with oc-inet:as-number', 'defined-type': 'oc-inet:as-number', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={\'range\': [\'0..4294967295\']}, int_size=32), is_leaf=True, yang_name="local-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-inet:as-number\', is_config=True)'}) self.__local_as = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for local_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/local_as (oc-inet:as-number) If this variable is read-only (config: false) in the source YANG file, then _set_local_as is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_local_as() directly. YANG Description: The local autonomous system number that is to be used when establishing sessions with the remote peer or peer group, if this differs from the global BGP router autonomous system number.<|endoftext|>
eb806ed21b17b2189a96d7abe36ee71860c3058168a1d4630cc962523fd2dc94
def _get_peer_type(self): '\n Getter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' return self.__peer_type
Getter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type) YANG Description: Explicitly designate the peer or peer group as internal (iBGP) or external (eBGP).
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_peer_type
ckishimo/napalm-yang
64
python
def _get_peer_type(self): '\n Getter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' return self.__peer_type
def _get_peer_type(self): '\n Getter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' return self.__peer_type<|docstring|>Getter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type) YANG Description: Explicitly designate the peer or peer group as internal (iBGP) or external (eBGP).<|endoftext|>
d3d5b2987b8079fd02ad0a2295c9f9a3b65d1b2ab2dc2a7b9ffe6b9aa00661b9
def _set_peer_type(self, v, load=False): '\n Setter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_peer_type is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_peer_type() directly.\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'INTERNAL': {}, 'EXTERNAL': {}}), is_leaf=True, yang_name='peer-type', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:peer-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'peer_type must be of a type compatible with oc-bgp-types:peer-type', 'defined-type': 'oc-bgp-types:peer-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'INTERNAL\': {}, \'EXTERNAL\': {}},), is_leaf=True, yang_name="peer-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:peer-type\', is_config=True)'}) self.__peer_type = t if hasattr(self, '_set'): self._set()
Setter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type) If this variable is read-only (config: false) in the source YANG file, then _set_peer_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_peer_type() directly. YANG Description: Explicitly designate the peer or peer group as internal (iBGP) or external (eBGP).
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_peer_type
ckishimo/napalm-yang
64
python
def _set_peer_type(self, v, load=False): '\n Setter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_peer_type is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_peer_type() directly.\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'INTERNAL': {}, 'EXTERNAL': {}}), is_leaf=True, yang_name='peer-type', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:peer-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'peer_type must be of a type compatible with oc-bgp-types:peer-type', 'defined-type': 'oc-bgp-types:peer-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'INTERNAL\': {}, \'EXTERNAL\': {}},), is_leaf=True, yang_name="peer-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:peer-type\', is_config=True)'}) self.__peer_type = t if hasattr(self, '_set'): self._set()
def _set_peer_type(self, v, load=False): '\n Setter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_peer_type is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_peer_type() directly.\n\n YANG Description: Explicitly designate the peer or peer group as internal\n(iBGP) or external (eBGP).\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'INTERNAL': {}, 'EXTERNAL': {}}), is_leaf=True, yang_name='peer-type', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:peer-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'peer_type must be of a type compatible with oc-bgp-types:peer-type', 'defined-type': 'oc-bgp-types:peer-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'INTERNAL\': {}, \'EXTERNAL\': {}},), is_leaf=True, yang_name="peer-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:peer-type\', is_config=True)'}) self.__peer_type = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for peer_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/peer_type (oc-bgp-types:peer-type) If this variable is read-only (config: false) in the source YANG file, then _set_peer_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_peer_type() directly. YANG Description: Explicitly designate the peer or peer group as internal (iBGP) or external (eBGP).<|endoftext|>
c49abcb46396dc99570e882300ad82fa41e6a72c38d8008b5cc395506c383ef5
def _get_auth_password(self): '\n Getter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' return self.__auth_password
Getter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password) YANG Description: Configures an MD5 authentication password for use with neighboring devices.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_auth_password
ckishimo/napalm-yang
64
python
def _get_auth_password(self): '\n Getter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' return self.__auth_password
def _get_auth_password(self): '\n Getter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' return self.__auth_password<|docstring|>Getter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password) YANG Description: Configures an MD5 authentication password for use with neighboring devices.<|endoftext|>
401b130d449c32655b912d3c0614c07e94e5546569f6db05c544048471567a02
def _set_auth_password(self, v, load=False): '\n Setter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_auth_password is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_auth_password() directly.\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='auth-password', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-types:routing-password', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'auth_password must be of a type compatible with oc-types:routing-password', 'defined-type': 'oc-types:routing-password', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="auth-password", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-types:routing-password\', is_config=True)'}) self.__auth_password = t if hasattr(self, '_set'): self._set()
Setter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password) If this variable is read-only (config: false) in the source YANG file, then _set_auth_password is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_auth_password() directly. YANG Description: Configures an MD5 authentication password for use with neighboring devices.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_auth_password
ckishimo/napalm-yang
64
python
def _set_auth_password(self, v, load=False): '\n Setter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_auth_password is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_auth_password() directly.\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='auth-password', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-types:routing-password', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'auth_password must be of a type compatible with oc-types:routing-password', 'defined-type': 'oc-types:routing-password', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="auth-password", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-types:routing-password\', is_config=True)'}) self.__auth_password = t if hasattr(self, '_set'): self._set()
def _set_auth_password(self, v, load=False): '\n Setter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_auth_password is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_auth_password() directly.\n\n YANG Description: Configures an MD5 authentication password for use with\nneighboring devices.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='auth-password', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-types:routing-password', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'auth_password must be of a type compatible with oc-types:routing-password', 'defined-type': 'oc-types:routing-password', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="auth-password", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-types:routing-password\', is_config=True)'}) self.__auth_password = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for auth_password, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/auth_password (oc-types:routing-password) If this variable is read-only (config: false) in the source YANG file, then _set_auth_password is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_auth_password() directly. YANG Description: Configures an MD5 authentication password for use with neighboring devices.<|endoftext|>
d893062721e5a3fd147c261456aeef656854784c3cb5fa7bea6df33a756ca117
def _get_remove_private_as(self): '\n Getter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' return self.__remove_private_as
Getter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option) YANG Description: Remove private AS numbers from updates sent to peers - when this leaf is not specified, the AS_PATH attribute should be sent to the peer unchanged
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_remove_private_as
ckishimo/napalm-yang
64
python
def _get_remove_private_as(self): '\n Getter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' return self.__remove_private_as
def _get_remove_private_as(self): '\n Getter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' return self.__remove_private_as<|docstring|>Getter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option) YANG Description: Remove private AS numbers from updates sent to peers - when this leaf is not specified, the AS_PATH attribute should be sent to the peer unchanged<|endoftext|>
d76899ed4f273fcc21b967d3c6af7610f32e86fc12133cdbb530a1ffdce15ae1
def _set_remove_private_as(self, v, load=False): '\n Setter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_remove_private_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_remove_private_as() directly.\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}}), is_leaf=True, yang_name='remove-private-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:remove-private-as-option', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'remove_private_as must be of a type compatible with oc-bgp-types:remove-private-as-option', 'defined-type': 'oc-bgp-types:remove-private-as-option', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}},), is_leaf=True, yang_name="remove-private-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:remove-private-as-option\', is_config=True)'}) self.__remove_private_as = t if hasattr(self, '_set'): self._set()
Setter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option) If this variable is read-only (config: false) in the source YANG file, then _set_remove_private_as is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_remove_private_as() directly. YANG Description: Remove private AS numbers from updates sent to peers - when this leaf is not specified, the AS_PATH attribute should be sent to the peer unchanged
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_remove_private_as
ckishimo/napalm-yang
64
python
def _set_remove_private_as(self, v, load=False): '\n Setter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_remove_private_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_remove_private_as() directly.\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}}), is_leaf=True, yang_name='remove-private-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:remove-private-as-option', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'remove_private_as must be of a type compatible with oc-bgp-types:remove-private-as-option', 'defined-type': 'oc-bgp-types:remove-private-as-option', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}},), is_leaf=True, yang_name="remove-private-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:remove-private-as-option\', is_config=True)'}) self.__remove_private_as = t if hasattr(self, '_set'): self._set()
def _set_remove_private_as(self, v, load=False): '\n Setter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_remove_private_as is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_remove_private_as() directly.\n\n YANG Description: Remove private AS numbers from updates sent to peers - when\nthis leaf is not specified, the AS_PATH attribute should be\nsent to the peer unchanged\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REMOVE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}, 'oc-bgp-types:PRIVATE_AS_REPLACE_ALL': {'@module': 'openconfig-bgp-types', '@namespace': 'http://openconfig.net/yang/bgp-types'}}), is_leaf=True, yang_name='remove-private-as', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:remove-private-as-option', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'remove_private_as must be of a type compatible with oc-bgp-types:remove-private-as-option', 'defined-type': 'oc-bgp-types:remove-private-as-option', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REMOVE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}, \'oc-bgp-types:PRIVATE_AS_REPLACE_ALL\': {\'@module\': \'openconfig-bgp-types\', \'@namespace\': \'http://openconfig.net/yang/bgp-types\'}},), is_leaf=True, yang_name="remove-private-as", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:remove-private-as-option\', is_config=True)'}) self.__remove_private_as = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for remove_private_as, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/remove_private_as (oc-bgp-types:remove-private-as-option) If this variable is read-only (config: false) in the source YANG file, then _set_remove_private_as is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_remove_private_as() directly. YANG Description: Remove private AS numbers from updates sent to peers - when this leaf is not specified, the AS_PATH attribute should be sent to the peer unchanged<|endoftext|>
d5c581c25d849a1453e2a27227a99dfcfc522d012cbc331c93574ebf60c13e69
def _get_route_flap_damping(self): '\n Getter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n\n YANG Description: Enable route flap damping.\n ' return self.__route_flap_damping
Getter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean) YANG Description: Enable route flap damping.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_route_flap_damping
ckishimo/napalm-yang
64
python
def _get_route_flap_damping(self): '\n Getter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n\n YANG Description: Enable route flap damping.\n ' return self.__route_flap_damping
def _get_route_flap_damping(self): '\n Getter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n\n YANG Description: Enable route flap damping.\n ' return self.__route_flap_damping<|docstring|>Getter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean) YANG Description: Enable route flap damping.<|endoftext|>
515a8f221a6c2f33136e65d5d8a735ff18c1bb1e4ef62ee971544214d8bd6710
def _set_route_flap_damping(self, v, load=False): '\n Setter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_route_flap_damping is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_route_flap_damping() directly.\n\n YANG Description: Enable route flap damping.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=YANGBool, default=YANGBool('false'), is_leaf=True, yang_name='route-flap-damping', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'route_flap_damping must be of a type compatible with boolean', 'defined-type': 'boolean', 'generated-type': 'YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="route-flap-damping", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'boolean\', is_config=True)'}) self.__route_flap_damping = t if hasattr(self, '_set'): self._set()
Setter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_route_flap_damping is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_route_flap_damping() directly. YANG Description: Enable route flap damping.
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_route_flap_damping
ckishimo/napalm-yang
64
python
def _set_route_flap_damping(self, v, load=False): '\n Setter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_route_flap_damping is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_route_flap_damping() directly.\n\n YANG Description: Enable route flap damping.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=YANGBool, default=YANGBool('false'), is_leaf=True, yang_name='route-flap-damping', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'route_flap_damping must be of a type compatible with boolean', 'defined-type': 'boolean', 'generated-type': 'YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="route-flap-damping", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'boolean\', is_config=True)'}) self.__route_flap_damping = t if hasattr(self, '_set'): self._set()
def _set_route_flap_damping(self, v, load=False): '\n Setter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_route_flap_damping is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_route_flap_damping() directly.\n\n YANG Description: Enable route flap damping.\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=YANGBool, default=YANGBool('false'), is_leaf=True, yang_name='route-flap-damping', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='boolean', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'route_flap_damping must be of a type compatible with boolean', 'defined-type': 'boolean', 'generated-type': 'YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="route-flap-damping", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'boolean\', is_config=True)'}) self.__route_flap_damping = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for route_flap_damping, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/route_flap_damping (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_route_flap_damping is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_route_flap_damping() directly. YANG Description: Enable route flap damping.<|endoftext|>
dbf6c96a4637c9a3755853e0476965a2fbcbd3170a369fd82d01f779aaaac676
def _get_send_community(self): '\n Getter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' return self.__send_community
Getter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type) YANG Description: Specify which types of community should be sent to the neighbor or group. The default is to not send the community attribute
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_send_community
ckishimo/napalm-yang
64
python
def _get_send_community(self): '\n Getter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' return self.__send_community
def _get_send_community(self): '\n Getter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' return self.__send_community<|docstring|>Getter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type) YANG Description: Specify which types of community should be sent to the neighbor or group. The default is to not send the community attribute<|endoftext|>
fd1fed6de97115fdb7eea2724329f40d9875d2a2be74ac26219afb0d188207dc
def _set_send_community(self, v, load=False): '\n Setter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_send_community is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_send_community() directly.\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'STANDARD': {}, 'EXTENDED': {}, 'BOTH': {}, 'NONE': {}}), default=six.text_type('NONE'), is_leaf=True, yang_name='send-community', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:community-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'send_community must be of a type compatible with oc-bgp-types:community-type', 'defined-type': 'oc-bgp-types:community-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'STANDARD\': {}, \'EXTENDED\': {}, \'BOTH\': {}, \'NONE\': {}},), default=six.text_type("NONE"), is_leaf=True, yang_name="send-community", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:community-type\', is_config=True)'}) self.__send_community = t if hasattr(self, '_set'): self._set()
Setter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type) If this variable is read-only (config: false) in the source YANG file, then _set_send_community is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_send_community() directly. YANG Description: Specify which types of community should be sent to the neighbor or group. The default is to not send the community attribute
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_send_community
ckishimo/napalm-yang
64
python
def _set_send_community(self, v, load=False): '\n Setter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_send_community is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_send_community() directly.\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'STANDARD': {}, 'EXTENDED': {}, 'BOTH': {}, 'NONE': {}}), default=six.text_type('NONE'), is_leaf=True, yang_name='send-community', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:community-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'send_community must be of a type compatible with oc-bgp-types:community-type', 'defined-type': 'oc-bgp-types:community-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'STANDARD\': {}, \'EXTENDED\': {}, \'BOTH\': {}, \'NONE\': {}},), default=six.text_type("NONE"), is_leaf=True, yang_name="send-community", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:community-type\', is_config=True)'}) self.__send_community = t if hasattr(self, '_set'): self._set()
def _set_send_community(self, v, load=False): '\n Setter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_send_community is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_send_community() directly.\n\n YANG Description: Specify which types of community should be sent to the\nneighbor or group. The default is to not send the\ncommunity attribute\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=RestrictedClassType(base_type=six.text_type, restriction_type='dict_key', restriction_arg={'STANDARD': {}, 'EXTENDED': {}, 'BOTH': {}, 'NONE': {}}), default=six.text_type('NONE'), is_leaf=True, yang_name='send-community', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-bgp-types:community-type', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'send_community must be of a type compatible with oc-bgp-types:community-type', 'defined-type': 'oc-bgp-types:community-type', 'generated-type': 'YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={\'STANDARD\': {}, \'EXTENDED\': {}, \'BOTH\': {}, \'NONE\': {}},), default=six.text_type("NONE"), is_leaf=True, yang_name="send-community", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'oc-bgp-types:community-type\', is_config=True)'}) self.__send_community = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for send_community, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/send_community (oc-bgp-types:community-type) If this variable is read-only (config: false) in the source YANG file, then _set_send_community is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_send_community() directly. YANG Description: Specify which types of community should be sent to the neighbor or group. The default is to not send the community attribute<|endoftext|>
43dda6c2cbd15f2655f3e5ed76d3a53219eefffe845436a82a6e875c7513c00f
def _get_description(self): '\n Getter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' return self.__description
Getter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string) YANG Description: An optional textual description (intended primarily for use with a peer or group
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_get_description
ckishimo/napalm-yang
64
python
def _get_description(self): '\n Getter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' return self.__description
def _get_description(self): '\n Getter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' return self.__description<|docstring|>Getter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string) YANG Description: An optional textual description (intended primarily for use with a peer or group<|endoftext|>
4a27a8cc277b015984484b497f2da4d64a64059335273d5d44f0c6aaea9cf7ea
def _set_description(self, v, load=False): '\n Setter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_description is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_description() directly.\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='description', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'description must be of a type compatible with string', 'defined-type': 'string', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="description", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'string\', is_config=True)'}) self.__description = t if hasattr(self, '_set'): self._set()
Setter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string) If this variable is read-only (config: false) in the source YANG file, then _set_description is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_description() directly. YANG Description: An optional textual description (intended primarily for use with a peer or group
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/__init__.py
_set_description
ckishimo/napalm-yang
64
python
def _set_description(self, v, load=False): '\n Setter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_description is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_description() directly.\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='description', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'description must be of a type compatible with string', 'defined-type': 'string', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="description", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'string\', is_config=True)'}) self.__description = t if hasattr(self, '_set'): self._set()
def _set_description(self, v, load=False): '\n Setter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_description is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_description() directly.\n\n YANG Description: An optional textual description (intended primarily for use\nwith a peer or group\n ' if hasattr(v, '_utype'): v = v._utype(v) try: t = YANGDynClass(v, base=six.text_type, is_leaf=True, yang_name='description', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='string', is_config=True) except (TypeError, ValueError): raise ValueError({'error-string': 'description must be of a type compatible with string', 'defined-type': 'string', 'generated-type': 'YANGDynClass(base=six.text_type, is_leaf=True, yang_name="description", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'string\', is_config=True)'}) self.__description = t if hasattr(self, '_set'): self._set()<|docstring|>Setter method for description, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/config/description (string) If this variable is read-only (config: false) in the source YANG file, then _set_description is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_description() directly. YANG Description: An optional textual description (intended primarily for use with a peer or group<|endoftext|>
6cbab63dd17f5b0b87da8715c9b9e0beba4f21396871a1babd66bece0896e5ac
def parse_args(): '\n Parse command line arguments.\n Returns:\n Parsed arguments.\n ' ap = argparse.ArgumentParser() ap.add_argument('-c', '--camera', default=0, help='camera id or path to a video file') return vars(ap.parse_args())
Parse command line arguments. Returns: Parsed arguments.
video_stream_detection.py
parse_args
piotrekm7/FaceDetectionAndLifeStageClassification
0
python
def parse_args(): '\n Parse command line arguments.\n Returns:\n Parsed arguments.\n ' ap = argparse.ArgumentParser() ap.add_argument('-c', '--camera', default=0, help='camera id or path to a video file') return vars(ap.parse_args())
def parse_args(): '\n Parse command line arguments.\n Returns:\n Parsed arguments.\n ' ap = argparse.ArgumentParser() ap.add_argument('-c', '--camera', default=0, help='camera id or path to a video file') return vars(ap.parse_args())<|docstring|>Parse command line arguments. Returns: Parsed arguments.<|endoftext|>
769bb45e7f0213542bfbaf41ba5efabb1189686fd4e8ef694d0c24b4f0e60f7b
def main(): '\n Runs face detection and life stage classification on video and displays the results.\n ' args = parse_args() cap = cv2.VideoCapture(args['camera']) image_processor = prepare_processing_engines() while True: (_, frame) = cap.read() processed_image = image_processor(frame) cv2.imshow('Output', processed_image) if ((cv2.waitKey(1) & 255) == ord('q')): break
Runs face detection and life stage classification on video and displays the results.
video_stream_detection.py
main
piotrekm7/FaceDetectionAndLifeStageClassification
0
python
def main(): '\n \n ' args = parse_args() cap = cv2.VideoCapture(args['camera']) image_processor = prepare_processing_engines() while True: (_, frame) = cap.read() processed_image = image_processor(frame) cv2.imshow('Output', processed_image) if ((cv2.waitKey(1) & 255) == ord('q')): break
def main(): '\n \n ' args = parse_args() cap = cv2.VideoCapture(args['camera']) image_processor = prepare_processing_engines() while True: (_, frame) = cap.read() processed_image = image_processor(frame) cv2.imshow('Output', processed_image) if ((cv2.waitKey(1) & 255) == ord('q')): break<|docstring|>Runs face detection and life stage classification on video and displays the results.<|endoftext|>
4d0702913c4e2b8711237eb9104ab495b82f7bb93df323dacf62bd0af526b4a7
@prepare.command(context_settings=dict(show_default=True)) @click.argument('corpus_dir', type=click.Path(exists=True, dir_okay=True)) @click.argument('output_dir', type=click.Path()) @click.option('--mic', type=click.Choice(['near', 'far']), default='far') def ali_meeting(corpus_dir: Pathlike, output_dir: Pathlike, mic: str): 'AliMeeting data preparation.' prepare_ali_meeting(corpus_dir, output_dir=output_dir, mic=mic)
AliMeeting data preparation.
lhotse/bin/modes/recipes/ali_meeting.py
ali_meeting
marcinwitkowski/lhotse
64
python
@prepare.command(context_settings=dict(show_default=True)) @click.argument('corpus_dir', type=click.Path(exists=True, dir_okay=True)) @click.argument('output_dir', type=click.Path()) @click.option('--mic', type=click.Choice(['near', 'far']), default='far') def ali_meeting(corpus_dir: Pathlike, output_dir: Pathlike, mic: str): prepare_ali_meeting(corpus_dir, output_dir=output_dir, mic=mic)
@prepare.command(context_settings=dict(show_default=True)) @click.argument('corpus_dir', type=click.Path(exists=True, dir_okay=True)) @click.argument('output_dir', type=click.Path()) @click.option('--mic', type=click.Choice(['near', 'far']), default='far') def ali_meeting(corpus_dir: Pathlike, output_dir: Pathlike, mic: str): prepare_ali_meeting(corpus_dir, output_dir=output_dir, mic=mic)<|docstring|>AliMeeting data preparation.<|endoftext|>
030aa5c465e6c5e0ad9714b250d293a9055e4cc16473074d3f8632b509f35208
@download.command(context_settings=dict(show_default=True)) @click.argument('target_dir', type=click.Path()) @click.option('--force-download', is_flag=True, default=False) def ali_meeting(target_dir: Pathlike, force_download: bool): 'AliMeeting download.' download_ali_meeting(target_dir, force_download=force_download)
AliMeeting download.
lhotse/bin/modes/recipes/ali_meeting.py
ali_meeting
marcinwitkowski/lhotse
64
python
@download.command(context_settings=dict(show_default=True)) @click.argument('target_dir', type=click.Path()) @click.option('--force-download', is_flag=True, default=False) def ali_meeting(target_dir: Pathlike, force_download: bool): download_ali_meeting(target_dir, force_download=force_download)
@download.command(context_settings=dict(show_default=True)) @click.argument('target_dir', type=click.Path()) @click.option('--force-download', is_flag=True, default=False) def ali_meeting(target_dir: Pathlike, force_download: bool): download_ali_meeting(target_dir, force_download=force_download)<|docstring|>AliMeeting download.<|endoftext|>
9a42ee622bec63bdbf00eda8347d1986c789491684a8b2b45f7e87d73e819c98
def levenshtein(a, b): 'Computes the Levenshtein distance between a and b.' (n, m) = (len(a), len(b)) if (n > m): (a, b) = (b, a) (n, m) = (m, n) current = range((n + 1)) for i in range(1, (m + 1)): (previous, current) = (current, ([i] + ([0] * n))) for j in range(1, (n + 1)): (add, delete) = ((previous[j] + 1), (current[(j - 1)] + 1)) change = previous[(j - 1)] if (a[(j - 1)] != b[(i - 1)]): change = (change + 1) current[j] = min(add, delete, change) return current[n]
Computes the Levenshtein distance between a and b.
ctc_utils.py
levenshtein
tandr3i/tf-end-to-end
71
python
def levenshtein(a, b): (n, m) = (len(a), len(b)) if (n > m): (a, b) = (b, a) (n, m) = (m, n) current = range((n + 1)) for i in range(1, (m + 1)): (previous, current) = (current, ([i] + ([0] * n))) for j in range(1, (n + 1)): (add, delete) = ((previous[j] + 1), (current[(j - 1)] + 1)) change = previous[(j - 1)] if (a[(j - 1)] != b[(i - 1)]): change = (change + 1) current[j] = min(add, delete, change) return current[n]
def levenshtein(a, b): (n, m) = (len(a), len(b)) if (n > m): (a, b) = (b, a) (n, m) = (m, n) current = range((n + 1)) for i in range(1, (m + 1)): (previous, current) = (current, ([i] + ([0] * n))) for j in range(1, (n + 1)): (add, delete) = ((previous[j] + 1), (current[(j - 1)] + 1)) change = previous[(j - 1)] if (a[(j - 1)] != b[(i - 1)]): change = (change + 1) current[j] = min(add, delete, change) return current[n]<|docstring|>Computes the Levenshtein distance between a and b.<|endoftext|>
51001d8f3f47f99a3cf4f77b1c2c13c6e8256b895cd5b677f63f7c2b48356fb4
def setup_basic_api_response(services=None, empty_resp=False, empty_val=False, status=200): "\n If `empty_resp', we return a totally empty API response, except for any\n error message.\n\n If `empty_val', the tz_key is an empty string.\n " if (services is None): services = FAKE_SERVICES for service in services: url_regex = re.compile(service.url.format(ip='.*')) api_body = {} if (not empty_resp): cur_level = api_body for (i, key) in enumerate(service.tz_keys, start=1): if (i == len(service.tz_keys)): if empty_val: cur_level[key] = '' else: cur_level[key] = FAKE_TIMEZONE else: cur_level[key] = {} cur_level = cur_level[key] tmp = {} if service.error_keys: for (i, key) in enumerate(reversed(service.error_keys)): if (i == 0): tmp[key] = FAKE_ERROR else: tmp[key] = tmp.copy() httpretty.register_uri(httpretty.GET, url_regex, body=json.dumps(api_body), content_type='application/json', status=status)
If `empty_resp', we return a totally empty API response, except for any error message. If `empty_val', the tz_key is an empty string.
tests/_test_utils.py
setup_basic_api_response
cdown/tzupdate
143
python
def setup_basic_api_response(services=None, empty_resp=False, empty_val=False, status=200): "\n If `empty_resp', we return a totally empty API response, except for any\n error message.\n\n If `empty_val', the tz_key is an empty string.\n " if (services is None): services = FAKE_SERVICES for service in services: url_regex = re.compile(service.url.format(ip='.*')) api_body = {} if (not empty_resp): cur_level = api_body for (i, key) in enumerate(service.tz_keys, start=1): if (i == len(service.tz_keys)): if empty_val: cur_level[key] = else: cur_level[key] = FAKE_TIMEZONE else: cur_level[key] = {} cur_level = cur_level[key] tmp = {} if service.error_keys: for (i, key) in enumerate(reversed(service.error_keys)): if (i == 0): tmp[key] = FAKE_ERROR else: tmp[key] = tmp.copy() httpretty.register_uri(httpretty.GET, url_regex, body=json.dumps(api_body), content_type='application/json', status=status)
def setup_basic_api_response(services=None, empty_resp=False, empty_val=False, status=200): "\n If `empty_resp', we return a totally empty API response, except for any\n error message.\n\n If `empty_val', the tz_key is an empty string.\n " if (services is None): services = FAKE_SERVICES for service in services: url_regex = re.compile(service.url.format(ip='.*')) api_body = {} if (not empty_resp): cur_level = api_body for (i, key) in enumerate(service.tz_keys, start=1): if (i == len(service.tz_keys)): if empty_val: cur_level[key] = else: cur_level[key] = FAKE_TIMEZONE else: cur_level[key] = {} cur_level = cur_level[key] tmp = {} if service.error_keys: for (i, key) in enumerate(reversed(service.error_keys)): if (i == 0): tmp[key] = FAKE_ERROR else: tmp[key] = tmp.copy() httpretty.register_uri(httpretty.GET, url_regex, body=json.dumps(api_body), content_type='application/json', status=status)<|docstring|>If `empty_resp', we return a totally empty API response, except for any error message. If `empty_val', the tz_key is an empty string.<|endoftext|>
cdb1731897e28a6b7b4144c262798dee1458a5c08e46cb2b52b48221d061fa98
def __init__(self, *args, **kwargs): 'Initialises the Listbox object.\n\n Args:\n\n * ``contents``: listbox contents\n * ``i``, ``o``: input&output device objects\n\n Kwargs:\n\n * ``name``: listbox name which can be used internally and for debugging.\n * ``selected``: value (that is, ``entry[1]``) of the element to be selected. If no element with this value is found, this is ignored.\n * ``entry_height``: number of display rows one listbox entry occupies.\n * ``append_exit``: appends an "Exit" entry to listbox.\n\n ' selected = kwargs.pop('selected', None) exitable = kwargs.pop('exitable', None) BaseListUIElement.__init__(self, *args, **kwargs) if (len(self.contents) == 0): raise ValueError("A listbox can't be empty!") if selected: self.go_to_value(selected) if exitable: logger.warning("Listbox ignores the 'exitable' argument!")
Initialises the Listbox object. Args: * ``contents``: listbox contents * ``i``, ``o``: input&output device objects Kwargs: * ``name``: listbox name which can be used internally and for debugging. * ``selected``: value (that is, ``entry[1]``) of the element to be selected. If no element with this value is found, this is ignored. * ``entry_height``: number of display rows one listbox entry occupies. * ``append_exit``: appends an "Exit" entry to listbox.
ui/listbox.py
__init__
hpagseddy/ZPUI
0
python
def __init__(self, *args, **kwargs): 'Initialises the Listbox object.\n\n Args:\n\n * ``contents``: listbox contents\n * ``i``, ``o``: input&output device objects\n\n Kwargs:\n\n * ``name``: listbox name which can be used internally and for debugging.\n * ``selected``: value (that is, ``entry[1]``) of the element to be selected. If no element with this value is found, this is ignored.\n * ``entry_height``: number of display rows one listbox entry occupies.\n * ``append_exit``: appends an "Exit" entry to listbox.\n\n ' selected = kwargs.pop('selected', None) exitable = kwargs.pop('exitable', None) BaseListUIElement.__init__(self, *args, **kwargs) if (len(self.contents) == 0): raise ValueError("A listbox can't be empty!") if selected: self.go_to_value(selected) if exitable: logger.warning("Listbox ignores the 'exitable' argument!")
def __init__(self, *args, **kwargs): 'Initialises the Listbox object.\n\n Args:\n\n * ``contents``: listbox contents\n * ``i``, ``o``: input&output device objects\n\n Kwargs:\n\n * ``name``: listbox name which can be used internally and for debugging.\n * ``selected``: value (that is, ``entry[1]``) of the element to be selected. If no element with this value is found, this is ignored.\n * ``entry_height``: number of display rows one listbox entry occupies.\n * ``append_exit``: appends an "Exit" entry to listbox.\n\n ' selected = kwargs.pop('selected', None) exitable = kwargs.pop('exitable', None) BaseListUIElement.__init__(self, *args, **kwargs) if (len(self.contents) == 0): raise ValueError("A listbox can't be empty!") if selected: self.go_to_value(selected) if exitable: logger.warning("Listbox ignores the 'exitable' argument!")<|docstring|>Initialises the Listbox object. Args: * ``contents``: listbox contents * ``i``, ``o``: input&output device objects Kwargs: * ``name``: listbox name which can be used internally and for debugging. * ``selected``: value (that is, ``entry[1]``) of the element to be selected. If no element with this value is found, this is ignored. * ``entry_height``: number of display rows one listbox entry occupies. * ``append_exit``: appends an "Exit" entry to listbox.<|endoftext|>
d82f90e4c57dc87ae1ac4c94b1156451977817167d1615cc7aa00376f146ca80
@to_be_foreground def select_entry(self): " Gets the currently specified entry's index and sets it as selected_entry attribute.\n |Is typically used as a callback from input event processing thread." logger.debug('entry selected') self.selected_entry = self.pointer self.deactivate()
Gets the currently specified entry's index and sets it as selected_entry attribute. |Is typically used as a callback from input event processing thread.
ui/listbox.py
select_entry
hpagseddy/ZPUI
0
python
@to_be_foreground def select_entry(self): " Gets the currently specified entry's index and sets it as selected_entry attribute.\n |Is typically used as a callback from input event processing thread." logger.debug('entry selected') self.selected_entry = self.pointer self.deactivate()
@to_be_foreground def select_entry(self): " Gets the currently specified entry's index and sets it as selected_entry attribute.\n |Is typically used as a callback from input event processing thread." logger.debug('entry selected') self.selected_entry = self.pointer self.deactivate()<|docstring|>Gets the currently specified entry's index and sets it as selected_entry attribute. |Is typically used as a callback from input event processing thread.<|endoftext|>
ff11af7f9638a7638ba10919fe18e67fcc125c84f3f579c6e4b3e184b12a6a55
def go_to_value(self, value): '\n Moves the pointer to the first entry which has the value passed.\n ' for (i, entry) in enumerate(self.contents): if isinstance(entry, Entry): if ((entry.name == value) or ((entry.name is None) and (entry.text == value))): self.start_pointer = i return elif (((len(entry) > 1) and (entry[1] == value)) or (entry[0] == value)): self.start_pointer = i return
Moves the pointer to the first entry which has the value passed.
ui/listbox.py
go_to_value
hpagseddy/ZPUI
0
python
def go_to_value(self, value): '\n \n ' for (i, entry) in enumerate(self.contents): if isinstance(entry, Entry): if ((entry.name == value) or ((entry.name is None) and (entry.text == value))): self.start_pointer = i return elif (((len(entry) > 1) and (entry[1] == value)) or (entry[0] == value)): self.start_pointer = i return
def go_to_value(self, value): '\n \n ' for (i, entry) in enumerate(self.contents): if isinstance(entry, Entry): if ((entry.name == value) or ((entry.name is None) and (entry.text == value))): self.start_pointer = i return elif (((len(entry) > 1) and (entry[1] == value)) or (entry[0] == value)): self.start_pointer = i return<|docstring|>Moves the pointer to the first entry which has the value passed.<|endoftext|>
25d47ffeb77723a5f6b40bc2735505edde9d3ac78208f6bf2cf2fdf457d8e77a
def test_create_user_with_email_successful(self): 'Create a new user with the email\n ' email = 'example@example.com' password = '1234567' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))
Create a new user with the email
app/core/tests/test_models.py
test_create_user_with_email_successful
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_create_user_with_email_successful(self): '\n ' email = 'example@example.com' password = '1234567' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))
def test_create_user_with_email_successful(self): '\n ' email = 'example@example.com' password = '1234567' user = get_user_model().objects.create_user(email=email, password=password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password))<|docstring|>Create a new user with the email<|endoftext|>
4637907653ef9393350212a7efc77b988c77ae9713f7b31fa43ef9adb96563d9
def test_new_user_email_normalized(self): 'Test the email for the new user normalized\n ' email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='12121212') self.assertEqual(user.email, email.lower())
Test the email for the new user normalized
app/core/tests/test_models.py
test_new_user_email_normalized
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_new_user_email_normalized(self): '\n ' email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='12121212') self.assertEqual(user.email, email.lower())
def test_new_user_email_normalized(self): '\n ' email = 'example@example.com' user = get_user_model().objects.create_user(email=email, password='12121212') self.assertEqual(user.email, email.lower())<|docstring|>Test the email for the new user normalized<|endoftext|>
691df9916d9086a3c07f68cd244d39ebaaeda5c21d34b90bb7e1b1d3912a6b34
def test_new_user_invalid_email(self): 'Test creating a user with no email\n ' with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test1234')
Test creating a user with no email
app/core/tests/test_models.py
test_new_user_invalid_email
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_new_user_invalid_email(self): '\n ' with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test1234')
def test_new_user_invalid_email(self): '\n ' with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test1234')<|docstring|>Test creating a user with no email<|endoftext|>
22f8e1ff05029d107692784a68139886d06bdedf442996540472f91fc24f7b57
def test_tag_str(self): 'Test the tag string representation\n ' tag = Tag.objects.create(user=sample_user(), name='Vegan') self.assertEqual(str(tag), tag.name)
Test the tag string representation
app/core/tests/test_models.py
test_tag_str
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_tag_str(self): '\n ' tag = Tag.objects.create(user=sample_user(), name='Vegan') self.assertEqual(str(tag), tag.name)
def test_tag_str(self): '\n ' tag = Tag.objects.create(user=sample_user(), name='Vegan') self.assertEqual(str(tag), tag.name)<|docstring|>Test the tag string representation<|endoftext|>
6605d8cf4d48792aa5c34031131f9a8aa20b88c957372e6a949a348d686f1f2d
def test_ingredient_str(self): 'Test the ingredient string representation\n ' ingredient = Ingredient.objects.create(user=sample_user(), name='Coco') self.assertEqual(str(ingredient), ingredient.name)
Test the ingredient string representation
app/core/tests/test_models.py
test_ingredient_str
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_ingredient_str(self): '\n ' ingredient = Ingredient.objects.create(user=sample_user(), name='Coco') self.assertEqual(str(ingredient), ingredient.name)
def test_ingredient_str(self): '\n ' ingredient = Ingredient.objects.create(user=sample_user(), name='Coco') self.assertEqual(str(ingredient), ingredient.name)<|docstring|>Test the ingredient string representation<|endoftext|>
0eba45e783c6ce7ed27b3c48e2faafd957a6c6f20e80773a87d978c42524ae9c
def test_recipe_str(self): 'Test converting the recipe representation\n ' recipe = Recipe.objects.create(user=sample_user(), title='Salad', time_minutes=5, price=12.0) self.assertEqual(str(recipe), recipe.title)
Test converting the recipe representation
app/core/tests/test_models.py
test_recipe_str
MauricioAntonioMartinez/django-workout-tracker-api
0
python
def test_recipe_str(self): '\n ' recipe = Recipe.objects.create(user=sample_user(), title='Salad', time_minutes=5, price=12.0) self.assertEqual(str(recipe), recipe.title)
def test_recipe_str(self): '\n ' recipe = Recipe.objects.create(user=sample_user(), title='Salad', time_minutes=5, price=12.0) self.assertEqual(str(recipe), recipe.title)<|docstring|>Test converting the recipe representation<|endoftext|>
bb35ef98ae1fca9fe31f91ab339ce5efab6d14990cd6f38b00fb86f2b3ab3d16
@patch('uuid.uuid4') def test_recipe_file_name_uuid(self, mock_uuid): 'Test that image is saved in the corrent location\n ' uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = recipe_image_file_path(None, 'myimage.jpg') exp_path = f'uploads/recipe/{uuid}.jpg' self.assertEqual(file_path, exp_path)
Test that image is saved in the corrent location
app/core/tests/test_models.py
test_recipe_file_name_uuid
MauricioAntonioMartinez/django-workout-tracker-api
0
python
@patch('uuid.uuid4') def test_recipe_file_name_uuid(self, mock_uuid): '\n ' uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = recipe_image_file_path(None, 'myimage.jpg') exp_path = f'uploads/recipe/{uuid}.jpg' self.assertEqual(file_path, exp_path)
@patch('uuid.uuid4') def test_recipe_file_name_uuid(self, mock_uuid): '\n ' uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = recipe_image_file_path(None, 'myimage.jpg') exp_path = f'uploads/recipe/{uuid}.jpg' self.assertEqual(file_path, exp_path)<|docstring|>Test that image is saved in the corrent location<|endoftext|>
51c187456cfa825c1465f779ca3594b3b02fb8144fce78bdb963c5a9b20c9bef
def stations_by_distance(stations, p): 'this function calculates the distance between stations \n and coordinate and forms a list of tuples sorted by distance' distance_list = [] for i in stations: distance = float(haversine(i.coord, p)) dist_tuple = (i.name, distance) distance_list.append(dist_tuple) sorted_dlist = sorted_by_key(distance_list, 1) return sorted_dlist
this function calculates the distance between stations and coordinate and forms a list of tuples sorted by distance
floodsystem/geo.py
stations_by_distance
hsinorshin/Flood_Warning_System_159
0
python
def stations_by_distance(stations, p): 'this function calculates the distance between stations \n and coordinate and forms a list of tuples sorted by distance' distance_list = [] for i in stations: distance = float(haversine(i.coord, p)) dist_tuple = (i.name, distance) distance_list.append(dist_tuple) sorted_dlist = sorted_by_key(distance_list, 1) return sorted_dlist
def stations_by_distance(stations, p): 'this function calculates the distance between stations \n and coordinate and forms a list of tuples sorted by distance' distance_list = [] for i in stations: distance = float(haversine(i.coord, p)) dist_tuple = (i.name, distance) distance_list.append(dist_tuple) sorted_dlist = sorted_by_key(distance_list, 1) return sorted_dlist<|docstring|>this function calculates the distance between stations and coordinate and forms a list of tuples sorted by distance<|endoftext|>
b4f0c54d449d8c9bd7746f9257a5268a24b6c60a7465b356e43c1b197e6c4cff
def stations_within_radius(stations, centre, r): 'function which returns a list of\n the names of the stations within a certain radius from the centre' within_r_list = [] for i in stations: distance = float(haversine(i.coord, centre)) if (distance < r): within_r_list.append(i.name) return within_r_list
function which returns a list of the names of the stations within a certain radius from the centre
floodsystem/geo.py
stations_within_radius
hsinorshin/Flood_Warning_System_159
0
python
def stations_within_radius(stations, centre, r): 'function which returns a list of\n the names of the stations within a certain radius from the centre' within_r_list = [] for i in stations: distance = float(haversine(i.coord, centre)) if (distance < r): within_r_list.append(i.name) return within_r_list
def stations_within_radius(stations, centre, r): 'function which returns a list of\n the names of the stations within a certain radius from the centre' within_r_list = [] for i in stations: distance = float(haversine(i.coord, centre)) if (distance < r): within_r_list.append(i.name) return within_r_list<|docstring|>function which returns a list of the names of the stations within a certain radius from the centre<|endoftext|>
73345db468e471684201b6a52b89a8c0a6690dc85b9a7239bbf74a7ba5508208
def rivers_with_station(stations): 'function which returns set of rivers by stations' river_set = set({}) for i in stations: river = i.river river_set.add(river) return river_set
function which returns set of rivers by stations
floodsystem/geo.py
rivers_with_station
hsinorshin/Flood_Warning_System_159
0
python
def rivers_with_station(stations): river_set = set({}) for i in stations: river = i.river river_set.add(river) return river_set
def rivers_with_station(stations): river_set = set({}) for i in stations: river = i.river river_set.add(river) return river_set<|docstring|>function which returns set of rivers by stations<|endoftext|>
a6eeb55148ca580e20a469b32a46f1536c518864432d086fc5b2adad82d5b007
def stations_by_river(stations): 'function which returns a list of stations by a river' river_dict = {} river = rivers_with_station(stations) for i in river: station_list = [] for x in stations: if (x.river == i): station = x.name station_list.append(station) river_dict[i] = station_list return river_dict
function which returns a list of stations by a river
floodsystem/geo.py
stations_by_river
hsinorshin/Flood_Warning_System_159
0
python
def stations_by_river(stations): river_dict = {} river = rivers_with_station(stations) for i in river: station_list = [] for x in stations: if (x.river == i): station = x.name station_list.append(station) river_dict[i] = station_list return river_dict
def stations_by_river(stations): river_dict = {} river = rivers_with_station(stations) for i in river: station_list = [] for x in stations: if (x.river == i): station = x.name station_list.append(station) river_dict[i] = station_list return river_dict<|docstring|>function which returns a list of stations by a river<|endoftext|>
2be778b7d3acda040581ebf8f05b54db18a2c68fe0ed5880a04eee2479250152
def rivers_by_station_number(stations, N): 'this function determines the N rivers with\n the greatest number of monitoring stations,\n returns list of tuples sorted by number of stations' river_list = [] river = rivers_with_station(stations) for i in river: river_counter = len(stations_by_river(stations)[i]) river_tuple = (i, river_counter) river_list.append(river_tuple) sorted_list = sorted_by_key(river_list, 1, reverse=True) counter = 0 for x in range((N - 1), len(river)): if (sorted_list[x][1] == sorted_list[(x + 1)][1]): counter += 1 else: break return sorted_list[:(N + counter)]
this function determines the N rivers with the greatest number of monitoring stations, returns list of tuples sorted by number of stations
floodsystem/geo.py
rivers_by_station_number
hsinorshin/Flood_Warning_System_159
0
python
def rivers_by_station_number(stations, N): 'this function determines the N rivers with\n the greatest number of monitoring stations,\n returns list of tuples sorted by number of stations' river_list = [] river = rivers_with_station(stations) for i in river: river_counter = len(stations_by_river(stations)[i]) river_tuple = (i, river_counter) river_list.append(river_tuple) sorted_list = sorted_by_key(river_list, 1, reverse=True) counter = 0 for x in range((N - 1), len(river)): if (sorted_list[x][1] == sorted_list[(x + 1)][1]): counter += 1 else: break return sorted_list[:(N + counter)]
def rivers_by_station_number(stations, N): 'this function determines the N rivers with\n the greatest number of monitoring stations,\n returns list of tuples sorted by number of stations' river_list = [] river = rivers_with_station(stations) for i in river: river_counter = len(stations_by_river(stations)[i]) river_tuple = (i, river_counter) river_list.append(river_tuple) sorted_list = sorted_by_key(river_list, 1, reverse=True) counter = 0 for x in range((N - 1), len(river)): if (sorted_list[x][1] == sorted_list[(x + 1)][1]): counter += 1 else: break return sorted_list[:(N + counter)]<|docstring|>this function determines the N rivers with the greatest number of monitoring stations, returns list of tuples sorted by number of stations<|endoftext|>
831d646a796cf3bb0e4f0b40ee71ff32ae766ed7adb5cb29a99530804d4629c6
def __lt__(self, other: 'SimpleRoll'): '\n We treat a roll as being less than another if the Result is lower,\n or same result is outside tie threshold for the result values.\n ' try: if (self.roll_result_object == other.roll_result_object): return ((self.result_value + self.tie_threshold) < other.result_value) return (self.roll_result_object.value < other.roll_result_object.value) except AttributeError: return NotImplemented
We treat a roll as being less than another if the Result is lower, or same result is outside tie threshold for the result values.
world/stat_checks/check_maker.py
__lt__
ApostateCD/arxcode
42
python
def __lt__(self, other: 'SimpleRoll'): '\n We treat a roll as being less than another if the Result is lower,\n or same result is outside tie threshold for the result values.\n ' try: if (self.roll_result_object == other.roll_result_object): return ((self.result_value + self.tie_threshold) < other.result_value) return (self.roll_result_object.value < other.roll_result_object.value) except AttributeError: return NotImplemented
def __lt__(self, other: 'SimpleRoll'): '\n We treat a roll as being less than another if the Result is lower,\n or same result is outside tie threshold for the result values.\n ' try: if (self.roll_result_object == other.roll_result_object): return ((self.result_value + self.tie_threshold) < other.result_value) return (self.roll_result_object.value < other.roll_result_object.value) except AttributeError: return NotImplemented<|docstring|>We treat a roll as being less than another if the Result is lower, or same result is outside tie threshold for the result values.<|endoftext|>
d88d86105a54c150c0c1e7e86769798b1a6c087a783b7b86352f033403126640
def __eq__(self, other: 'SimpleRoll'): 'Equal if they have the same apparent result object and the' return ((self.roll_result_object == other.roll_result_object) and (abs((self.result_value - other.result_value)) <= self.tie_threshold))
Equal if they have the same apparent result object and the
world/stat_checks/check_maker.py
__eq__
ApostateCD/arxcode
42
python
def __eq__(self, other: 'SimpleRoll'): return ((self.roll_result_object == other.roll_result_object) and (abs((self.result_value - other.result_value)) <= self.tie_threshold))
def __eq__(self, other: 'SimpleRoll'): return ((self.roll_result_object == other.roll_result_object) and (abs((self.result_value - other.result_value)) <= self.tie_threshold))<|docstring|>Equal if they have the same apparent result object and the<|endoftext|>
fde604196c344e82e8703920e62dfb009e32214dfd312a8b81a1c04be2570aa4
def execute(self): 'Does the actual roll' self.raw_roll = randint(1, 100) val = self.get_roll_value_for_traits() val += self.get_roll_value_for_knack() val -= self.get_roll_value_for_rating() val += self.raw_roll self.result_value = val self.natural_roll_type = self.check_for_crit_or_botch() self.roll_result_object = RollResult.get_instance_for_roll(val, natural_roll_type=self.natural_roll_type) self.result_message = self.roll_result_object.render(**self.get_context())
Does the actual roll
world/stat_checks/check_maker.py
execute
ApostateCD/arxcode
42
python
def execute(self): self.raw_roll = randint(1, 100) val = self.get_roll_value_for_traits() val += self.get_roll_value_for_knack() val -= self.get_roll_value_for_rating() val += self.raw_roll self.result_value = val self.natural_roll_type = self.check_for_crit_or_botch() self.roll_result_object = RollResult.get_instance_for_roll(val, natural_roll_type=self.natural_roll_type) self.result_message = self.roll_result_object.render(**self.get_context())
def execute(self): self.raw_roll = randint(1, 100) val = self.get_roll_value_for_traits() val += self.get_roll_value_for_knack() val -= self.get_roll_value_for_rating() val += self.raw_roll self.result_value = val self.natural_roll_type = self.check_for_crit_or_botch() self.roll_result_object = RollResult.get_instance_for_roll(val, natural_roll_type=self.natural_roll_type) self.result_message = self.roll_result_object.render(**self.get_context())<|docstring|>Does the actual roll<|endoftext|>
31462b64b2612d274c4315c755cc909e0cb29dbbfc1f613d6d8263834b73f55f
def announce_to_players(self): "\n Sends a private roll result message to specific players as well as\n to all GMs (player and staff) at that character's location.\n " player_notifier = SelfListNotifier(self.character, receivers=self.receivers, to_player=True, to_gm=True) staff_notifier = RoomNotifier(self.character, room=self.character.location, to_staff=True) player_notifier.generate() staff_notifier.generate() staff_names = [f'|c{name}|n' for name in sorted(staff_notifier.receiver_names)] receiver_names = (sorted(player_notifier.receiver_names) + staff_names) if receiver_names: receiver_suffix = f"(Shared with: {', '.join(receiver_names)})" else: receiver_suffix = f'(Shared with: {self.character})' private_msg = f'|w[Private Roll]|n {self.roll_message} {receiver_suffix}' player_notifier.notify(private_msg, options={'roll': True}) staff_notifier.notify(private_msg, options={'roll': True})
Sends a private roll result message to specific players as well as to all GMs (player and staff) at that character's location.
world/stat_checks/check_maker.py
announce_to_players
ApostateCD/arxcode
42
python
def announce_to_players(self): "\n Sends a private roll result message to specific players as well as\n to all GMs (player and staff) at that character's location.\n " player_notifier = SelfListNotifier(self.character, receivers=self.receivers, to_player=True, to_gm=True) staff_notifier = RoomNotifier(self.character, room=self.character.location, to_staff=True) player_notifier.generate() staff_notifier.generate() staff_names = [f'|c{name}|n' for name in sorted(staff_notifier.receiver_names)] receiver_names = (sorted(player_notifier.receiver_names) + staff_names) if receiver_names: receiver_suffix = f"(Shared with: {', '.join(receiver_names)})" else: receiver_suffix = f'(Shared with: {self.character})' private_msg = f'|w[Private Roll]|n {self.roll_message} {receiver_suffix}' player_notifier.notify(private_msg, options={'roll': True}) staff_notifier.notify(private_msg, options={'roll': True})
def announce_to_players(self): "\n Sends a private roll result message to specific players as well as\n to all GMs (player and staff) at that character's location.\n " player_notifier = SelfListNotifier(self.character, receivers=self.receivers, to_player=True, to_gm=True) staff_notifier = RoomNotifier(self.character, room=self.character.location, to_staff=True) player_notifier.generate() staff_notifier.generate() staff_names = [f'|c{name}|n' for name in sorted(staff_notifier.receiver_names)] receiver_names = (sorted(player_notifier.receiver_names) + staff_names) if receiver_names: receiver_suffix = f"(Shared with: {', '.join(receiver_names)})" else: receiver_suffix = f'(Shared with: {self.character})' private_msg = f'|w[Private Roll]|n {self.roll_message} {receiver_suffix}' player_notifier.notify(private_msg, options={'roll': True}) staff_notifier.notify(private_msg, options={'roll': True})<|docstring|>Sends a private roll result message to specific players as well as to all GMs (player and staff) at that character's location.<|endoftext|>
204b0e4f1067f19a68c52a88c2f065760a35b22b36e9100819604864e39f1a29
def get_roll_value_for_stat(self) -> int: '\n Looks up how much to modify our roll by based on our stat. We use a lookup table to\n determine how much each level of the stat is weighted by. Weight may be different if\n there is no skills for this roll.\n ' if (not self.stat): return 0 base = self.character.traits.get_stat_value(self.stat) only_stat = (not self.skill) return StatWeight.get_weighted_value_for_stat(base, only_stat)
Looks up how much to modify our roll by based on our stat. We use a lookup table to determine how much each level of the stat is weighted by. Weight may be different if there is no skills for this roll.
world/stat_checks/check_maker.py
get_roll_value_for_stat
ApostateCD/arxcode
42
python
def get_roll_value_for_stat(self) -> int: '\n Looks up how much to modify our roll by based on our stat. We use a lookup table to\n determine how much each level of the stat is weighted by. Weight may be different if\n there is no skills for this roll.\n ' if (not self.stat): return 0 base = self.character.traits.get_stat_value(self.stat) only_stat = (not self.skill) return StatWeight.get_weighted_value_for_stat(base, only_stat)
def get_roll_value_for_stat(self) -> int: '\n Looks up how much to modify our roll by based on our stat. We use a lookup table to\n determine how much each level of the stat is weighted by. Weight may be different if\n there is no skills for this roll.\n ' if (not self.stat): return 0 base = self.character.traits.get_stat_value(self.stat) only_stat = (not self.skill) return StatWeight.get_weighted_value_for_stat(base, only_stat)<|docstring|>Looks up how much to modify our roll by based on our stat. We use a lookup table to determine how much each level of the stat is weighted by. Weight may be different if there is no skills for this roll.<|endoftext|>
5e0d58193b84ed50bceae8293a3fde50b3d937d9c2a2f24caae6419c8e5bfb9d
def get_roll_value_for_skill(self) -> int: '\n Looks up how much to modify our roll based on our skill. We use a lookup table to\n determine how much each level of the skill is weighted by.\n ' if (not self.skill): return 0 base = self.character.traits.get_skill_value(self.skill) return StatWeight.get_weighted_value_for_skill(base)
Looks up how much to modify our roll based on our skill. We use a lookup table to determine how much each level of the skill is weighted by.
world/stat_checks/check_maker.py
get_roll_value_for_skill
ApostateCD/arxcode
42
python
def get_roll_value_for_skill(self) -> int: '\n Looks up how much to modify our roll based on our skill. We use a lookup table to\n determine how much each level of the skill is weighted by.\n ' if (not self.skill): return 0 base = self.character.traits.get_skill_value(self.skill) return StatWeight.get_weighted_value_for_skill(base)
def get_roll_value_for_skill(self) -> int: '\n Looks up how much to modify our roll based on our skill. We use a lookup table to\n determine how much each level of the skill is weighted by.\n ' if (not self.skill): return 0 base = self.character.traits.get_skill_value(self.skill) return StatWeight.get_weighted_value_for_skill(base)<|docstring|>Looks up how much to modify our roll based on our skill. We use a lookup table to determine how much each level of the skill is weighted by.<|endoftext|>
eb11f41329c598d9bba002ac9b351596680ae15f829013b932b17d9a394d9ba8
def get_roll_value_for_knack(self) -> int: "Looks up the value for the character's knacks, if any." try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers([self.stat], [self.skill]) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)
Looks up the value for the character's knacks, if any.
world/stat_checks/check_maker.py
get_roll_value_for_knack
ApostateCD/arxcode
42
python
def get_roll_value_for_knack(self) -> int: try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers([self.stat], [self.skill]) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)
def get_roll_value_for_knack(self) -> int: try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers([self.stat], [self.skill]) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)<|docstring|>Looks up the value for the character's knacks, if any.<|endoftext|>
2378369729cc7c4b36cb94ccb7b43b1eac0ec1688453ea38c31d4b93dfd8f792
def check_for_crit_or_botch(self): '\n Checks our lookup table with our raw roll and sees if we got a crit or botch.\n ' return NaturalRollType.get_roll_type(self.raw_roll)
Checks our lookup table with our raw roll and sees if we got a crit or botch.
world/stat_checks/check_maker.py
check_for_crit_or_botch
ApostateCD/arxcode
42
python
def check_for_crit_or_botch(self): '\n \n ' return NaturalRollType.get_roll_type(self.raw_roll)
def check_for_crit_or_botch(self): '\n \n ' return NaturalRollType.get_roll_type(self.raw_roll)<|docstring|>Checks our lookup table with our raw roll and sees if we got a crit or botch.<|endoftext|>
0931b18244e2d35db70cea1bd6134101a9ba5af25c27bbb9d5408a934c50a39f
def get_roll_value_for_traits(self) -> int: '\n Get the value for our traits from our check\n ' return self.check.get_value_for_traits(self.character)
Get the value for our traits from our check
world/stat_checks/check_maker.py
get_roll_value_for_traits
ApostateCD/arxcode
42
python
def get_roll_value_for_traits(self) -> int: '\n \n ' return self.check.get_value_for_traits(self.character)
def get_roll_value_for_traits(self) -> int: '\n \n ' return self.check.get_value_for_traits(self.character)<|docstring|>Get the value for our traits from our check<|endoftext|>
b4cd661d94465668a480fa6751fdb0b5bfee6c22056c2477e3bc26e72767f48b
def get_roll_value_for_rating(self) -> int: '\n Get the value for the difficult rating from our check\n ' if self.rating: return super().get_roll_value_for_rating() self.rating = self.check.get_difficulty_rating(self.target, **self.roll_kwargs) return self.rating.value
Get the value for the difficult rating from our check
world/stat_checks/check_maker.py
get_roll_value_for_rating
ApostateCD/arxcode
42
python
def get_roll_value_for_rating(self) -> int: '\n \n ' if self.rating: return super().get_roll_value_for_rating() self.rating = self.check.get_difficulty_rating(self.target, **self.roll_kwargs) return self.rating.value
def get_roll_value_for_rating(self) -> int: '\n \n ' if self.rating: return super().get_roll_value_for_rating() self.rating = self.check.get_difficulty_rating(self.target, **self.roll_kwargs) return self.rating.value<|docstring|>Get the value for the difficult rating from our check<|endoftext|>
b8a830ec46c4662bf27ee2b83d086dc1d6be9607a964026262ef9a7369e8f1bb
def get_roll_value_for_knack(self) -> int: "Looks up the value for the character's knacks, if any." try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers(self.check.get_stats_list(self.character), self.check.get_skills_list(self.character)) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)
Looks up the value for the character's knacks, if any.
world/stat_checks/check_maker.py
get_roll_value_for_knack
ApostateCD/arxcode
42
python
def get_roll_value_for_knack(self) -> int: try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers(self.check.get_stats_list(self.character), self.check.get_skills_list(self.character)) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)
def get_roll_value_for_knack(self) -> int: try: mods: ModifierHandler = self.character.mods base = mods.get_total_roll_modifiers(self.check.get_stats_list(self.character), self.check.get_skills_list(self.character)) except AttributeError: return 0 return StatWeight.get_weighted_value_for_knack(base)<|docstring|>Looks up the value for the character's knacks, if any.<|endoftext|>
e512be4fa3311a5129ba99a3af99249fe718562a368d0257807c9debb96117c3
def exploit(conn): '\n corrupt the canary and trigger __stack_chk_fail()\n ' conn.recvuntil('name:\n') input_name = (b'A' * 24) input_name += p64(6295592) input_name += (b'D' * 8) input_name += (b'E' * 8) input_name += (b'F' * 7) conn.sendline(input_name) conn.recvuntil('description:\n') input_des = (b'B' * 7) conn.sendline(input_des) conn.interactive()
corrupt the canary and trigger __stack_chk_fail()
linux_binary_exploit/canary_bypass02/canary_bypass02_exploit_v02.py
exploit
greyshell/Penetration-Test
13
python
def exploit(conn): '\n \n ' conn.recvuntil('name:\n') input_name = (b'A' * 24) input_name += p64(6295592) input_name += (b'D' * 8) input_name += (b'E' * 8) input_name += (b'F' * 7) conn.sendline(input_name) conn.recvuntil('description:\n') input_des = (b'B' * 7) conn.sendline(input_des) conn.interactive()
def exploit(conn): '\n \n ' conn.recvuntil('name:\n') input_name = (b'A' * 24) input_name += p64(6295592) input_name += (b'D' * 8) input_name += (b'E' * 8) input_name += (b'F' * 7) conn.sendline(input_name) conn.recvuntil('description:\n') input_des = (b'B' * 7) conn.sendline(input_des) conn.interactive()<|docstring|>corrupt the canary and trigger __stack_chk_fail()<|endoftext|>
7129247a24c4bcf86f731416c9f2e9c7caebb5a02e07ecf1663826bff7637fb9
def retry(fn: Callable, timeout: int=900) -> None: 'Call the given function repeatedly, with 1 second intervals,\n until it returns True or a timeout is reached.\n ' for _ in range(timeout): if fn(False): return time.sleep(1) if (not fn(True)): raise Exception(f'action timed out after {timeout} seconds')
Call the given function repeatedly, with 1 second intervals, until it returns True or a timeout is reached.
nixos/lib/test-driver/test-driver.py
retry
pranaysashank/nixpkgs
7
python
def retry(fn: Callable, timeout: int=900) -> None: 'Call the given function repeatedly, with 1 second intervals,\n until it returns True or a timeout is reached.\n ' for _ in range(timeout): if fn(False): return time.sleep(1) if (not fn(True)): raise Exception(f'action timed out after {timeout} seconds')
def retry(fn: Callable, timeout: int=900) -> None: 'Call the given function repeatedly, with 1 second intervals,\n until it returns True or a timeout is reached.\n ' for _ in range(timeout): if fn(False): return time.sleep(1) if (not fn(True)): raise Exception(f'action timed out after {timeout} seconds')<|docstring|>Call the given function repeatedly, with 1 second intervals, until it returns True or a timeout is reached.<|endoftext|>
76fb7324f332838b7626d4fca12e9d78c939299a40115a559df76f17b4cdaace
def wait_for_unit(self, unit: str, user: Optional[str]=None) -> None: 'Wait for a systemd unit to get into "active" state.\n Throws exceptions on "failed" and "inactive" states as well as\n after timing out.\n ' def check_active(_: Any) -> bool: info = self.get_unit_info(unit, user) state = info['ActiveState'] if (state == 'failed'): raise Exception('unit "{}" reached state "{}"'.format(unit, state)) if (state == 'inactive'): (status, jobs) = self.systemctl('list-jobs --full 2>&1', user) if ('No jobs' in jobs): info = self.get_unit_info(unit, user) if (info['ActiveState'] == state): raise Exception('unit "{}" is inactive and there are no pending jobs'.format(unit)) return (state == 'active') retry(check_active)
Wait for a systemd unit to get into "active" state. Throws exceptions on "failed" and "inactive" states as well as after timing out.
nixos/lib/test-driver/test-driver.py
wait_for_unit
pranaysashank/nixpkgs
7
python
def wait_for_unit(self, unit: str, user: Optional[str]=None) -> None: 'Wait for a systemd unit to get into "active" state.\n Throws exceptions on "failed" and "inactive" states as well as\n after timing out.\n ' def check_active(_: Any) -> bool: info = self.get_unit_info(unit, user) state = info['ActiveState'] if (state == 'failed'): raise Exception('unit "{}" reached state "{}"'.format(unit, state)) if (state == 'inactive'): (status, jobs) = self.systemctl('list-jobs --full 2>&1', user) if ('No jobs' in jobs): info = self.get_unit_info(unit, user) if (info['ActiveState'] == state): raise Exception('unit "{}" is inactive and there are no pending jobs'.format(unit)) return (state == 'active') retry(check_active)
def wait_for_unit(self, unit: str, user: Optional[str]=None) -> None: 'Wait for a systemd unit to get into "active" state.\n Throws exceptions on "failed" and "inactive" states as well as\n after timing out.\n ' def check_active(_: Any) -> bool: info = self.get_unit_info(unit, user) state = info['ActiveState'] if (state == 'failed'): raise Exception('unit "{}" reached state "{}"'.format(unit, state)) if (state == 'inactive'): (status, jobs) = self.systemctl('list-jobs --full 2>&1', user) if ('No jobs' in jobs): info = self.get_unit_info(unit, user) if (info['ActiveState'] == state): raise Exception('unit "{}" is inactive and there are no pending jobs'.format(unit)) return (state == 'active') retry(check_active)<|docstring|>Wait for a systemd unit to get into "active" state. Throws exceptions on "failed" and "inactive" states as well as after timing out.<|endoftext|>
6bba3019112e478879882991317602d42b62a774384c330ee32b3755bed17366
def shell_interact(self) -> None: 'Allows you to interact with the guest shell\n\n Should only be used during test development, not in the production test.' self.connect() self.log('Terminal is ready (there is no prompt):') subprocess.run(['socat', 'READLINE', f'FD:{self.shell.fileno()}'], pass_fds=[self.shell.fileno()])
Allows you to interact with the guest shell Should only be used during test development, not in the production test.
nixos/lib/test-driver/test-driver.py
shell_interact
pranaysashank/nixpkgs
7
python
def shell_interact(self) -> None: 'Allows you to interact with the guest shell\n\n Should only be used during test development, not in the production test.' self.connect() self.log('Terminal is ready (there is no prompt):') subprocess.run(['socat', 'READLINE', f'FD:{self.shell.fileno()}'], pass_fds=[self.shell.fileno()])
def shell_interact(self) -> None: 'Allows you to interact with the guest shell\n\n Should only be used during test development, not in the production test.' self.connect() self.log('Terminal is ready (there is no prompt):') subprocess.run(['socat', 'READLINE', f'FD:{self.shell.fileno()}'], pass_fds=[self.shell.fileno()])<|docstring|>Allows you to interact with the guest shell Should only be used during test development, not in the production test.<|endoftext|>
a1d813e4a365939d9b1976aa8f23f184876817d2d7451b69c030ed013375835c
def succeed(self, *commands: str) -> str: 'Execute each command and check that it succeeds.' output = '' for command in commands: with self.nested('must succeed: {}'.format(command)): (status, out) = self.execute(command) if (status != 0): self.log('output: {}'.format(out)) raise Exception('command `{}` failed (exit code {})'.format(command, status)) output += out return output
Execute each command and check that it succeeds.
nixos/lib/test-driver/test-driver.py
succeed
pranaysashank/nixpkgs
7
python
def succeed(self, *commands: str) -> str: output = for command in commands: with self.nested('must succeed: {}'.format(command)): (status, out) = self.execute(command) if (status != 0): self.log('output: {}'.format(out)) raise Exception('command `{}` failed (exit code {})'.format(command, status)) output += out return output
def succeed(self, *commands: str) -> str: output = for command in commands: with self.nested('must succeed: {}'.format(command)): (status, out) = self.execute(command) if (status != 0): self.log('output: {}'.format(out)) raise Exception('command `{}` failed (exit code {})'.format(command, status)) output += out return output<|docstring|>Execute each command and check that it succeeds.<|endoftext|>
7a4417c8032b92c4f1eb753676052b8aaacf9323753f6dfbd1249b2fa278723c
def fail(self, *commands: str) -> str: 'Execute each command and check that it fails.' output = '' for command in commands: with self.nested('must fail: {}'.format(command)): (status, out) = self.execute(command) if (status == 0): raise Exception('command `{}` unexpectedly succeeded'.format(command)) output += out return output
Execute each command and check that it fails.
nixos/lib/test-driver/test-driver.py
fail
pranaysashank/nixpkgs
7
python
def fail(self, *commands: str) -> str: output = for command in commands: with self.nested('must fail: {}'.format(command)): (status, out) = self.execute(command) if (status == 0): raise Exception('command `{}` unexpectedly succeeded'.format(command)) output += out return output
def fail(self, *commands: str) -> str: output = for command in commands: with self.nested('must fail: {}'.format(command)): (status, out) = self.execute(command) if (status == 0): raise Exception('command `{}` unexpectedly succeeded'.format(command)) output += out return output<|docstring|>Execute each command and check that it fails.<|endoftext|>
ecbcd4747d3d3e98960aef19250b0c59f8a47f9a14af982c11c6ba7c3dbae002
def wait_until_succeeds(self, command: str, timeout: int=900) -> str: 'Wait until a command returns success and return its output.\n Throws an exception on timeout.\n ' output = '' def check_success(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status == 0) with self.nested('waiting for success: {}'.format(command)): retry(check_success, timeout) return output
Wait until a command returns success and return its output. Throws an exception on timeout.
nixos/lib/test-driver/test-driver.py
wait_until_succeeds
pranaysashank/nixpkgs
7
python
def wait_until_succeeds(self, command: str, timeout: int=900) -> str: 'Wait until a command returns success and return its output.\n Throws an exception on timeout.\n ' output = def check_success(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status == 0) with self.nested('waiting for success: {}'.format(command)): retry(check_success, timeout) return output
def wait_until_succeeds(self, command: str, timeout: int=900) -> str: 'Wait until a command returns success and return its output.\n Throws an exception on timeout.\n ' output = def check_success(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status == 0) with self.nested('waiting for success: {}'.format(command)): retry(check_success, timeout) return output<|docstring|>Wait until a command returns success and return its output. Throws an exception on timeout.<|endoftext|>
ffb6174106b0f10f30a6cf9e020bb63eff3343171c4245d24d8878c9c1c26165
def wait_until_fails(self, command: str) -> str: 'Wait until a command returns failure.\n Throws an exception on timeout.\n ' output = '' def check_failure(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status != 0) with self.nested('waiting for failure: {}'.format(command)): retry(check_failure) return output
Wait until a command returns failure. Throws an exception on timeout.
nixos/lib/test-driver/test-driver.py
wait_until_fails
pranaysashank/nixpkgs
7
python
def wait_until_fails(self, command: str) -> str: 'Wait until a command returns failure.\n Throws an exception on timeout.\n ' output = def check_failure(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status != 0) with self.nested('waiting for failure: {}'.format(command)): retry(check_failure) return output
def wait_until_fails(self, command: str) -> str: 'Wait until a command returns failure.\n Throws an exception on timeout.\n ' output = def check_failure(_: Any) -> bool: nonlocal output (status, output) = self.execute(command) return (status != 0) with self.nested('waiting for failure: {}'.format(command)): retry(check_failure) return output<|docstring|>Wait until a command returns failure. Throws an exception on timeout.<|endoftext|>
25199bbc1cd03cd6c14203126a5ce37eba5f71ec9d54ba3f3bcc5a048f4f0209
def wait_until_tty_matches(self, tty: str, regexp: str) -> None: 'Wait until the visible output on the chosen TTY matches regular\n expression. Throws an exception on timeout.\n ' matcher = re.compile(regexp) def tty_matches(last: bool) -> bool: text = self.get_tty_text(tty) if last: self.log(f'Last chance to match /{regexp}/ on TTY{tty}, which currently contains: {text}') return (len(matcher.findall(text)) > 0) with self.nested('waiting for {} to appear on tty {}'.format(regexp, tty)): retry(tty_matches)
Wait until the visible output on the chosen TTY matches regular expression. Throws an exception on timeout.
nixos/lib/test-driver/test-driver.py
wait_until_tty_matches
pranaysashank/nixpkgs
7
python
def wait_until_tty_matches(self, tty: str, regexp: str) -> None: 'Wait until the visible output on the chosen TTY matches regular\n expression. Throws an exception on timeout.\n ' matcher = re.compile(regexp) def tty_matches(last: bool) -> bool: text = self.get_tty_text(tty) if last: self.log(f'Last chance to match /{regexp}/ on TTY{tty}, which currently contains: {text}') return (len(matcher.findall(text)) > 0) with self.nested('waiting for {} to appear on tty {}'.format(regexp, tty)): retry(tty_matches)
def wait_until_tty_matches(self, tty: str, regexp: str) -> None: 'Wait until the visible output on the chosen TTY matches regular\n expression. Throws an exception on timeout.\n ' matcher = re.compile(regexp) def tty_matches(last: bool) -> bool: text = self.get_tty_text(tty) if last: self.log(f'Last chance to match /{regexp}/ on TTY{tty}, which currently contains: {text}') return (len(matcher.findall(text)) > 0) with self.nested('waiting for {} to appear on tty {}'.format(regexp, tty)): retry(tty_matches)<|docstring|>Wait until the visible output on the chosen TTY matches regular expression. Throws an exception on timeout.<|endoftext|>
76d4c759af56fe9238c05021f9e757bf4e2b35525fc8c3aa289c80749df7173b
def wait_for_file(self, filename: str) -> None: "Waits until the file exists in machine's file system." def check_file(_: Any) -> bool: (status, _) = self.execute('test -e {}'.format(filename)) return (status == 0) with self.nested('waiting for file ‘{}‘'.format(filename)): retry(check_file)
Waits until the file exists in machine's file system.
nixos/lib/test-driver/test-driver.py
wait_for_file
pranaysashank/nixpkgs
7
python
def wait_for_file(self, filename: str) -> None: def check_file(_: Any) -> bool: (status, _) = self.execute('test -e {}'.format(filename)) return (status == 0) with self.nested('waiting for file ‘{}‘'.format(filename)): retry(check_file)
def wait_for_file(self, filename: str) -> None: def check_file(_: Any) -> bool: (status, _) = self.execute('test -e {}'.format(filename)) return (status == 0) with self.nested('waiting for file ‘{}‘'.format(filename)): retry(check_file)<|docstring|>Waits until the file exists in machine's file system.<|endoftext|>
b2c38c69bfd2be19f230efd80145f45aa8765b71983208106145c37f43faaa93
def copy_from_host_via_shell(self, source: str, target: str) -> None: 'Copy a file from the host into the guest by piping it over the\n shell into the destination file. Works without host-guest shared folder.\n Prefer copy_from_host for whenever possible.\n ' with open(source, 'rb') as fh: content_b64 = base64.b64encode(fh.read()).decode() self.succeed(f'mkdir -p $(dirname {target})', f'echo -n {content_b64} | base64 -d > {target}')
Copy a file from the host into the guest by piping it over the shell into the destination file. Works without host-guest shared folder. Prefer copy_from_host for whenever possible.
nixos/lib/test-driver/test-driver.py
copy_from_host_via_shell
pranaysashank/nixpkgs
7
python
def copy_from_host_via_shell(self, source: str, target: str) -> None: 'Copy a file from the host into the guest by piping it over the\n shell into the destination file. Works without host-guest shared folder.\n Prefer copy_from_host for whenever possible.\n ' with open(source, 'rb') as fh: content_b64 = base64.b64encode(fh.read()).decode() self.succeed(f'mkdir -p $(dirname {target})', f'echo -n {content_b64} | base64 -d > {target}')
def copy_from_host_via_shell(self, source: str, target: str) -> None: 'Copy a file from the host into the guest by piping it over the\n shell into the destination file. Works without host-guest shared folder.\n Prefer copy_from_host for whenever possible.\n ' with open(source, 'rb') as fh: content_b64 = base64.b64encode(fh.read()).decode() self.succeed(f'mkdir -p $(dirname {target})', f'echo -n {content_b64} | base64 -d > {target}')<|docstring|>Copy a file from the host into the guest by piping it over the shell into the destination file. Works without host-guest shared folder. Prefer copy_from_host for whenever possible.<|endoftext|>
e55ae227428b2e394aa525f3bc8a95ed0babd41975453f9ae3ac0963948ed2f5
def copy_from_host(self, source: str, target: str) -> None: 'Copy a file from the host into the guest via the `shared_dir` shared\n among all the VMs (using a temporary directory).\n ' host_src = pathlib.Path(source) vm_target = pathlib.Path(target) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) host_intermediate = (shared_temp / host_src.name) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / host_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) if host_src.is_dir(): shutil.copytree(host_src, host_intermediate) else: shutil.copy(host_src, host_intermediate) self.succeed(make_command(['mkdir', '-p', vm_target.parent])) self.succeed(make_command(['cp', '-r', vm_intermediate, vm_target]))
Copy a file from the host into the guest via the `shared_dir` shared among all the VMs (using a temporary directory).
nixos/lib/test-driver/test-driver.py
copy_from_host
pranaysashank/nixpkgs
7
python
def copy_from_host(self, source: str, target: str) -> None: 'Copy a file from the host into the guest via the `shared_dir` shared\n among all the VMs (using a temporary directory).\n ' host_src = pathlib.Path(source) vm_target = pathlib.Path(target) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) host_intermediate = (shared_temp / host_src.name) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / host_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) if host_src.is_dir(): shutil.copytree(host_src, host_intermediate) else: shutil.copy(host_src, host_intermediate) self.succeed(make_command(['mkdir', '-p', vm_target.parent])) self.succeed(make_command(['cp', '-r', vm_intermediate, vm_target]))
def copy_from_host(self, source: str, target: str) -> None: 'Copy a file from the host into the guest via the `shared_dir` shared\n among all the VMs (using a temporary directory).\n ' host_src = pathlib.Path(source) vm_target = pathlib.Path(target) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) host_intermediate = (shared_temp / host_src.name) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / host_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) if host_src.is_dir(): shutil.copytree(host_src, host_intermediate) else: shutil.copy(host_src, host_intermediate) self.succeed(make_command(['mkdir', '-p', vm_target.parent])) self.succeed(make_command(['cp', '-r', vm_intermediate, vm_target]))<|docstring|>Copy a file from the host into the guest via the `shared_dir` shared among all the VMs (using a temporary directory).<|endoftext|>
c33d264e1a3d6527c49d9f22eae33c7b16c571c560fee567687132e920962659
def copy_from_vm(self, source: str, target_dir: str='') -> None: 'Copy a file from the VM (specified by an in-VM source path) to a path\n relative to `$out`. The file is copied via the `shared_dir` shared among\n all the VMs (using a temporary directory).\n ' out_dir = pathlib.Path(os.environ.get('out', os.getcwd())) vm_src = pathlib.Path(source) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / vm_src.name) intermediate = (shared_temp / vm_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) self.succeed(make_command(['cp', '-r', vm_src, vm_intermediate])) abs_target = ((out_dir / target_dir) / vm_src.name) abs_target.parent.mkdir(exist_ok=True, parents=True) if intermediate.is_dir(): shutil.copytree(intermediate, abs_target) else: shutil.copy(intermediate, abs_target)
Copy a file from the VM (specified by an in-VM source path) to a path relative to `$out`. The file is copied via the `shared_dir` shared among all the VMs (using a temporary directory).
nixos/lib/test-driver/test-driver.py
copy_from_vm
pranaysashank/nixpkgs
7
python
def copy_from_vm(self, source: str, target_dir: str=) -> None: 'Copy a file from the VM (specified by an in-VM source path) to a path\n relative to `$out`. The file is copied via the `shared_dir` shared among\n all the VMs (using a temporary directory).\n ' out_dir = pathlib.Path(os.environ.get('out', os.getcwd())) vm_src = pathlib.Path(source) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / vm_src.name) intermediate = (shared_temp / vm_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) self.succeed(make_command(['cp', '-r', vm_src, vm_intermediate])) abs_target = ((out_dir / target_dir) / vm_src.name) abs_target.parent.mkdir(exist_ok=True, parents=True) if intermediate.is_dir(): shutil.copytree(intermediate, abs_target) else: shutil.copy(intermediate, abs_target)
def copy_from_vm(self, source: str, target_dir: str=) -> None: 'Copy a file from the VM (specified by an in-VM source path) to a path\n relative to `$out`. The file is copied via the `shared_dir` shared among\n all the VMs (using a temporary directory).\n ' out_dir = pathlib.Path(os.environ.get('out', os.getcwd())) vm_src = pathlib.Path(source) with tempfile.TemporaryDirectory(dir=self.shared_dir) as shared_td: shared_temp = pathlib.Path(shared_td) vm_shared_temp = (pathlib.Path('/tmp/shared') / shared_temp.name) vm_intermediate = (vm_shared_temp / vm_src.name) intermediate = (shared_temp / vm_src.name) self.succeed(make_command(['mkdir', '-p', vm_shared_temp])) self.succeed(make_command(['cp', '-r', vm_src, vm_intermediate])) abs_target = ((out_dir / target_dir) / vm_src.name) abs_target.parent.mkdir(exist_ok=True, parents=True) if intermediate.is_dir(): shutil.copytree(intermediate, abs_target) else: shutil.copy(intermediate, abs_target)<|docstring|>Copy a file from the VM (specified by an in-VM source path) to a path relative to `$out`. The file is copied via the `shared_dir` shared among all the VMs (using a temporary directory).<|endoftext|>
32df182d094d658a7a77738c0175191e808038a5c8768976222957e212368443
def dump_tty_contents(self, tty: str) -> None: 'Debugging: Dump the contents of the TTY<n>' self.execute('fold -w 80 /dev/vcs{} | systemd-cat'.format(tty))
Debugging: Dump the contents of the TTY<n>
nixos/lib/test-driver/test-driver.py
dump_tty_contents
pranaysashank/nixpkgs
7
python
def dump_tty_contents(self, tty: str) -> None: self.execute('fold -w 80 /dev/vcs{} | systemd-cat'.format(tty))
def dump_tty_contents(self, tty: str) -> None: self.execute('fold -w 80 /dev/vcs{} | systemd-cat'.format(tty))<|docstring|>Debugging: Dump the contents of the TTY<n><|endoftext|>
b27f16becd4a28b522b40ef69868fcae051ffb38e9845a4ec8a722b6fce3242d
def wait_for_x(self) -> None: 'Wait until it is possible to connect to the X server. Note that\n testing the existence of /tmp/.X11-unix/X0 is insufficient.\n ' def check_x(_: Any) -> bool: cmd = ('journalctl -b SYSLOG_IDENTIFIER=systemd | ' + 'grep "Reached target Current graphical"') (status, _) = self.execute(cmd) if (status != 0): return False (status, _) = self.execute('[ -e /tmp/.X11-unix/X0 ]') return (status == 0) with self.nested('waiting for the X11 server'): retry(check_x)
Wait until it is possible to connect to the X server. Note that testing the existence of /tmp/.X11-unix/X0 is insufficient.
nixos/lib/test-driver/test-driver.py
wait_for_x
pranaysashank/nixpkgs
7
python
def wait_for_x(self) -> None: 'Wait until it is possible to connect to the X server. Note that\n testing the existence of /tmp/.X11-unix/X0 is insufficient.\n ' def check_x(_: Any) -> bool: cmd = ('journalctl -b SYSLOG_IDENTIFIER=systemd | ' + 'grep "Reached target Current graphical"') (status, _) = self.execute(cmd) if (status != 0): return False (status, _) = self.execute('[ -e /tmp/.X11-unix/X0 ]') return (status == 0) with self.nested('waiting for the X11 server'): retry(check_x)
def wait_for_x(self) -> None: 'Wait until it is possible to connect to the X server. Note that\n testing the existence of /tmp/.X11-unix/X0 is insufficient.\n ' def check_x(_: Any) -> bool: cmd = ('journalctl -b SYSLOG_IDENTIFIER=systemd | ' + 'grep "Reached target Current graphical"') (status, _) = self.execute(cmd) if (status != 0): return False (status, _) = self.execute('[ -e /tmp/.X11-unix/X0 ]') return (status == 0) with self.nested('waiting for the X11 server'): retry(check_x)<|docstring|>Wait until it is possible to connect to the X server. Note that testing the existence of /tmp/.X11-unix/X0 is insufficient.<|endoftext|>
ca24506d69c79fc11a9ef24514b7adc3fe901bc1f9f1f316f9e60d54cdea84f6
def forward_port(self, host_port: int=8080, guest_port: int=80) -> None: 'Forward a TCP port on the host to a TCP port on the guest.\n Useful during interactive testing.\n ' self.send_monitor_command('hostfwd_add tcp::{}-:{}'.format(host_port, guest_port))
Forward a TCP port on the host to a TCP port on the guest. Useful during interactive testing.
nixos/lib/test-driver/test-driver.py
forward_port
pranaysashank/nixpkgs
7
python
def forward_port(self, host_port: int=8080, guest_port: int=80) -> None: 'Forward a TCP port on the host to a TCP port on the guest.\n Useful during interactive testing.\n ' self.send_monitor_command('hostfwd_add tcp::{}-:{}'.format(host_port, guest_port))
def forward_port(self, host_port: int=8080, guest_port: int=80) -> None: 'Forward a TCP port on the host to a TCP port on the guest.\n Useful during interactive testing.\n ' self.send_monitor_command('hostfwd_add tcp::{}-:{}'.format(host_port, guest_port))<|docstring|>Forward a TCP port on the host to a TCP port on the guest. Useful during interactive testing.<|endoftext|>
2fa05bc9290443470c3bc5c97436374813dac90e4f07f5472631132a2a05d7f6
def block(self) -> None: 'Make the machine unreachable by shutting down eth1 (the multicast\n interface used to talk to the other VMs). We keep eth0 up so that\n the test driver can continue to talk to the machine.\n ' self.send_monitor_command('set_link virtio-net-pci.1 off')
Make the machine unreachable by shutting down eth1 (the multicast interface used to talk to the other VMs). We keep eth0 up so that the test driver can continue to talk to the machine.
nixos/lib/test-driver/test-driver.py
block
pranaysashank/nixpkgs
7
python
def block(self) -> None: 'Make the machine unreachable by shutting down eth1 (the multicast\n interface used to talk to the other VMs). We keep eth0 up so that\n the test driver can continue to talk to the machine.\n ' self.send_monitor_command('set_link virtio-net-pci.1 off')
def block(self) -> None: 'Make the machine unreachable by shutting down eth1 (the multicast\n interface used to talk to the other VMs). We keep eth0 up so that\n the test driver can continue to talk to the machine.\n ' self.send_monitor_command('set_link virtio-net-pci.1 off')<|docstring|>Make the machine unreachable by shutting down eth1 (the multicast interface used to talk to the other VMs). We keep eth0 up so that the test driver can continue to talk to the machine.<|endoftext|>
da59aca5675437e6b2416b664e22ea001ca463e27d14e937b005a5378393cb80
def unblock(self) -> None: 'Make the machine reachable.' self.send_monitor_command('set_link virtio-net-pci.1 on')
Make the machine reachable.
nixos/lib/test-driver/test-driver.py
unblock
pranaysashank/nixpkgs
7
python
def unblock(self) -> None: self.send_monitor_command('set_link virtio-net-pci.1 on')
def unblock(self) -> None: self.send_monitor_command('set_link virtio-net-pci.1 on')<|docstring|>Make the machine reachable.<|endoftext|>
62c1681aa9c5f2a5ad089b57c24b3b3368cb7698ff76e52e838afc91a3f3b28b
@cached_property def credentials_location(self): "\n Helper to determine where will GDrive remote read credentials from.\n Useful for tests, exception messages, etc. Returns either env variable\n name if it's set or actual path to the credentials file.\n " if os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA): return GDriveFileSystem.GDRIVE_CREDENTIALS_DATA if os.path.exists(self._gdrive_user_credentials_path): return self._gdrive_user_credentials_path return None
Helper to determine where will GDrive remote read credentials from. Useful for tests, exception messages, etc. Returns either env variable name if it's set or actual path to the credentials file.
dvc/fs/gdrive.py
credentials_location
gsvolt/dvc
1
python
@cached_property def credentials_location(self): "\n Helper to determine where will GDrive remote read credentials from.\n Useful for tests, exception messages, etc. Returns either env variable\n name if it's set or actual path to the credentials file.\n " if os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA): return GDriveFileSystem.GDRIVE_CREDENTIALS_DATA if os.path.exists(self._gdrive_user_credentials_path): return self._gdrive_user_credentials_path return None
@cached_property def credentials_location(self): "\n Helper to determine where will GDrive remote read credentials from.\n Useful for tests, exception messages, etc. Returns either env variable\n name if it's set or actual path to the credentials file.\n " if os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA): return GDriveFileSystem.GDRIVE_CREDENTIALS_DATA if os.path.exists(self._gdrive_user_credentials_path): return self._gdrive_user_credentials_path return None<|docstring|>Helper to determine where will GDrive remote read credentials from. Useful for tests, exception messages, etc. Returns either env variable name if it's set or actual path to the credentials file.<|endoftext|>
a02796a9e0eb4a3b8b183aa4ad944388fa9625c937a562f5608ffd07c4b3f34f
@staticmethod def _validate_credentials(auth, settings): '\n Detects discrepancy in DVC config and cached credentials file.\n Usually happens when a second remote is added and it is using\n the same credentials default file. Or when someones decides to change\n DVC config client id or secret but forgets to remove the cached\n credentials file.\n ' if (not os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA)): if ((settings['client_config']['client_id'] != auth.credentials.client_id) or (settings['client_config']['client_secret'] != auth.credentials.client_secret)): logger.warning('Client ID and secret configured do not match the actual ones used\nto access the remote. Do you use multiple GDrive remotes and forgot to\nset `gdrive_user_credentials_file` for one or more of them? Learn more at\n{}.\n'.format(format_link('https://man.dvc.org/remote/modify')))
Detects discrepancy in DVC config and cached credentials file. Usually happens when a second remote is added and it is using the same credentials default file. Or when someones decides to change DVC config client id or secret but forgets to remove the cached credentials file.
dvc/fs/gdrive.py
_validate_credentials
gsvolt/dvc
1
python
@staticmethod def _validate_credentials(auth, settings): '\n Detects discrepancy in DVC config and cached credentials file.\n Usually happens when a second remote is added and it is using\n the same credentials default file. Or when someones decides to change\n DVC config client id or secret but forgets to remove the cached\n credentials file.\n ' if (not os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA)): if ((settings['client_config']['client_id'] != auth.credentials.client_id) or (settings['client_config']['client_secret'] != auth.credentials.client_secret)): logger.warning('Client ID and secret configured do not match the actual ones used\nto access the remote. Do you use multiple GDrive remotes and forgot to\nset `gdrive_user_credentials_file` for one or more of them? Learn more at\n{}.\n'.format(format_link('https://man.dvc.org/remote/modify')))
@staticmethod def _validate_credentials(auth, settings): '\n Detects discrepancy in DVC config and cached credentials file.\n Usually happens when a second remote is added and it is using\n the same credentials default file. Or when someones decides to change\n DVC config client id or secret but forgets to remove the cached\n credentials file.\n ' if (not os.getenv(GDriveFileSystem.GDRIVE_CREDENTIALS_DATA)): if ((settings['client_config']['client_id'] != auth.credentials.client_id) or (settings['client_config']['client_secret'] != auth.credentials.client_secret)): logger.warning('Client ID and secret configured do not match the actual ones used\nto access the remote. Do you use multiple GDrive remotes and forgot to\nset `gdrive_user_credentials_file` for one or more of them? Learn more at\n{}.\n'.format(format_link('https://man.dvc.org/remote/modify')))<|docstring|>Detects discrepancy in DVC config and cached credentials file. Usually happens when a second remote is added and it is using the same credentials default file. Or when someones decides to change DVC config client id or secret but forgets to remove the cached credentials file.<|endoftext|>
b6e41e172bb3a908c7b54d1e58ffd1cba32a91417f4114ce216868f513d0cbfc
def __init__(self, num_input=5, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n LSTM-FC Model, lstm layer contributes to learning time series data, dropout helps to prevent overfitting.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build LSTM_FC Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] for (i, num_curr) in enumerate(num_hidden): lstm = LSTMLayer(num_prev, num_curr, input_layers=[prev_layer], name='lstm{0}'.format((i + 1))) num_prev = num_curr prev_layer = lstm self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)
LSTM-FC Model, lstm layer contributes to learning time series data, dropout helps to prevent overfitting. Arguments: num_input: the number of input variables num_hidden: the number of neurons in each hidden layer num_output: output size (one in this study) clip_at: gradient clip scale_norm: gradient norm scale Returns: output (water table depth in this study)
models.py
__init__
molyswu/LSTM-water-table-depth-prediction
35
python
def __init__(self, num_input=5, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n LSTM-FC Model, lstm layer contributes to learning time series data, dropout helps to prevent overfitting.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build LSTM_FC Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] for (i, num_curr) in enumerate(num_hidden): lstm = LSTMLayer(num_prev, num_curr, input_layers=[prev_layer], name='lstm{0}'.format((i + 1))) num_prev = num_curr prev_layer = lstm self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)
def __init__(self, num_input=5, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n LSTM-FC Model, lstm layer contributes to learning time series data, dropout helps to prevent overfitting.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build LSTM_FC Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] for (i, num_curr) in enumerate(num_hidden): lstm = LSTMLayer(num_prev, num_curr, input_layers=[prev_layer], name='lstm{0}'.format((i + 1))) num_prev = num_curr prev_layer = lstm self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)<|docstring|>LSTM-FC Model, lstm layer contributes to learning time series data, dropout helps to prevent overfitting. Arguments: num_input: the number of input variables num_hidden: the number of neurons in each hidden layer num_output: output size (one in this study) clip_at: gradient clip scale_norm: gradient norm scale Returns: output (water table depth in this study)<|endoftext|>
e62f997a5ca83a3379392bab2658c43352cc66770669fdcc875da2268d44086e
def __init__(self, num_input=256, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n FFNN Model, two hidden fully-connected layers.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build FFNN Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] fc = FullyConnectedLayer(num_prev, num_hidden, input_layers=[prev_layer], name='fc') num_prev = num_hidden prev_layer = fc self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)
FFNN Model, two hidden fully-connected layers. Arguments: num_input: the number of input variables num_hidden: the number of neurons in each hidden layer num_output: output size (one in this study) clip_at: gradient clip scale_norm: gradient norm scale Returns: output (water table depth in this study)
models.py
__init__
molyswu/LSTM-water-table-depth-prediction
35
python
def __init__(self, num_input=256, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n FFNN Model, two hidden fully-connected layers.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build FFNN Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] fc = FullyConnectedLayer(num_prev, num_hidden, input_layers=[prev_layer], name='fc') num_prev = num_hidden prev_layer = fc self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)
def __init__(self, num_input=256, num_hidden=[64, 64], num_output=1, clip_at=0.0, scale_norm=0.0): '\n FFNN Model, two hidden fully-connected layers.\n\n Arguments:\n num_input: the number of input variables\n num_hidden: the number of neurons in each hidden layer\n num_output: output size (one in this study)\n clip_at: gradient clip\n scale_norm: gradient norm scale\n\n Returns:\n output (water table depth in this study)\n ' print('Build FFNN Model......') X = T.fmatrix() Y = T.fmatrix() learning_rate = T.fscalar() dropout_prob = T.fscalar() self.num_input = num_input self.num_hidden = num_hidden self.num_output = num_output self.clip_at = clip_at self.scale_norm = scale_norm inputs = InputLayer(X, name='inputs') num_prev = num_input prev_layer = inputs self.layers = [inputs] fc = FullyConnectedLayer(num_prev, num_hidden, input_layers=[prev_layer], name='fc') num_prev = num_hidden prev_layer = fc self.layers.append(prev_layer) prev_layer = DropoutLayer(prev_layer, dropout_prob) self.layers.append(prev_layer) fc = FullyConnectedLayer(num_prev, num_output, input_layers=[prev_layer], name='yhat') self.layers.append(fc) Y_hat = fc.output() loss = T.sum(((Y - Y_hat) ** 2)) params = get_params(self.layers) (updates, grads) = sgd(loss, params, learning_rate) self.train_func = theano.function([X, Y, learning_rate, dropout_prob], loss, updates=updates, allow_input_downcast=True) self.predict_func = theano.function([X, dropout_prob], Y_hat, allow_input_downcast=True)<|docstring|>FFNN Model, two hidden fully-connected layers. Arguments: num_input: the number of input variables num_hidden: the number of neurons in each hidden layer num_output: output size (one in this study) clip_at: gradient clip scale_norm: gradient norm scale Returns: output (water table depth in this study)<|endoftext|>
3eafeb1f45f5e0deafe58b1aff88528ef19c8f2b46866e08b8d17eb89be168df
def skill_score_murphy(predicted, reference): '\n Calculate non-dimensional skill score (SS) using Murphy.\n\n Calculates the non-dimensional skill score (SS) difference between two\n variables PREDICTED and REFERENCE. The skill score is calculated using\n the formula:\n\n SS = 1 - RMSE^2/SDEV^2\n\n where RMSE is the root-mean-squre error between the predicted and\n reference values\n\n (RMSE)^2 = sum_(n=1)^N (p_n - r_n)^2/N\n\n and SDEV is the standard deviation of the reference values\n\n SDEV^2 = sum_(n=1)^N [r_n - mean(r)]^2/(N-1)\n\n where p is the predicted values, r is the reference values, and\n N is the total number of values in p & r. Note that p & r must\n have the same number of values.\n\n Input:\n PREDICTED : predicted field\n REFERENCE : reference field\n\n Output:\n SS : skill score\n\n Reference:\n Allan H. Murphy, 1988: Skill Scores Based on the Mean Square Error\n and Their Relationships to the Correlation Coefficient. Mon. Wea.\n Rev., 116, 2417-2424.\n doi: http//dx.doi.org/10.1175/1520-0493(1988)<2417:SSBOTM>2.0.CO;2\n\n Author: Peter A. Rochford\n Symplectic, LLC\n www.thesymplectic.com\n example@example.com\n\n Created on Dec 7, 2016\n ' utils.check_arrays(predicted, reference) rmse2 = (rmsd(predicted, reference) ** 2) sdev2 = (np.std(reference, ddof=1) ** 2) ss = (1 - (rmse2 / sdev2)) return ss
Calculate non-dimensional skill score (SS) using Murphy. Calculates the non-dimensional skill score (SS) difference between two variables PREDICTED and REFERENCE. The skill score is calculated using the formula: SS = 1 - RMSE^2/SDEV^2 where RMSE is the root-mean-squre error between the predicted and reference values (RMSE)^2 = sum_(n=1)^N (p_n - r_n)^2/N and SDEV is the standard deviation of the reference values SDEV^2 = sum_(n=1)^N [r_n - mean(r)]^2/(N-1) where p is the predicted values, r is the reference values, and N is the total number of values in p & r. Note that p & r must have the same number of values. Input: PREDICTED : predicted field REFERENCE : reference field Output: SS : skill score Reference: Allan H. Murphy, 1988: Skill Scores Based on the Mean Square Error and Their Relationships to the Correlation Coefficient. Mon. Wea. Rev., 116, 2417-2424. doi: http//dx.doi.org/10.1175/1520-0493(1988)<2417:SSBOTM>2.0.CO;2 Author: Peter A. Rochford Symplectic, LLC www.thesymplectic.com example@example.com Created on Dec 7, 2016
src/plottoolbox/skill_metrics/skill_score_murphy.py
skill_score_murphy
timcera/plottoolbox
5
python
def skill_score_murphy(predicted, reference): '\n Calculate non-dimensional skill score (SS) using Murphy.\n\n Calculates the non-dimensional skill score (SS) difference between two\n variables PREDICTED and REFERENCE. The skill score is calculated using\n the formula:\n\n SS = 1 - RMSE^2/SDEV^2\n\n where RMSE is the root-mean-squre error between the predicted and\n reference values\n\n (RMSE)^2 = sum_(n=1)^N (p_n - r_n)^2/N\n\n and SDEV is the standard deviation of the reference values\n\n SDEV^2 = sum_(n=1)^N [r_n - mean(r)]^2/(N-1)\n\n where p is the predicted values, r is the reference values, and\n N is the total number of values in p & r. Note that p & r must\n have the same number of values.\n\n Input:\n PREDICTED : predicted field\n REFERENCE : reference field\n\n Output:\n SS : skill score\n\n Reference:\n Allan H. Murphy, 1988: Skill Scores Based on the Mean Square Error\n and Their Relationships to the Correlation Coefficient. Mon. Wea.\n Rev., 116, 2417-2424.\n doi: http//dx.doi.org/10.1175/1520-0493(1988)<2417:SSBOTM>2.0.CO;2\n\n Author: Peter A. Rochford\n Symplectic, LLC\n www.thesymplectic.com\n example@example.com\n\n Created on Dec 7, 2016\n ' utils.check_arrays(predicted, reference) rmse2 = (rmsd(predicted, reference) ** 2) sdev2 = (np.std(reference, ddof=1) ** 2) ss = (1 - (rmse2 / sdev2)) return ss
def skill_score_murphy(predicted, reference): '\n Calculate non-dimensional skill score (SS) using Murphy.\n\n Calculates the non-dimensional skill score (SS) difference between two\n variables PREDICTED and REFERENCE. The skill score is calculated using\n the formula:\n\n SS = 1 - RMSE^2/SDEV^2\n\n where RMSE is the root-mean-squre error between the predicted and\n reference values\n\n (RMSE)^2 = sum_(n=1)^N (p_n - r_n)^2/N\n\n and SDEV is the standard deviation of the reference values\n\n SDEV^2 = sum_(n=1)^N [r_n - mean(r)]^2/(N-1)\n\n where p is the predicted values, r is the reference values, and\n N is the total number of values in p & r. Note that p & r must\n have the same number of values.\n\n Input:\n PREDICTED : predicted field\n REFERENCE : reference field\n\n Output:\n SS : skill score\n\n Reference:\n Allan H. Murphy, 1988: Skill Scores Based on the Mean Square Error\n and Their Relationships to the Correlation Coefficient. Mon. Wea.\n Rev., 116, 2417-2424.\n doi: http//dx.doi.org/10.1175/1520-0493(1988)<2417:SSBOTM>2.0.CO;2\n\n Author: Peter A. Rochford\n Symplectic, LLC\n www.thesymplectic.com\n example@example.com\n\n Created on Dec 7, 2016\n ' utils.check_arrays(predicted, reference) rmse2 = (rmsd(predicted, reference) ** 2) sdev2 = (np.std(reference, ddof=1) ** 2) ss = (1 - (rmse2 / sdev2)) return ss<|docstring|>Calculate non-dimensional skill score (SS) using Murphy. Calculates the non-dimensional skill score (SS) difference between two variables PREDICTED and REFERENCE. The skill score is calculated using the formula: SS = 1 - RMSE^2/SDEV^2 where RMSE is the root-mean-squre error between the predicted and reference values (RMSE)^2 = sum_(n=1)^N (p_n - r_n)^2/N and SDEV is the standard deviation of the reference values SDEV^2 = sum_(n=1)^N [r_n - mean(r)]^2/(N-1) where p is the predicted values, r is the reference values, and N is the total number of values in p & r. Note that p & r must have the same number of values. Input: PREDICTED : predicted field REFERENCE : reference field Output: SS : skill score Reference: Allan H. Murphy, 1988: Skill Scores Based on the Mean Square Error and Their Relationships to the Correlation Coefficient. Mon. Wea. Rev., 116, 2417-2424. doi: http//dx.doi.org/10.1175/1520-0493(1988)<2417:SSBOTM>2.0.CO;2 Author: Peter A. Rochford Symplectic, LLC www.thesymplectic.com example@example.com Created on Dec 7, 2016<|endoftext|>
e117cc2071442dcadaf38cd674d06b0a0f54f3536cd69ad6979fe940ca8dcbf8
def plot_density(model, loader=[], batch_size=100, mesh_size=5.0, device='cpu'): 'Plot the density of a normalizing flow model. If loader not empty, it plots also its data samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n loader: loader containing data to plot. DataLoader\n bacth_size: discretization factor for the mesh. int\n mesh_size: range for the 2D mesh. float\n ' with torch.no_grad(): (xx, yy) = np.meshgrid(np.linspace((- mesh_size), mesh_size, num=batch_size), np.linspace((- mesh_size), mesh_size, num=batch_size)) coords = np.stack((xx, yy), axis=2) coords_resh = coords.reshape([(- 1), 2]) log_prob = np.zeros((batch_size ** 2)) for i in range(0, (batch_size ** 2), batch_size): data = torch.from_numpy(coords_resh[(i:(i + batch_size), :)]).float().to(device) log_prob[i:(i + batch_size)] = model.log_prob(data.to(device)).cpu().detach().numpy() plt.scatter(coords_resh[(:, 0)], coords_resh[(:, 1)], c=np.exp(log_prob)) plt.colorbar() for X in loader: plt.scatter(X[(:, 0)], X[(:, 1)], marker='x', c='orange', alpha=0.05) plt.show()
Plot the density of a normalizing flow model. If loader not empty, it plots also its data samples. Args: model: normalizing flow model. Flow or StackedFlows loader: loader containing data to plot. DataLoader bacth_size: discretization factor for the mesh. int mesh_size: range for the 2D mesh. float
project_1/nf_utils.py
plot_density
AbinavRavi/MLGS2020
0
python
def plot_density(model, loader=[], batch_size=100, mesh_size=5.0, device='cpu'): 'Plot the density of a normalizing flow model. If loader not empty, it plots also its data samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n loader: loader containing data to plot. DataLoader\n bacth_size: discretization factor for the mesh. int\n mesh_size: range for the 2D mesh. float\n ' with torch.no_grad(): (xx, yy) = np.meshgrid(np.linspace((- mesh_size), mesh_size, num=batch_size), np.linspace((- mesh_size), mesh_size, num=batch_size)) coords = np.stack((xx, yy), axis=2) coords_resh = coords.reshape([(- 1), 2]) log_prob = np.zeros((batch_size ** 2)) for i in range(0, (batch_size ** 2), batch_size): data = torch.from_numpy(coords_resh[(i:(i + batch_size), :)]).float().to(device) log_prob[i:(i + batch_size)] = model.log_prob(data.to(device)).cpu().detach().numpy() plt.scatter(coords_resh[(:, 0)], coords_resh[(:, 1)], c=np.exp(log_prob)) plt.colorbar() for X in loader: plt.scatter(X[(:, 0)], X[(:, 1)], marker='x', c='orange', alpha=0.05) plt.show()
def plot_density(model, loader=[], batch_size=100, mesh_size=5.0, device='cpu'): 'Plot the density of a normalizing flow model. If loader not empty, it plots also its data samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n loader: loader containing data to plot. DataLoader\n bacth_size: discretization factor for the mesh. int\n mesh_size: range for the 2D mesh. float\n ' with torch.no_grad(): (xx, yy) = np.meshgrid(np.linspace((- mesh_size), mesh_size, num=batch_size), np.linspace((- mesh_size), mesh_size, num=batch_size)) coords = np.stack((xx, yy), axis=2) coords_resh = coords.reshape([(- 1), 2]) log_prob = np.zeros((batch_size ** 2)) for i in range(0, (batch_size ** 2), batch_size): data = torch.from_numpy(coords_resh[(i:(i + batch_size), :)]).float().to(device) log_prob[i:(i + batch_size)] = model.log_prob(data.to(device)).cpu().detach().numpy() plt.scatter(coords_resh[(:, 0)], coords_resh[(:, 1)], c=np.exp(log_prob)) plt.colorbar() for X in loader: plt.scatter(X[(:, 0)], X[(:, 1)], marker='x', c='orange', alpha=0.05) plt.show()<|docstring|>Plot the density of a normalizing flow model. If loader not empty, it plots also its data samples. Args: model: normalizing flow model. Flow or StackedFlows loader: loader containing data to plot. DataLoader bacth_size: discretization factor for the mesh. int mesh_size: range for the 2D mesh. float<|endoftext|>
f4a80587f6cfbfa5db86bf16ac01190ce03f9c5300b2965a787069d1cab10ca1
def plot_samples(model, num_samples=500, mesh_size=5.0): 'Plot samples from a normalizing flow model. Colors are selected according to the densities at the samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n num_samples: number of samples to plot. int\n mesh_size: range for the 2D mesh. float\n ' (x, log_prob) = model.rsample(batch_size=num_samples) x = x.cpu().detach().numpy() log_prob = log_prob.cpu().detach().numpy() plt.scatter(x[(:, 0)], x[(:, 1)], c=np.exp(log_prob)) plt.xlim((- mesh_size), mesh_size) plt.ylim((- mesh_size), mesh_size) plt.show()
Plot samples from a normalizing flow model. Colors are selected according to the densities at the samples. Args: model: normalizing flow model. Flow or StackedFlows num_samples: number of samples to plot. int mesh_size: range for the 2D mesh. float
project_1/nf_utils.py
plot_samples
AbinavRavi/MLGS2020
0
python
def plot_samples(model, num_samples=500, mesh_size=5.0): 'Plot samples from a normalizing flow model. Colors are selected according to the densities at the samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n num_samples: number of samples to plot. int\n mesh_size: range for the 2D mesh. float\n ' (x, log_prob) = model.rsample(batch_size=num_samples) x = x.cpu().detach().numpy() log_prob = log_prob.cpu().detach().numpy() plt.scatter(x[(:, 0)], x[(:, 1)], c=np.exp(log_prob)) plt.xlim((- mesh_size), mesh_size) plt.ylim((- mesh_size), mesh_size) plt.show()
def plot_samples(model, num_samples=500, mesh_size=5.0): 'Plot samples from a normalizing flow model. Colors are selected according to the densities at the samples.\n\n Args:\n model: normalizing flow model. Flow or StackedFlows\n num_samples: number of samples to plot. int\n mesh_size: range for the 2D mesh. float\n ' (x, log_prob) = model.rsample(batch_size=num_samples) x = x.cpu().detach().numpy() log_prob = log_prob.cpu().detach().numpy() plt.scatter(x[(:, 0)], x[(:, 1)], c=np.exp(log_prob)) plt.xlim((- mesh_size), mesh_size) plt.ylim((- mesh_size), mesh_size) plt.show()<|docstring|>Plot samples from a normalizing flow model. Colors are selected according to the densities at the samples. Args: model: normalizing flow model. Flow or StackedFlows num_samples: number of samples to plot. int mesh_size: range for the 2D mesh. float<|endoftext|>
39ba8844bd385bd21261e7d6e95ddc79c9ce9ff1f4bcc70ec43ae6bcbb08ece9
def forward(self, x): 'Compute f(x) and log_abs_det_jac(x).' raise NotImplementedError
Compute f(x) and log_abs_det_jac(x).
project_1/nf_utils.py
forward
AbinavRavi/MLGS2020
0
python
def forward(self, x): raise NotImplementedError
def forward(self, x): raise NotImplementedError<|docstring|>Compute f(x) and log_abs_det_jac(x).<|endoftext|>
afb8a011a4bf9f1637feacfd076cd6a2fa0dd7d7500579062d2d09434b42175f
def inverse(self, y): 'Compute f^-1(y) and inv_log_abs_det_jac(y).' raise NotImplementedError
Compute f^-1(y) and inv_log_abs_det_jac(y).
project_1/nf_utils.py
inverse
AbinavRavi/MLGS2020
0
python
def inverse(self, y): raise NotImplementedError
def inverse(self, y): raise NotImplementedError<|docstring|>Compute f^-1(y) and inv_log_abs_det_jac(y).<|endoftext|>
5955b21b9dfe3574e41f0d22f60060dfd69efabcf7c56c03cad9c2d03b989bb7
def get_inverse(self): 'Get inverse transformation.' return InverseFlow(self)
Get inverse transformation.
project_1/nf_utils.py
get_inverse
AbinavRavi/MLGS2020
0
python
def get_inverse(self): return InverseFlow(self)
def get_inverse(self): return InverseFlow(self)<|docstring|>Get inverse transformation.<|endoftext|>
32b3b4839ecd1cf6b7bbe75832ed0ab7f20454368a22200e948aa09e244af0d4
def __init__(self, base_flow): 'Create the reverse flow from a base flow.\n\n Args:\n base_flow: flow to reverse.\n ' super().__init__() self.base_flow = base_flow if hasattr(base_flow, 'domain'): self.codomain = base_flow.domain if hasattr(base_flow, 'codomain'): self.domain = base_flow.codomain
Create the reverse flow from a base flow. Args: base_flow: flow to reverse.
project_1/nf_utils.py
__init__
AbinavRavi/MLGS2020
0
python
def __init__(self, base_flow): 'Create the reverse flow from a base flow.\n\n Args:\n base_flow: flow to reverse.\n ' super().__init__() self.base_flow = base_flow if hasattr(base_flow, 'domain'): self.codomain = base_flow.domain if hasattr(base_flow, 'codomain'): self.domain = base_flow.codomain
def __init__(self, base_flow): 'Create the reverse flow from a base flow.\n\n Args:\n base_flow: flow to reverse.\n ' super().__init__() self.base_flow = base_flow if hasattr(base_flow, 'domain'): self.codomain = base_flow.domain if hasattr(base_flow, 'codomain'): self.domain = base_flow.codomain<|docstring|>Create the reverse flow from a base flow. Args: base_flow: flow to reverse.<|endoftext|>
e11f9062d594fbeaaa106dede08cefd515b24f6371f410a1e7e74420e7d37bc5
def forward(self, x): 'Compute the forward transformation given an input x.\n\n Args:\n x: input sample. shape [batch_size, dim]\n\n Returns:\n y: sample after forward tranformation. shape [batch_size, dim]\n log_det_jac: log determinant of the jacobian of the forward tranformation, shape [batch_size]\n ' (y, log_det_jac) = self.base_flow.inverse(x) return (y, log_det_jac)
Compute the forward transformation given an input x. Args: x: input sample. shape [batch_size, dim] Returns: y: sample after forward tranformation. shape [batch_size, dim] log_det_jac: log determinant of the jacobian of the forward tranformation, shape [batch_size]
project_1/nf_utils.py
forward
AbinavRavi/MLGS2020
0
python
def forward(self, x): 'Compute the forward transformation given an input x.\n\n Args:\n x: input sample. shape [batch_size, dim]\n\n Returns:\n y: sample after forward tranformation. shape [batch_size, dim]\n log_det_jac: log determinant of the jacobian of the forward tranformation, shape [batch_size]\n ' (y, log_det_jac) = self.base_flow.inverse(x) return (y, log_det_jac)
def forward(self, x): 'Compute the forward transformation given an input x.\n\n Args:\n x: input sample. shape [batch_size, dim]\n\n Returns:\n y: sample after forward tranformation. shape [batch_size, dim]\n log_det_jac: log determinant of the jacobian of the forward tranformation, shape [batch_size]\n ' (y, log_det_jac) = self.base_flow.inverse(x) return (y, log_det_jac)<|docstring|>Compute the forward transformation given an input x. Args: x: input sample. shape [batch_size, dim] Returns: y: sample after forward tranformation. shape [batch_size, dim] log_det_jac: log determinant of the jacobian of the forward tranformation, shape [batch_size]<|endoftext|>
c390c6055c51f66b1ee706b5e21dab6fa4331b1ca0130932789e6b49c71abf9d
def inverse(self, y): 'Compute the inverse transformation given an input y.\n\n Args:\n y: input sample. shape [batch_size, dim]\n\n Returns:\n x: sample after inverse tranformation. shape [batch_size, dim]\n inv_log_det_jac: log determinant of the jacobian of the inverse tranformation, shape [batch_size]\n ' (x, inv_log_det_jac) = self.base_flow.forward(y) return (x, inv_log_det_jac)
Compute the inverse transformation given an input y. Args: y: input sample. shape [batch_size, dim] Returns: x: sample after inverse tranformation. shape [batch_size, dim] inv_log_det_jac: log determinant of the jacobian of the inverse tranformation, shape [batch_size]
project_1/nf_utils.py
inverse
AbinavRavi/MLGS2020
0
python
def inverse(self, y): 'Compute the inverse transformation given an input y.\n\n Args:\n y: input sample. shape [batch_size, dim]\n\n Returns:\n x: sample after inverse tranformation. shape [batch_size, dim]\n inv_log_det_jac: log determinant of the jacobian of the inverse tranformation, shape [batch_size]\n ' (x, inv_log_det_jac) = self.base_flow.forward(y) return (x, inv_log_det_jac)
def inverse(self, y): 'Compute the inverse transformation given an input y.\n\n Args:\n y: input sample. shape [batch_size, dim]\n\n Returns:\n x: sample after inverse tranformation. shape [batch_size, dim]\n inv_log_det_jac: log determinant of the jacobian of the inverse tranformation, shape [batch_size]\n ' (x, inv_log_det_jac) = self.base_flow.forward(y) return (x, inv_log_det_jac)<|docstring|>Compute the inverse transformation given an input y. Args: y: input sample. shape [batch_size, dim] Returns: x: sample after inverse tranformation. shape [batch_size, dim] inv_log_det_jac: log determinant of the jacobian of the inverse tranformation, shape [batch_size]<|endoftext|>
458f6fb600e0687bc049f6a493c7e4d608e47dc8d7fbc4e337ca5898a9ada47f
def __init__(self, n_gaussians=6, n_samples=100, radius=3.0, variance=0.3, seed=0): 'Create a 2D dataset with Gaussians on a circle.\n\n Args:\n n_gaussians: number of Gaussians. int\n n_samples: number of sample per Gaussian. int\n radius: radius of the circle where the Gaussian means lie. float\n varaince: varaince of the gaussians. float\n seed: random seed: int\n ' self.n_gaussians = n_gaussians self.n_samples = n_samples self.radius = radius self.variance = variance np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_gaussians, endpoint=False) mean_pos = (radius * np.column_stack((np.sin(radial_pos), np.cos(radial_pos)))) samples = [] for (ix, mean) in enumerate(mean_pos): sampled_points = (mean[(:, None)] + (np.random.normal(loc=0, scale=variance, size=n_samples), np.random.normal(loc=0, scale=variance, size=n_samples))) samples.append(sampled_points) p = np.random.permutation((self.n_gaussians * self.n_samples)) self.X = np.transpose(samples, (0, 2, 1)).reshape([(- 1), 2])[p]
Create a 2D dataset with Gaussians on a circle. Args: n_gaussians: number of Gaussians. int n_samples: number of sample per Gaussian. int radius: radius of the circle where the Gaussian means lie. float varaince: varaince of the gaussians. float seed: random seed: int
project_1/nf_utils.py
__init__
AbinavRavi/MLGS2020
0
python
def __init__(self, n_gaussians=6, n_samples=100, radius=3.0, variance=0.3, seed=0): 'Create a 2D dataset with Gaussians on a circle.\n\n Args:\n n_gaussians: number of Gaussians. int\n n_samples: number of sample per Gaussian. int\n radius: radius of the circle where the Gaussian means lie. float\n varaince: varaince of the gaussians. float\n seed: random seed: int\n ' self.n_gaussians = n_gaussians self.n_samples = n_samples self.radius = radius self.variance = variance np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_gaussians, endpoint=False) mean_pos = (radius * np.column_stack((np.sin(radial_pos), np.cos(radial_pos)))) samples = [] for (ix, mean) in enumerate(mean_pos): sampled_points = (mean[(:, None)] + (np.random.normal(loc=0, scale=variance, size=n_samples), np.random.normal(loc=0, scale=variance, size=n_samples))) samples.append(sampled_points) p = np.random.permutation((self.n_gaussians * self.n_samples)) self.X = np.transpose(samples, (0, 2, 1)).reshape([(- 1), 2])[p]
def __init__(self, n_gaussians=6, n_samples=100, radius=3.0, variance=0.3, seed=0): 'Create a 2D dataset with Gaussians on a circle.\n\n Args:\n n_gaussians: number of Gaussians. int\n n_samples: number of sample per Gaussian. int\n radius: radius of the circle where the Gaussian means lie. float\n varaince: varaince of the gaussians. float\n seed: random seed: int\n ' self.n_gaussians = n_gaussians self.n_samples = n_samples self.radius = radius self.variance = variance np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_gaussians, endpoint=False) mean_pos = (radius * np.column_stack((np.sin(radial_pos), np.cos(radial_pos)))) samples = [] for (ix, mean) in enumerate(mean_pos): sampled_points = (mean[(:, None)] + (np.random.normal(loc=0, scale=variance, size=n_samples), np.random.normal(loc=0, scale=variance, size=n_samples))) samples.append(sampled_points) p = np.random.permutation((self.n_gaussians * self.n_samples)) self.X = np.transpose(samples, (0, 2, 1)).reshape([(- 1), 2])[p]<|docstring|>Create a 2D dataset with Gaussians on a circle. Args: n_gaussians: number of Gaussians. int n_samples: number of sample per Gaussian. int radius: radius of the circle where the Gaussian means lie. float varaince: varaince of the gaussians. float seed: random seed: int<|endoftext|>
b50956ef7c3fa543f88e8b2d8439c55f72be6c0862865cd85bdf89e149f85e9d
def __init__(self, n_samples=1200, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_samples = n_samples np.random.seed(seed) (self.X, _) = make_moons(n_samples=n_samples, shuffle=True, noise=0.05, random_state=None)
Create a 2D dataset with spirals. Args: n_samples: number of sample per spiral. int seed: random seed: int
project_1/nf_utils.py
__init__
AbinavRavi/MLGS2020
0
python
def __init__(self, n_samples=1200, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_samples = n_samples np.random.seed(seed) (self.X, _) = make_moons(n_samples=n_samples, shuffle=True, noise=0.05, random_state=None)
def __init__(self, n_samples=1200, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_samples = n_samples np.random.seed(seed) (self.X, _) = make_moons(n_samples=n_samples, shuffle=True, noise=0.05, random_state=None)<|docstring|>Create a 2D dataset with spirals. Args: n_samples: number of sample per spiral. int seed: random seed: int<|endoftext|>
f33559629bc253506d1c043bbe28bd43e47d34180256c6914e0240f8cef3a9cd
def __init__(self, n_spirals=2, n_samples=600, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_spirals: number of spiral. int\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_spirals = n_spirals self.n_samples = n_samples np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_spirals, endpoint=False) samples = [] for (ix, radius) in enumerate(radial_pos): n = (((np.sqrt(np.random.rand(n_samples, 1)) * 540) * (2 * np.pi)) / 360) d1x = (((- np.cos(n)) * n) + (np.random.rand(n_samples, 1) * 0.5)) d1y = ((np.sin(n) * n) + (np.random.rand(n_samples, 1) * 0.5)) x = (np.vstack((np.hstack((d1x, d1y)), np.hstack(((- d1x), (- d1y))))) / 3) x += (np.random.randn(*x.shape) * 0.01) samples.append(x) p = np.random.permutation((self.n_spirals * self.n_samples)) self.X = np.concatenate(samples, axis=0)[p]
Create a 2D dataset with spirals. Args: n_spirals: number of spiral. int n_samples: number of sample per spiral. int seed: random seed: int
project_1/nf_utils.py
__init__
AbinavRavi/MLGS2020
0
python
def __init__(self, n_spirals=2, n_samples=600, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_spirals: number of spiral. int\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_spirals = n_spirals self.n_samples = n_samples np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_spirals, endpoint=False) samples = [] for (ix, radius) in enumerate(radial_pos): n = (((np.sqrt(np.random.rand(n_samples, 1)) * 540) * (2 * np.pi)) / 360) d1x = (((- np.cos(n)) * n) + (np.random.rand(n_samples, 1) * 0.5)) d1y = ((np.sin(n) * n) + (np.random.rand(n_samples, 1) * 0.5)) x = (np.vstack((np.hstack((d1x, d1y)), np.hstack(((- d1x), (- d1y))))) / 3) x += (np.random.randn(*x.shape) * 0.01) samples.append(x) p = np.random.permutation((self.n_spirals * self.n_samples)) self.X = np.concatenate(samples, axis=0)[p]
def __init__(self, n_spirals=2, n_samples=600, seed=0): 'Create a 2D dataset with spirals.\n\n Args:\n n_spirals: number of spiral. int\n n_samples: number of sample per spiral. int\n seed: random seed: int\n ' self.n_spirals = n_spirals self.n_samples = n_samples np.random.seed(seed) radial_pos = np.linspace(0, (np.pi * 2), num=n_spirals, endpoint=False) samples = [] for (ix, radius) in enumerate(radial_pos): n = (((np.sqrt(np.random.rand(n_samples, 1)) * 540) * (2 * np.pi)) / 360) d1x = (((- np.cos(n)) * n) + (np.random.rand(n_samples, 1) * 0.5)) d1y = ((np.sin(n) * n) + (np.random.rand(n_samples, 1) * 0.5)) x = (np.vstack((np.hstack((d1x, d1y)), np.hstack(((- d1x), (- d1y))))) / 3) x += (np.random.randn(*x.shape) * 0.01) samples.append(x) p = np.random.permutation((self.n_spirals * self.n_samples)) self.X = np.concatenate(samples, axis=0)[p]<|docstring|>Create a 2D dataset with spirals. Args: n_spirals: number of spiral. int n_samples: number of sample per spiral. int seed: random seed: int<|endoftext|>
2f93744271db46df6550b923650517acad5e21259a25fe0b10826a989238ce80
def create(input_path=None, output_path=None, **kw): "The XDW generator.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') if input_path: output_path = derivative_path(output_path) if (ext.upper() == '.PDF'): return create_from_pdf(input_path, output_path, **kw) if (ext.upper() in ('.BMP', '.JPG', '.JPEG', '.TIF', '.TIFF')): try: return create_from_image(input_path, output_path, **kw) except Exception as e: pass return create_from_app(input_path, output_path, **kw) output_path = derivative_path(adjust_path((output_path or 'blank.xdw'))) with open(output_path, 'wb') as f: f.write(BLANKPAGE) return output_path
The XDW generator. Returns actual pathname of generated document, which may be different from `output_path' argument.
xdwlib/document.py
create
hayasix/xdwlib
12
python
def create(input_path=None, output_path=None, **kw): "The XDW generator.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') if input_path: output_path = derivative_path(output_path) if (ext.upper() == '.PDF'): return create_from_pdf(input_path, output_path, **kw) if (ext.upper() in ('.BMP', '.JPG', '.JPEG', '.TIF', '.TIFF')): try: return create_from_image(input_path, output_path, **kw) except Exception as e: pass return create_from_app(input_path, output_path, **kw) output_path = derivative_path(adjust_path((output_path or 'blank.xdw'))) with open(output_path, 'wb') as f: f.write(BLANKPAGE) return output_path
def create(input_path=None, output_path=None, **kw): "The XDW generator.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') if input_path: output_path = derivative_path(output_path) if (ext.upper() == '.PDF'): return create_from_pdf(input_path, output_path, **kw) if (ext.upper() in ('.BMP', '.JPG', '.JPEG', '.TIF', '.TIFF')): try: return create_from_image(input_path, output_path, **kw) except Exception as e: pass return create_from_app(input_path, output_path, **kw) output_path = derivative_path(adjust_path((output_path or 'blank.xdw'))) with open(output_path, 'wb') as f: f.write(BLANKPAGE) return output_path<|docstring|>The XDW generator. Returns actual pathname of generated document, which may be different from `output_path' argument.<|endoftext|>
77091f80424a352ca15178f421d9fe5022352a79110d4b38c964259ae0edef6a
def create_from_image(input_path, output_path=None, fitimage='FITDEF', compress='NORMAL', zoom=0, size=Point(0, 0), align=('CENTER', 'CENTER'), maxpapersize='DEFAULT'): "XDW generator from image file.\n\n fitimage 'FITDEF' | 'FIT' | 'FITDEF_DIVIDEBMP' |\n 'USERDEF' | 'USERDEF_FIT'\n compress 'NORMAL' | 'LOSSLESS' | 'NOCOMPRESS' |\n 'HIGHQUALITY' | 'HIGHCOMPRESS' |\n 'JPEG' | 'JPEG_TTN2' | 'PACKBITS' | 'G4' |\n 'MRC_NORMAL' | 'MRC_HIGHQUALITY' | 'MRC_HIGHCOMPRESS'\n zoom (float) in percent; 0 means 100%. < 1/1000 is ignored.\n size (Point) in mm; for fitimange 'userdef' or 'userdef_fit'\n (int) 1=A3R, 2=A3, 3=A4R, 4=A4, 5=A5R, 6=A5,\n 7=B4R, 8=B4, 9=B5R, 10=B5\n align (horiz, vert) where:\n horiz 'CENTER' | 'LEFT' | 'RIGHT'\n vert 'CENTER' | 'TOP' | 'BOTTOM'\n maxpapersize 'DEFAULT' | 'A3' | '2A0'\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) opt = XDW_CREATE_OPTION_EX2() opt.nFitImage = XDW_CREATE_FITIMAGE.normalize(fitimage) opt.nCompress = XDW_COMPRESS.normalize(compress) opt.nZoomDetail = int((zoom * 1000)) if (not isinstance(size, Point)): size = XDW_SIZE.normalize(size) size = XDW_SIZE_MM[(size or 3)] size = Point(*size) opt.nWidth = int((size.x * 100)) opt.nHeight = int((size.y * 100)) opt.nHorPos = XDW_CREATE_HPOS.normalize(align[0]) opt.nVerPos = XDW_CREATE_VPOS.normalize(align[1]) opt.nMaxPaperSize = XDW_CREATE_MAXPAPERSIZE.normalize(maxpapersize) if (XDWVER < 8): XDW_CreateXdwFromImageFile(cp(input_path), cp(output_path), opt) else: XDW_CreateXdwFromImageFileW(input_path, output_path, opt) return output_path
XDW generator from image file. fitimage 'FITDEF' | 'FIT' | 'FITDEF_DIVIDEBMP' | 'USERDEF' | 'USERDEF_FIT' compress 'NORMAL' | 'LOSSLESS' | 'NOCOMPRESS' | 'HIGHQUALITY' | 'HIGHCOMPRESS' | 'JPEG' | 'JPEG_TTN2' | 'PACKBITS' | 'G4' | 'MRC_NORMAL' | 'MRC_HIGHQUALITY' | 'MRC_HIGHCOMPRESS' zoom (float) in percent; 0 means 100%. < 1/1000 is ignored. size (Point) in mm; for fitimange 'userdef' or 'userdef_fit' (int) 1=A3R, 2=A3, 3=A4R, 4=A4, 5=A5R, 6=A5, 7=B4R, 8=B4, 9=B5R, 10=B5 align (horiz, vert) where: horiz 'CENTER' | 'LEFT' | 'RIGHT' vert 'CENTER' | 'TOP' | 'BOTTOM' maxpapersize 'DEFAULT' | 'A3' | '2A0' Returns actual pathname of generated document, which may be different from `output_path' argument.
xdwlib/document.py
create_from_image
hayasix/xdwlib
12
python
def create_from_image(input_path, output_path=None, fitimage='FITDEF', compress='NORMAL', zoom=0, size=Point(0, 0), align=('CENTER', 'CENTER'), maxpapersize='DEFAULT'): "XDW generator from image file.\n\n fitimage 'FITDEF' | 'FIT' | 'FITDEF_DIVIDEBMP' |\n 'USERDEF' | 'USERDEF_FIT'\n compress 'NORMAL' | 'LOSSLESS' | 'NOCOMPRESS' |\n 'HIGHQUALITY' | 'HIGHCOMPRESS' |\n 'JPEG' | 'JPEG_TTN2' | 'PACKBITS' | 'G4' |\n 'MRC_NORMAL' | 'MRC_HIGHQUALITY' | 'MRC_HIGHCOMPRESS'\n zoom (float) in percent; 0 means 100%. < 1/1000 is ignored.\n size (Point) in mm; for fitimange 'userdef' or 'userdef_fit'\n (int) 1=A3R, 2=A3, 3=A4R, 4=A4, 5=A5R, 6=A5,\n 7=B4R, 8=B4, 9=B5R, 10=B5\n align (horiz, vert) where:\n horiz 'CENTER' | 'LEFT' | 'RIGHT'\n vert 'CENTER' | 'TOP' | 'BOTTOM'\n maxpapersize 'DEFAULT' | 'A3' | '2A0'\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) opt = XDW_CREATE_OPTION_EX2() opt.nFitImage = XDW_CREATE_FITIMAGE.normalize(fitimage) opt.nCompress = XDW_COMPRESS.normalize(compress) opt.nZoomDetail = int((zoom * 1000)) if (not isinstance(size, Point)): size = XDW_SIZE.normalize(size) size = XDW_SIZE_MM[(size or 3)] size = Point(*size) opt.nWidth = int((size.x * 100)) opt.nHeight = int((size.y * 100)) opt.nHorPos = XDW_CREATE_HPOS.normalize(align[0]) opt.nVerPos = XDW_CREATE_VPOS.normalize(align[1]) opt.nMaxPaperSize = XDW_CREATE_MAXPAPERSIZE.normalize(maxpapersize) if (XDWVER < 8): XDW_CreateXdwFromImageFile(cp(input_path), cp(output_path), opt) else: XDW_CreateXdwFromImageFileW(input_path, output_path, opt) return output_path
def create_from_image(input_path, output_path=None, fitimage='FITDEF', compress='NORMAL', zoom=0, size=Point(0, 0), align=('CENTER', 'CENTER'), maxpapersize='DEFAULT'): "XDW generator from image file.\n\n fitimage 'FITDEF' | 'FIT' | 'FITDEF_DIVIDEBMP' |\n 'USERDEF' | 'USERDEF_FIT'\n compress 'NORMAL' | 'LOSSLESS' | 'NOCOMPRESS' |\n 'HIGHQUALITY' | 'HIGHCOMPRESS' |\n 'JPEG' | 'JPEG_TTN2' | 'PACKBITS' | 'G4' |\n 'MRC_NORMAL' | 'MRC_HIGHQUALITY' | 'MRC_HIGHCOMPRESS'\n zoom (float) in percent; 0 means 100%. < 1/1000 is ignored.\n size (Point) in mm; for fitimange 'userdef' or 'userdef_fit'\n (int) 1=A3R, 2=A3, 3=A4R, 4=A4, 5=A5R, 6=A5,\n 7=B4R, 8=B4, 9=B5R, 10=B5\n align (horiz, vert) where:\n horiz 'CENTER' | 'LEFT' | 'RIGHT'\n vert 'CENTER' | 'TOP' | 'BOTTOM'\n maxpapersize 'DEFAULT' | 'A3' | '2A0'\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) opt = XDW_CREATE_OPTION_EX2() opt.nFitImage = XDW_CREATE_FITIMAGE.normalize(fitimage) opt.nCompress = XDW_COMPRESS.normalize(compress) opt.nZoomDetail = int((zoom * 1000)) if (not isinstance(size, Point)): size = XDW_SIZE.normalize(size) size = XDW_SIZE_MM[(size or 3)] size = Point(*size) opt.nWidth = int((size.x * 100)) opt.nHeight = int((size.y * 100)) opt.nHorPos = XDW_CREATE_HPOS.normalize(align[0]) opt.nVerPos = XDW_CREATE_VPOS.normalize(align[1]) opt.nMaxPaperSize = XDW_CREATE_MAXPAPERSIZE.normalize(maxpapersize) if (XDWVER < 8): XDW_CreateXdwFromImageFile(cp(input_path), cp(output_path), opt) else: XDW_CreateXdwFromImageFileW(input_path, output_path, opt) return output_path<|docstring|>XDW generator from image file. fitimage 'FITDEF' | 'FIT' | 'FITDEF_DIVIDEBMP' | 'USERDEF' | 'USERDEF_FIT' compress 'NORMAL' | 'LOSSLESS' | 'NOCOMPRESS' | 'HIGHQUALITY' | 'HIGHCOMPRESS' | 'JPEG' | 'JPEG_TTN2' | 'PACKBITS' | 'G4' | 'MRC_NORMAL' | 'MRC_HIGHQUALITY' | 'MRC_HIGHCOMPRESS' zoom (float) in percent; 0 means 100%. < 1/1000 is ignored. size (Point) in mm; for fitimange 'userdef' or 'userdef_fit' (int) 1=A3R, 2=A3, 3=A4R, 4=A4, 5=A5R, 6=A5, 7=B4R, 8=B4, 9=B5R, 10=B5 align (horiz, vert) where: horiz 'CENTER' | 'LEFT' | 'RIGHT' vert 'CENTER' | 'TOP' | 'BOTTOM' maxpapersize 'DEFAULT' | 'A3' | '2A0' Returns actual pathname of generated document, which may be different from `output_path' argument.<|endoftext|>
36a33c54d1aea475b3aab25a67bff3a523978b226d64d8a453df486acb6ca158
def create_from_pdf(input_path, output_path=None): "XDW generator from image PDF file.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) try: if (XDWVER < 8): XDW_CreateXdwFromImagePdfFile(cp(input_path), cp(output_path)) else: XDW_CreateXdwFromImagePdfFileW(input_path, output_path) except Exception as e: create_from_app(input_path, output_path, timeout=3600) return output_path
XDW generator from image PDF file. Returns actual pathname of generated document, which may be different from `output_path' argument.
xdwlib/document.py
create_from_pdf
hayasix/xdwlib
12
python
def create_from_pdf(input_path, output_path=None): "XDW generator from image PDF file.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) try: if (XDWVER < 8): XDW_CreateXdwFromImagePdfFile(cp(input_path), cp(output_path)) else: XDW_CreateXdwFromImagePdfFileW(input_path, output_path) except Exception as e: create_from_app(input_path, output_path, timeout=3600) return output_path
def create_from_pdf(input_path, output_path=None): "XDW generator from image PDF file.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) try: if (XDWVER < 8): XDW_CreateXdwFromImagePdfFile(cp(input_path), cp(output_path)) else: XDW_CreateXdwFromImagePdfFileW(input_path, output_path) except Exception as e: create_from_app(input_path, output_path, timeout=3600) return output_path<|docstring|>XDW generator from image PDF file. Returns actual pathname of generated document, which may be different from `output_path' argument.<|endoftext|>
a2373f76e22069baa8bf2ee9b8868db23dcbbca2004aaeffcbd2f414e2c8e961
def create_from_app(input_path, output_path=None, attachment=False, timeout=0): "Create document through other app with optional attachment.\n\n attachment (bool) attach original data file (given by input_path) or not\n timeout (int) max seconds to wait until application printing is done\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): handle = XDW_BeginCreationFromAppFile(cp(input_path), cp(output_path), bool(attachment)) else: handle = XDW_BeginCreationFromAppFileW(input_path, output_path, bool(attachment)) st = time.time() try: while True: status = XDW_GetStatusCreationFromAppFile(handle) if (status.phase in (XDW_CRTP_FINISHED, XDW_CRTP_CANCELED, XDW_CRTP_CANCELING)): break if (timeout and (timeout < (time.time() - st))): XDW_CancelCreationFromAppFile(handle) break time.sleep(2) finally: XDW_EndCreationFromAppFile(handle) return output_path
Create document through other app with optional attachment. attachment (bool) attach original data file (given by input_path) or not timeout (int) max seconds to wait until application printing is done Returns actual pathname of generated document, which may be different from `output_path' argument.
xdwlib/document.py
create_from_app
hayasix/xdwlib
12
python
def create_from_app(input_path, output_path=None, attachment=False, timeout=0): "Create document through other app with optional attachment.\n\n attachment (bool) attach original data file (given by input_path) or not\n timeout (int) max seconds to wait until application printing is done\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): handle = XDW_BeginCreationFromAppFile(cp(input_path), cp(output_path), bool(attachment)) else: handle = XDW_BeginCreationFromAppFileW(input_path, output_path, bool(attachment)) st = time.time() try: while True: status = XDW_GetStatusCreationFromAppFile(handle) if (status.phase in (XDW_CRTP_FINISHED, XDW_CRTP_CANCELED, XDW_CRTP_CANCELING)): break if (timeout and (timeout < (time.time() - st))): XDW_CancelCreationFromAppFile(handle) break time.sleep(2) finally: XDW_EndCreationFromAppFile(handle) return output_path
def create_from_app(input_path, output_path=None, attachment=False, timeout=0): "Create document through other app with optional attachment.\n\n attachment (bool) attach original data file (given by input_path) or not\n timeout (int) max seconds to wait until application printing is done\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_path = adjust_path(input_path) (root, ext) = os.path.splitext(input_path) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): handle = XDW_BeginCreationFromAppFile(cp(input_path), cp(output_path), bool(attachment)) else: handle = XDW_BeginCreationFromAppFileW(input_path, output_path, bool(attachment)) st = time.time() try: while True: status = XDW_GetStatusCreationFromAppFile(handle) if (status.phase in (XDW_CRTP_FINISHED, XDW_CRTP_CANCELED, XDW_CRTP_CANCELING)): break if (timeout and (timeout < (time.time() - st))): XDW_CancelCreationFromAppFile(handle) break time.sleep(2) finally: XDW_EndCreationFromAppFile(handle) return output_path<|docstring|>Create document through other app with optional attachment. attachment (bool) attach original data file (given by input_path) or not timeout (int) max seconds to wait until application printing is done Returns actual pathname of generated document, which may be different from `output_path' argument.<|endoftext|>
b0f41e14a76f83771df942325aef1ea56584429b8938aac26609d40bbfcf6541
def merge(input_paths, output_path=None): "Merge XDW's into a new XDW.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_paths = [adjust_path(path) for path in input_paths] (root, ext) = os.path.splitext(input_paths[0]) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): XDW_MergeXdwFiles(map(cp, input_paths), cp(output_path)) else: XDW_MergeXdwFilesW(input_paths, output_path) return output_path
Merge XDW's into a new XDW. Returns actual pathname of generated document, which may be different from `output_path' argument.
xdwlib/document.py
merge
hayasix/xdwlib
12
python
def merge(input_paths, output_path=None): "Merge XDW's into a new XDW.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_paths = [adjust_path(path) for path in input_paths] (root, ext) = os.path.splitext(input_paths[0]) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): XDW_MergeXdwFiles(map(cp, input_paths), cp(output_path)) else: XDW_MergeXdwFilesW(input_paths, output_path) return output_path
def merge(input_paths, output_path=None): "Merge XDW's into a new XDW.\n\n Returns actual pathname of generated document, which may be different\n from `output_path' argument.\n " input_paths = [adjust_path(path) for path in input_paths] (root, ext) = os.path.splitext(input_paths[0]) output_path = adjust_path((output_path or root), ext='.xdw') output_path = derivative_path(output_path) if (XDWVER < 8): XDW_MergeXdwFiles(map(cp, input_paths), cp(output_path)) else: XDW_MergeXdwFilesW(input_paths, output_path) return output_path<|docstring|>Merge XDW's into a new XDW. Returns actual pathname of generated document, which may be different from `output_path' argument.<|endoftext|>
973d66724acf690ee63c000b99fb5595f0f57d5ce9cdbc23bf42ab2ca9d26794
def absolute_page(self, pos, append=False): 'Concrete method over absolute_page().' pos = self._pos(pos, append=append) return pos
Concrete method over absolute_page().
xdwlib/document.py
absolute_page
hayasix/xdwlib
12
python
def absolute_page(self, pos, append=False): pos = self._pos(pos, append=append) return pos
def absolute_page(self, pos, append=False): pos = self._pos(pos, append=append) return pos<|docstring|>Concrete method over absolute_page().<|endoftext|>
4dd8705249d6cc531b220fc974d39d291689f59de77376b076600a1b2a5ddd42
def update_pages(self): 'Concrete method over update_pages().' XDWFile.update_pages(self)
Concrete method over update_pages().
xdwlib/document.py
update_pages
hayasix/xdwlib
12
python
def update_pages(self): XDWFile.update_pages(self)
def update_pages(self): XDWFile.update_pages(self)<|docstring|>Concrete method over update_pages().<|endoftext|>
ccbc36c68d02a3e62ab46adc139aa7a4736a8498a23446f906fc97245e96278b
def dirname(self): 'Concrete method over dirname().' return self.dir
Concrete method over dirname().
xdwlib/document.py
dirname
hayasix/xdwlib
12
python
def dirname(self): return self.dir
def dirname(self): return self.dir<|docstring|>Concrete method over dirname().<|endoftext|>
b38f88c18c278ea52a2cca01f960639db4971d2acc52aa0d33b79ca4e6261e20
def retrieve_waiver_claim_information(raw_data): '\n Retrieves transaction information for a waiver claim, e.g. *Claimed ...\n off waivers from the ...*\n ' if raw_data.endswith('.'): raw_data = raw_data[:(- 1)] match = re.search(CLAIM_FROM_REGEX, raw_data) try: (pos, plr_name, team_name) = match.group(1, 2, 3) except Exception as e: print("+ Unable to retrieve feasible information from '%s'", raw_data) return (pos, plr_name, team_name)
Retrieves transaction information for a waiver claim, e.g. *Claimed ... off waivers from the ...*
_get_transactions.py
retrieve_waiver_claim_information
leaffan/pynhldb
3
python
def retrieve_waiver_claim_information(raw_data): '\n Retrieves transaction information for a waiver claim, e.g. *Claimed ...\n off waivers from the ...*\n ' if raw_data.endswith('.'): raw_data = raw_data[:(- 1)] match = re.search(CLAIM_FROM_REGEX, raw_data) try: (pos, plr_name, team_name) = match.group(1, 2, 3) except Exception as e: print("+ Unable to retrieve feasible information from '%s'", raw_data) return (pos, plr_name, team_name)
def retrieve_waiver_claim_information(raw_data): '\n Retrieves transaction information for a waiver claim, e.g. *Claimed ...\n off waivers from the ...*\n ' if raw_data.endswith('.'): raw_data = raw_data[:(- 1)] match = re.search(CLAIM_FROM_REGEX, raw_data) try: (pos, plr_name, team_name) = match.group(1, 2, 3) except Exception as e: print("+ Unable to retrieve feasible information from '%s'", raw_data) return (pos, plr_name, team_name)<|docstring|>Retrieves transaction information for a waiver claim, e.g. *Claimed ... off waivers from the ...*<|endoftext|>
ab21db7666361197e6210e023e938d9ace11c39a20ca307443f0ecb7a45e3905
def retrieve_waiver_claim(transaction_raw_data): '\n Retrieves transaction properties for a waiver claim.\n ' (position, plr_name, other_team_name) = retrieve_waiver_claim_information(transaction_raw_data) other_team = Team.find_by_name(other_team_name) if (other_team is None): print(('+ Unable to find second team in ' + ("transaction in '%s'" % transaction_raw_data))) return position = position[0] plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.split(' ', 2) plr = Player.find_by_name_extended(first_name, last_name) if (plr is None): print(('+ Unable to find transferred player ' + ("in '%s'" % transaction_raw_data))) return return (plr, other_team)
Retrieves transaction properties for a waiver claim.
_get_transactions.py
retrieve_waiver_claim
leaffan/pynhldb
3
python
def retrieve_waiver_claim(transaction_raw_data): '\n \n ' (position, plr_name, other_team_name) = retrieve_waiver_claim_information(transaction_raw_data) other_team = Team.find_by_name(other_team_name) if (other_team is None): print(('+ Unable to find second team in ' + ("transaction in '%s'" % transaction_raw_data))) return position = position[0] plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.split(' ', 2) plr = Player.find_by_name_extended(first_name, last_name) if (plr is None): print(('+ Unable to find transferred player ' + ("in '%s'" % transaction_raw_data))) return return (plr, other_team)
def retrieve_waiver_claim(transaction_raw_data): '\n \n ' (position, plr_name, other_team_name) = retrieve_waiver_claim_information(transaction_raw_data) other_team = Team.find_by_name(other_team_name) if (other_team is None): print(('+ Unable to find second team in ' + ("transaction in '%s'" % transaction_raw_data))) return position = position[0] plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.split(' ', 2) plr = Player.find_by_name_extended(first_name, last_name) if (plr is None): print(('+ Unable to find transferred player ' + ("in '%s'" % transaction_raw_data))) return return (plr, other_team)<|docstring|>Retrieves transaction properties for a waiver claim.<|endoftext|>
486931eb9dbc0346c35c56e73faf29606083f6629f12cb4b836848e84fb05bb2
def find_player_in_transaction(position, plr_name): '\n Finds actual player in database.\n ' plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.strip().split(' ', 2)[:2] plr = Player.find_by_name_extended(first_name, last_name) return plr
Finds actual player in database.
_get_transactions.py
find_player_in_transaction
leaffan/pynhldb
3
python
def find_player_in_transaction(position, plr_name): '\n \n ' plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.strip().split(' ', 2)[:2] plr = Player.find_by_name_extended(first_name, last_name) return plr
def find_player_in_transaction(position, plr_name): '\n \n ' plr = Player.find_by_full_name(plr_name, position[0]) if (plr is None): plr = Player.find_by_full_name(plr_name) if (plr is None): (first_name, last_name) = plr_name.strip().split(' ', 2)[:2] plr = Player.find_by_name_extended(first_name, last_name) return plr<|docstring|>Finds actual player in database.<|endoftext|>
6d022a7747ccd060f609de8f530eaa008372094eff47302564690f78f7a9fef5
def retrieve_signing_information(transaction_raw_data): '\n Retrieves transaction properties for a contract signing.\n ' signings = list() if any(((s in transaction_raw_data) for s in ['extension', 'offer sheet', 'tryout'])): return signings if ('contracts' in transaction_raw_data): match = re.search(MULTIPLE_SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: length = match.group(2) tokens = [s.strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = match.group(2) signings.append((position, plr_name, length)) else: if token.startswith('who'): continue signings.append((position, token, length)) else: print(('+ Unable to retrieve feasible information about multiple ' + ("contract signings from '%s'" % transaction_raw_data))) elif ('contract' in transaction): match = re.search(SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = match.group(2) length = match.group(3) signings.append((position, plr_name, length)) else: print(('+ Unable to retrieve single contract signing ' + ("from '%s'" % transaction_raw_data))) elif ('and ' in transaction): match = re.search(MULTIPLE_SIGNING, transaction_raw_data) if match: tokens = [re.sub('\\.$', '', s).strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', '', match.group(2)) plr_name = match.group(2) signings.append((position, plr_name)) else: if token.startswith('who'): continue signings.append((position, token)) else: match = re.search(SIGNING_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', '', match.group(2)) signings.append((position, plr_name)) else: print(('+ Unable to retrieve single signing ' + ("from '%s'" % transaction_raw_data))) return signings
Retrieves transaction properties for a contract signing.
_get_transactions.py
retrieve_signing_information
leaffan/pynhldb
3
python
def retrieve_signing_information(transaction_raw_data): '\n \n ' signings = list() if any(((s in transaction_raw_data) for s in ['extension', 'offer sheet', 'tryout'])): return signings if ('contracts' in transaction_raw_data): match = re.search(MULTIPLE_SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: length = match.group(2) tokens = [s.strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = match.group(2) signings.append((position, plr_name, length)) else: if token.startswith('who'): continue signings.append((position, token, length)) else: print(('+ Unable to retrieve feasible information about multiple ' + ("contract signings from '%s'" % transaction_raw_data))) elif ('contract' in transaction): match = re.search(SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = match.group(2) length = match.group(3) signings.append((position, plr_name, length)) else: print(('+ Unable to retrieve single contract signing ' + ("from '%s'" % transaction_raw_data))) elif ('and ' in transaction): match = re.search(MULTIPLE_SIGNING, transaction_raw_data) if match: tokens = [re.sub('\\.$', , s).strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', , match.group(2)) plr_name = match.group(2) signings.append((position, plr_name)) else: if token.startswith('who'): continue signings.append((position, token)) else: match = re.search(SIGNING_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', , match.group(2)) signings.append((position, plr_name)) else: print(('+ Unable to retrieve single signing ' + ("from '%s'" % transaction_raw_data))) return signings
def retrieve_signing_information(transaction_raw_data): '\n \n ' signings = list() if any(((s in transaction_raw_data) for s in ['extension', 'offer sheet', 'tryout'])): return signings if ('contracts' in transaction_raw_data): match = re.search(MULTIPLE_SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: length = match.group(2) tokens = [s.strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = match.group(2) signings.append((position, plr_name, length)) else: if token.startswith('who'): continue signings.append((position, token, length)) else: print(('+ Unable to retrieve feasible information about multiple ' + ("contract signings from '%s'" % transaction_raw_data))) elif ('contract' in transaction): match = re.search(SIGNING_WITH_CONTRACT_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = match.group(2) length = match.group(3) signings.append((position, plr_name, length)) else: print(('+ Unable to retrieve single contract signing ' + ("from '%s'" % transaction_raw_data))) elif ('and ' in transaction): match = re.search(MULTIPLE_SIGNING, transaction_raw_data) if match: tokens = [re.sub('\\.$', , s).strip() for s in re.split(',\\s?|and ', match.group(1)) if s] for token in tokens: match = re.search(('(%s)\\s(.+)' % '|'.join((POSITIONS + POSITION_PLURALS))), token) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', , match.group(2)) plr_name = match.group(2) signings.append((position, plr_name)) else: if token.startswith('who'): continue signings.append((position, token)) else: match = re.search(SIGNING_REGEX, transaction_raw_data) if match: position = match.group(1)[0].upper() plr_name = re.sub('\\.$', , match.group(2)) signings.append((position, plr_name)) else: print(('+ Unable to retrieve single signing ' + ("from '%s'" % transaction_raw_data))) return signings<|docstring|>Retrieves transaction properties for a contract signing.<|endoftext|>
7e072c32ae5a6bbc1d27acc23b1de1d1f59c8d1c97c542d80571f9edd61b9bc4
def list_by_alert_rule(self, resource_group_name, workspace_name, rule_id, **kwargs): "Gets all actions of alert rule.\n\n :param resource_group_name: The name of the resource group within the user's subscription. The\n name is case insensitive.\n :type resource_group_name: str\n :param workspace_name: The name of the workspace.\n :type workspace_name: str\n :param rule_id: Alert rule ID.\n :type rule_id: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either ActionsList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.ActionsList]\n :raises: ~azure.core.exceptions.HttpResponseError\n " cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-01-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list_by_alert_rule.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', pattern='^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'workspaceName': self._serialize.url('workspace_name', workspace_name, 'str', max_length=90, min_length=1), 'ruleId': self._serialize.url('rule_id', rule_id, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ActionsList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
Gets all actions of alert rule. :param resource_group_name: The name of the resource group within the user's subscription. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param rule_id: Alert rule ID. :type rule_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionsList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.ActionsList] :raises: ~azure.core.exceptions.HttpResponseError
sdk/securityinsight/azure-mgmt-securityinsight/azure/mgmt/securityinsight/operations/_actions_operations.py
list_by_alert_rule
jayachithra/azure-sdk-for-python
2,728
python
def list_by_alert_rule(self, resource_group_name, workspace_name, rule_id, **kwargs): "Gets all actions of alert rule.\n\n :param resource_group_name: The name of the resource group within the user's subscription. The\n name is case insensitive.\n :type resource_group_name: str\n :param workspace_name: The name of the workspace.\n :type workspace_name: str\n :param rule_id: Alert rule ID.\n :type rule_id: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either ActionsList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.ActionsList]\n :raises: ~azure.core.exceptions.HttpResponseError\n " cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-01-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list_by_alert_rule.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', pattern='^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'workspaceName': self._serialize.url('workspace_name', workspace_name, 'str', max_length=90, min_length=1), 'ruleId': self._serialize.url('rule_id', rule_id, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ActionsList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
def list_by_alert_rule(self, resource_group_name, workspace_name, rule_id, **kwargs): "Gets all actions of alert rule.\n\n :param resource_group_name: The name of the resource group within the user's subscription. The\n name is case insensitive.\n :type resource_group_name: str\n :param workspace_name: The name of the workspace.\n :type workspace_name: str\n :param rule_id: Alert rule ID.\n :type rule_id: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either ActionsList or the result of cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.ActionsList]\n :raises: ~azure.core.exceptions.HttpResponseError\n " cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = '2020-01-01' accept = 'application/json' def prepare_request(next_link=None): header_parameters = {} header_parameters['Accept'] = self._serialize.header('accept', accept, 'str') if (not next_link): url = self.list_by_alert_rule.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', pattern='^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$'), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1, pattern='^[-\\w\\._\\(\\)]+$'), 'workspaceName': self._serialize.url('workspace_name', workspace_name, 'str', max_length=90, min_length=1), 'ruleId': self._serialize.url('rule_id', rule_id, 'str')} url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ActionsList', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)<|docstring|>Gets all actions of alert rule. :param resource_group_name: The name of the resource group within the user's subscription. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param rule_id: Alert rule ID. :type rule_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionsList or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securityinsight.models.ActionsList] :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
78d6c549f02ca682844dcd260f6c14b6bcb7109fb5cd2433188a06d078a1aaba
def _drawBoundingBox(self, videoWidth, point1, point2, boundingBox, color, thickness): 'Method for drawing rectangle according to points' if boundingBox.is_on_border(): rightBorderPoint = ((videoWidth - 1), point2[1]) cv2.rectangle(self.frame, point1, rightBorderPoint, color, thickness) leftBorderPoint = (0, point1[1]) cv2.rectangle(self.frame, leftBorderPoint, point2, color, thickness) else: cv2.rectangle(self.frame, point1, point2, color, thickness)
Method for drawing rectangle according to points
code/modified_TracKit/siamdw_360_border.py
_drawBoundingBox
VitaAmbroz/360Tracking
2
python
def _drawBoundingBox(self, videoWidth, point1, point2, boundingBox, color, thickness): if boundingBox.is_on_border(): rightBorderPoint = ((videoWidth - 1), point2[1]) cv2.rectangle(self.frame, point1, rightBorderPoint, color, thickness) leftBorderPoint = (0, point1[1]) cv2.rectangle(self.frame, leftBorderPoint, point2, color, thickness) else: cv2.rectangle(self.frame, point1, point2, color, thickness)
def _drawBoundingBox(self, videoWidth, point1, point2, boundingBox, color, thickness): if boundingBox.is_on_border(): rightBorderPoint = ((videoWidth - 1), point2[1]) cv2.rectangle(self.frame, point1, rightBorderPoint, color, thickness) leftBorderPoint = (0, point1[1]) cv2.rectangle(self.frame, leftBorderPoint, point2, color, thickness) else: cv2.rectangle(self.frame, point1, point2, color, thickness)<|docstring|>Method for drawing rectangle according to points<|endoftext|>
7b44cfa0e5240a3152c6d3b62a865f883422bb12b395713ef5256a2b77fb16ce
def _checkBoundsOfPointStrict(self, point): 'Checks if given point is in interval [0,self.width] and [0,self.height]' x = point[0] y = point[1] if (x < 0): x = 0 elif (x > (self.video_width - 1)): x = (self.video_width - 1) if (y < 0): y = 0 elif (y > (self.video_height - 1)): y = (self.video_height - 1) point = (x, y) return point
Checks if given point is in interval [0,self.width] and [0,self.height]
code/modified_TracKit/siamdw_360_border.py
_checkBoundsOfPointStrict
VitaAmbroz/360Tracking
2
python
def _checkBoundsOfPointStrict(self, point): x = point[0] y = point[1] if (x < 0): x = 0 elif (x > (self.video_width - 1)): x = (self.video_width - 1) if (y < 0): y = 0 elif (y > (self.video_height - 1)): y = (self.video_height - 1) point = (x, y) return point
def _checkBoundsOfPointStrict(self, point): x = point[0] y = point[1] if (x < 0): x = 0 elif (x > (self.video_width - 1)): x = (self.video_width - 1) if (y < 0): y = 0 elif (y > (self.video_height - 1)): y = (self.video_height - 1) point = (x, y) return point<|docstring|>Checks if given point is in interval [0,self.width] and [0,self.height]<|endoftext|>
ee349c62a639c381b0c8c70c6750e327f441feb65c12e4301fe75e5aabd1ecb0
def _saveResults(self): 'Method for saving result bounding boxes to .txt file' resultData = self.parser.createAnnotations(self.result_bounding_boxes) self.parser.saveDataToFile(self.save_result_path, resultData) print((((("File '" + self.save_result_path) + "' has been successfully created with total ") + str(len(self.result_bounding_boxes))) + ' computed frames.'))
Method for saving result bounding boxes to .txt file
code/modified_TracKit/siamdw_360_border.py
_saveResults
VitaAmbroz/360Tracking
2
python
def _saveResults(self): resultData = self.parser.createAnnotations(self.result_bounding_boxes) self.parser.saveDataToFile(self.save_result_path, resultData) print((((("File '" + self.save_result_path) + "' has been successfully created with total ") + str(len(self.result_bounding_boxes))) + ' computed frames.'))
def _saveResults(self): resultData = self.parser.createAnnotations(self.result_bounding_boxes) self.parser.saveDataToFile(self.save_result_path, resultData) print((((("File '" + self.save_result_path) + "' has been successfully created with total ") + str(len(self.result_bounding_boxes))) + ' computed frames.'))<|docstring|>Method for saving result bounding boxes to .txt file<|endoftext|>
88c130f1a472887b7e7921e712cac83703f0c370fac61c49134710577e38e0fd
def run_siamdw_border(self): 'Method for start SiamDW tracking with improvement of object crossing left/right border in equirectangular projection' info = edict() info.arch = self.arch info.dataset = self.video info.epoch_test = True info.cls_type = 'thinner' net = models.__dict__[self.arch]() tracker = SiamFC(info) print('[*] ======= Track video with {} ======='.format(self.arch)) print(self.resume) net = load_pretrain(net, self.resume) net.eval() net = net.cuda() self._track_video(tracker, net)
Method for start SiamDW tracking with improvement of object crossing left/right border in equirectangular projection
code/modified_TracKit/siamdw_360_border.py
run_siamdw_border
VitaAmbroz/360Tracking
2
python
def run_siamdw_border(self): info = edict() info.arch = self.arch info.dataset = self.video info.epoch_test = True info.cls_type = 'thinner' net = models.__dict__[self.arch]() tracker = SiamFC(info) print('[*] ======= Track video with {} ======='.format(self.arch)) print(self.resume) net = load_pretrain(net, self.resume) net.eval() net = net.cuda() self._track_video(tracker, net)
def run_siamdw_border(self): info = edict() info.arch = self.arch info.dataset = self.video info.epoch_test = True info.cls_type = 'thinner' net = models.__dict__[self.arch]() tracker = SiamFC(info) print('[*] ======= Track video with {} ======='.format(self.arch)) print(self.resume) net = load_pretrain(net, self.resume) net.eval() net = net.cuda() self._track_video(tracker, net)<|docstring|>Method for start SiamDW tracking with improvement of object crossing left/right border in equirectangular projection<|endoftext|>
9373b1f2a826e676b21f0519cce895079d946f6577ebd72d37ce364aa1ba653d
def get_version(package): '\n Return package version as listed in `__version__` in `init.py`.\n ' init_py = open(os.path.join(package, '__init__.py')).read() return re.search('^__version__ = [\'"]([^\'"]+)[\'"]', init_py, re.MULTILINE).group(1)
Return package version as listed in `__version__` in `init.py`.
setup.py
get_version
sloria/django-rest-marshmallow
132
python
def get_version(package): '\n \n ' init_py = open(os.path.join(package, '__init__.py')).read() return re.search('^__version__ = [\'"]([^\'"]+)[\'"]', init_py, re.MULTILINE).group(1)
def get_version(package): '\n \n ' init_py = open(os.path.join(package, '__init__.py')).read() return re.search('^__version__ = [\'"]([^\'"]+)[\'"]', init_py, re.MULTILINE).group(1)<|docstring|>Return package version as listed in `__version__` in `init.py`.<|endoftext|>
ebb819796bea2d16c184e5a6fa1d659868a003d8a01c0818f11229b801a87c9c
def get_packages(package): '\n Return root package and all sub-packages.\n ' return [dirpath for (dirpath, dirnames, filenames) in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))]
Return root package and all sub-packages.
setup.py
get_packages
sloria/django-rest-marshmallow
132
python
def get_packages(package): '\n \n ' return [dirpath for (dirpath, dirnames, filenames) in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_packages(package): '\n \n ' return [dirpath for (dirpath, dirnames, filenames) in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))]<|docstring|>Return root package and all sub-packages.<|endoftext|>
ec66b1c518a1ee65819991b60fd870a7c1c84e332a8aebcdf48bf57b05d0b324
def get_package_data(package): '\n Return all files under the root package, that are not in a\n package themselves.\n ' walk = [(dirpath.replace((package + os.sep), '', 1), filenames) for (dirpath, dirnames, filenames) in os.walk(package) if (not os.path.exists(os.path.join(dirpath, '__init__.py')))] filepaths = [] for (base, filenames) in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths}
Return all files under the root package, that are not in a package themselves.
setup.py
get_package_data
sloria/django-rest-marshmallow
132
python
def get_package_data(package): '\n Return all files under the root package, that are not in a\n package themselves.\n ' walk = [(dirpath.replace((package + os.sep), , 1), filenames) for (dirpath, dirnames, filenames) in os.walk(package) if (not os.path.exists(os.path.join(dirpath, '__init__.py')))] filepaths = [] for (base, filenames) in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths}
def get_package_data(package): '\n Return all files under the root package, that are not in a\n package themselves.\n ' walk = [(dirpath.replace((package + os.sep), , 1), filenames) for (dirpath, dirnames, filenames) in os.walk(package) if (not os.path.exists(os.path.join(dirpath, '__init__.py')))] filepaths = [] for (base, filenames) in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths}<|docstring|>Return all files under the root package, that are not in a package themselves.<|endoftext|>