repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
wrap_exception
def wrap_exception(func: Callable) -> Callable: """Decorator to wrap BTLEExceptions into BluetoothBackendException.""" try: # only do the wrapping if bluepy is installed. # otherwise it's pointless anyway from bluepy.btle import BTLEException except ImportError: return func def _func_wrapper(*args, **kwargs): error_count = 0 last_error = None while error_count < RETRY_LIMIT: try: return func(*args, **kwargs) except BTLEException as exception: error_count += 1 last_error = exception time.sleep(RETRY_DELAY) _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT) raise BluetoothBackendException() from last_error return _func_wrapper
python
def wrap_exception(func: Callable) -> Callable: """Decorator to wrap BTLEExceptions into BluetoothBackendException.""" try: # only do the wrapping if bluepy is installed. # otherwise it's pointless anyway from bluepy.btle import BTLEException except ImportError: return func def _func_wrapper(*args, **kwargs): error_count = 0 last_error = None while error_count < RETRY_LIMIT: try: return func(*args, **kwargs) except BTLEException as exception: error_count += 1 last_error = exception time.sleep(RETRY_DELAY) _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT) raise BluetoothBackendException() from last_error return _func_wrapper
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "try", ":", "# only do the wrapping if bluepy is installed.", "# otherwise it's pointless anyway", "from", "bluepy", ".", "btle", "import", "BTLEException", "except", "ImportError", ":", ...
Decorator to wrap BTLEExceptions into BluetoothBackendException.
[ "Decorator", "to", "wrap", "BTLEExceptions", "into", "BluetoothBackendException", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L13-L35
train
25,500
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.write_handle
def write_handle(self, handle: int, value: bytes): """Write a handle from the device. You must be connected to do this. """ if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.writeCharacteristic(handle, value, True)
python
def write_handle(self, handle: int, value: bytes): """Write a handle from the device. You must be connected to do this. """ if self._peripheral is None: raise BluetoothBackendException('not connected to backend') return self._peripheral.writeCharacteristic(handle, value, True)
[ "def", "write_handle", "(", "self", ",", "handle", ":", "int", ",", "value", ":", "bytes", ")", ":", "if", "self", ".", "_peripheral", "is", "None", ":", "raise", "BluetoothBackendException", "(", "'not connected to backend'", ")", "return", "self", ".", "_p...
Write a handle from the device. You must be connected to do this.
[ "Write", "a", "handle", "from", "the", "device", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L79-L86
train
25,501
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.check_backend
def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
python
def check_backend() -> bool: """Check if the backend is available.""" try: import bluepy.btle # noqa: F401 #pylint: disable=unused-import return True except ImportError as importerror: _LOGGER.error('bluepy not found: %s', str(importerror)) return False
[ "def", "check_backend", "(", ")", "->", "bool", ":", "try", ":", "import", "bluepy", ".", "btle", "# noqa: F401 #pylint: disable=unused-import", "return", "True", "except", "ImportError", "as", "importerror", ":", "_LOGGER", ".", "error", "(", "'bluepy not found: %s...
Check if the backend is available.
[ "Check", "if", "the", "backend", "is", "available", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L97-L104
train
25,502
ChristianKuehnel/btlewrap
btlewrap/bluepy.py
BluepyBackend.scan_for_devices
def scan_for_devices(timeout: float) -> List[Tuple[str, str]]: """Scan for bluetooth low energy devices. Note this must be run as root!""" from bluepy.btle import Scanner scanner = Scanner() result = [] for device in scanner.scan(timeout): result.append((device.addr, device.getValueText(9))) return result
python
def scan_for_devices(timeout: float) -> List[Tuple[str, str]]: """Scan for bluetooth low energy devices. Note this must be run as root!""" from bluepy.btle import Scanner scanner = Scanner() result = [] for device in scanner.scan(timeout): result.append((device.addr, device.getValueText(9))) return result
[ "def", "scan_for_devices", "(", "timeout", ":", "float", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "from", "bluepy", ".", "btle", "import", "Scanner", "scanner", "=", "Scanner", "(", ")", "result", "=", "[", "]", "for", ...
Scan for bluetooth low energy devices. Note this must be run as root!
[ "Scan", "for", "bluetooth", "low", "energy", "devices", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L108-L118
train
25,503
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
wrap_exception
def wrap_exception(func: Callable) -> Callable: """Wrap all IOErrors to BluetoothBackendException""" def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapper
python
def wrap_exception(func: Callable) -> Callable: """Wrap all IOErrors to BluetoothBackendException""" def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapper
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "def", "_func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ...
Wrap all IOErrors to BluetoothBackendException
[ "Wrap", "all", "IOErrors", "to", "BluetoothBackendException" ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L19-L27
train
25,504
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.write_handle
def write_handle(self, handle: int, value: bytes): # noqa: C901 # pylint: disable=arguments-differ """Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={}".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(value), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", self.timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=self.timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Killed hanging gatttool") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output if "successfully" in result: _LOGGER.debug( "Exit write_ble with result (%s)", current_thread()) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
python
def write_handle(self, handle: int, value: bytes): # noqa: C901 # pylint: disable=arguments-differ """Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={}".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(value), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", self.timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=self.timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Killed hanging gatttool") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output if "successfully" in result: _LOGGER.debug( "Exit write_ble with result (%s)", current_thread()) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
[ "def", "write_handle", "(", "self", ",", "handle", ":", "int", ",", "value", ":", "bytes", ")", ":", "# noqa: C901", "# pylint: disable=arguments-differ", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not c...
Read from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX @param: value - value to write to the given handle
[ "Read", "from", "a", "BLE", "address", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L62-L116
train
25,505
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.wait_for_notification
def wait_for_notification(self, handle: int, delegate, notification_timeout: float): """Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the --listen argument and the delegate object's handleNotification is called for every returned row @param: notification_timeout """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={} --listen".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(self._DATA_MODE_LISTEN), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", notification_timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=notification_timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group, because listening always hangs os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Listening stopped forcefully after timeout.") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output to determine success if "successfully" in result: _LOGGER.debug("Exit write_ble with result (%s)", current_thread()) # extract useful data. for element in self.extract_notification_payload(result): delegate.handleNotification(handle, bytes([int(x, 16) for x in element.split()])) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
python
def wait_for_notification(self, handle: int, delegate, notification_timeout: float): """Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the --listen argument and the delegate object's handleNotification is called for every returned row @param: notification_timeout """ if not self.is_connected(): raise BluetoothBackendException('Not connected to any device.') attempt = 0 delay = 10 _LOGGER.debug("Enter write_ble (%s)", current_thread()) while attempt <= self.retries: cmd = "gatttool --device={} --addr-type={} --char-write-req -a {} -n {} --adapter={} --listen".format( self._mac, self.address_type, self.byte_to_handle(handle), self.bytes_to_string(self._DATA_MODE_LISTEN), self.adapter) _LOGGER.debug("Running gatttool with a timeout of %d: %s", notification_timeout, cmd) with Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) as process: try: result = process.communicate(timeout=notification_timeout)[0] _LOGGER.debug("Finished gatttool") except TimeoutExpired: # send signal to the process group, because listening always hangs os.killpg(process.pid, signal.SIGINT) result = process.communicate()[0] _LOGGER.debug("Listening stopped forcefully after timeout.") result = result.decode("utf-8").strip(' \n\t') if "Write Request failed" in result: raise BluetoothBackendException('Error writing handle to sensor: {}'.format(result)) _LOGGER.debug("Got %s from gatttool", result) # Parse the output to determine success if "successfully" in result: _LOGGER.debug("Exit write_ble with result (%s)", current_thread()) # extract useful data. for element in self.extract_notification_payload(result): delegate.handleNotification(handle, bytes([int(x, 16) for x in element.split()])) return True attempt += 1 _LOGGER.debug("Waiting for %s seconds before retrying", delay) if attempt < self.retries: time.sleep(delay) delay *= 2 raise BluetoothBackendException("Exit write_ble, no data ({})".format(current_thread()))
[ "def", "wait_for_notification", "(", "self", ",", "handle", ":", "int", ",", "delegate", ",", "notification_timeout", ":", "float", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not connected to a...
Listen for characteristics changes from a BLE address. @param: mac - MAC address in format XX:XX:XX:XX:XX:XX @param: handle - BLE characteristics handle in format 0xXX a value of 0x0100 is written to register for listening @param: delegate - gatttool receives the --listen argument and the delegate object's handleNotification is called for every returned row @param: notification_timeout
[ "Listen", "for", "characteristics", "changes", "from", "a", "BLE", "address", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L119-L176
train
25,506
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.check_backend
def check_backend() -> bool: """Check if gatttool is available on the system.""" try: call('gatttool', stdout=PIPE, stderr=PIPE) return True except OSError as os_err: msg = 'gatttool not found: {}'.format(str(os_err)) _LOGGER.error(msg) return False
python
def check_backend() -> bool: """Check if gatttool is available on the system.""" try: call('gatttool', stdout=PIPE, stderr=PIPE) return True except OSError as os_err: msg = 'gatttool not found: {}'.format(str(os_err)) _LOGGER.error(msg) return False
[ "def", "check_backend", "(", ")", "->", "bool", ":", "try", ":", "call", "(", "'gatttool'", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "return", "True", "except", "OSError", "as", "os_err", ":", "msg", "=", "'gatttool not found: {}'", "...
Check if gatttool is available on the system.
[ "Check", "if", "gatttool", "is", "available", "on", "the", "system", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L260-L268
train
25,507
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
GatttoolBackend.bytes_to_string
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str: """Convert a byte array to a hex string.""" prefix_string = '' if prefix: prefix_string = '0x' suffix = ''.join([format(c, "02x") for c in raw_data]) return prefix_string + suffix.upper()
python
def bytes_to_string(raw_data: bytes, prefix: bool = False) -> str: """Convert a byte array to a hex string.""" prefix_string = '' if prefix: prefix_string = '0x' suffix = ''.join([format(c, "02x") for c in raw_data]) return prefix_string + suffix.upper()
[ "def", "bytes_to_string", "(", "raw_data", ":", "bytes", ",", "prefix", ":", "bool", "=", "False", ")", "->", "str", ":", "prefix_string", "=", "''", "if", "prefix", ":", "prefix_string", "=", "'0x'", "suffix", "=", "''", ".", "join", "(", "[", "format...
Convert a byte array to a hex string.
[ "Convert", "a", "byte", "array", "to", "a", "hex", "string", "." ]
1b7aec934529dcf03f5ecdccd0b09c25c389974f
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L276-L282
train
25,508
datacamp/antlr-ast
antlr_ast/marshalling.py
decode_ast
def decode_ast(registry, ast_json): """JSON decoder for BaseNodes""" if ast_json.get("@type"): subclass = registry.get_cls(ast_json["@type"], tuple(ast_json["@fields"])) return subclass( ast_json["children"], ast_json["field_references"], ast_json["label_references"], position=ast_json["@position"], ) else: return ast_json
python
def decode_ast(registry, ast_json): """JSON decoder for BaseNodes""" if ast_json.get("@type"): subclass = registry.get_cls(ast_json["@type"], tuple(ast_json["@fields"])) return subclass( ast_json["children"], ast_json["field_references"], ast_json["label_references"], position=ast_json["@position"], ) else: return ast_json
[ "def", "decode_ast", "(", "registry", ",", "ast_json", ")", ":", "if", "ast_json", ".", "get", "(", "\"@type\"", ")", ":", "subclass", "=", "registry", ".", "get_cls", "(", "ast_json", "[", "\"@type\"", "]", ",", "tuple", "(", "ast_json", "[", "\"@fields...
JSON decoder for BaseNodes
[ "JSON", "decoder", "for", "BaseNodes" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/marshalling.py#L27-L38
train
25,509
datacamp/antlr-ast
antlr_ast/ast.py
simplify_tree
def simplify_tree(tree, unpack_lists=True, in_list=False): """Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists """ # TODO: copy (or (de)serialize)? outside this function? if isinstance(tree, BaseNode) and not isinstance(tree, Terminal): used_fields = [field for field in tree._fields if getattr(tree, field, False)] if len(used_fields) == 1: result = getattr(tree, used_fields[0]) else: result = None if ( len(used_fields) != 1 or isinstance(tree, AliasNode) or (in_list and isinstance(result, list)) ): result = tree for field in tree._fields: old_value = getattr(tree, field, None) if old_value: setattr( result, field, simplify_tree(old_value, unpack_lists=unpack_lists), ) return result assert result is not None elif isinstance(tree, list) and len(tree) == 1 and unpack_lists: result = tree[0] else: if isinstance(tree, list): result = [ simplify_tree(el, unpack_lists=unpack_lists, in_list=True) for el in tree ] else: result = tree return result return simplify_tree(result, unpack_lists=unpack_lists)
python
def simplify_tree(tree, unpack_lists=True, in_list=False): """Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists """ # TODO: copy (or (de)serialize)? outside this function? if isinstance(tree, BaseNode) and not isinstance(tree, Terminal): used_fields = [field for field in tree._fields if getattr(tree, field, False)] if len(used_fields) == 1: result = getattr(tree, used_fields[0]) else: result = None if ( len(used_fields) != 1 or isinstance(tree, AliasNode) or (in_list and isinstance(result, list)) ): result = tree for field in tree._fields: old_value = getattr(tree, field, None) if old_value: setattr( result, field, simplify_tree(old_value, unpack_lists=unpack_lists), ) return result assert result is not None elif isinstance(tree, list) and len(tree) == 1 and unpack_lists: result = tree[0] else: if isinstance(tree, list): result = [ simplify_tree(el, unpack_lists=unpack_lists, in_list=True) for el in tree ] else: result = tree return result return simplify_tree(result, unpack_lists=unpack_lists)
[ "def", "simplify_tree", "(", "tree", ",", "unpack_lists", "=", "True", ",", "in_list", "=", "False", ")", ":", "# TODO: copy (or (de)serialize)? outside this function?", "if", "isinstance", "(", "tree", ",", "BaseNode", ")", "and", "not", "isinstance", "(", "tree"...
Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_list: this is used to prevent unpacking a node in a list as AST visit can't handle nested lists
[ "Recursively", "unpack", "single", "-", "item", "lists", "and", "objects", "where", "fields", "and", "labels", "only", "reference", "a", "single", "child" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L521-L563
train
25,510
datacamp/antlr-ast
antlr_ast/ast.py
get_field
def get_field(ctx, field): """Helper to get the value of a field""" # field can be a string or a node attribute if isinstance(field, str): field = getattr(ctx, field, None) # when not alias needs to be called if callable(field): field = field() # when alias set on token, need to go from CommonToken -> Terminal Node elif isinstance(field, CommonToken): # giving a name to lexer rules sets it to a token, # rather than the terminal node corresponding to that token # so we need to find it in children field = next( filter(lambda c: getattr(c, "symbol", None) is field, ctx.children) ) return field
python
def get_field(ctx, field): """Helper to get the value of a field""" # field can be a string or a node attribute if isinstance(field, str): field = getattr(ctx, field, None) # when not alias needs to be called if callable(field): field = field() # when alias set on token, need to go from CommonToken -> Terminal Node elif isinstance(field, CommonToken): # giving a name to lexer rules sets it to a token, # rather than the terminal node corresponding to that token # so we need to find it in children field = next( filter(lambda c: getattr(c, "symbol", None) is field, ctx.children) ) return field
[ "def", "get_field", "(", "ctx", ",", "field", ")", ":", "# field can be a string or a node attribute", "if", "isinstance", "(", "field", ",", "str", ")", ":", "field", "=", "getattr", "(", "ctx", ",", "field", ",", "None", ")", "# when not alias needs to be call...
Helper to get the value of a field
[ "Helper", "to", "get", "the", "value", "of", "a", "field" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L641-L657
train
25,511
datacamp/antlr-ast
antlr_ast/ast.py
get_field_names
def get_field_names(ctx): """Get fields defined in an ANTLR context for a parser rule""" # this does not include labels and literals, only rule names and token names # TODO: check ANTLR parser template for full exclusion list fields = [ field for field in type(ctx).__dict__ if not field.startswith("__") and field not in ["accept", "enterRule", "exitRule", "getRuleIndex", "copyFrom"] ] return fields
python
def get_field_names(ctx): """Get fields defined in an ANTLR context for a parser rule""" # this does not include labels and literals, only rule names and token names # TODO: check ANTLR parser template for full exclusion list fields = [ field for field in type(ctx).__dict__ if not field.startswith("__") and field not in ["accept", "enterRule", "exitRule", "getRuleIndex", "copyFrom"] ] return fields
[ "def", "get_field_names", "(", "ctx", ")", ":", "# this does not include labels and literals, only rule names and token names", "# TODO: check ANTLR parser template for full exclusion list", "fields", "=", "[", "field", "for", "field", "in", "type", "(", "ctx", ")", ".", "__d...
Get fields defined in an ANTLR context for a parser rule
[ "Get", "fields", "defined", "in", "an", "ANTLR", "context", "for", "a", "parser", "rule" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L707-L717
train
25,512
datacamp/antlr-ast
antlr_ast/ast.py
get_label_names
def get_label_names(ctx): """Get labels defined in an ANTLR context for a parser rule""" labels = [ label for label in ctx.__dict__ if not label.startswith("_") and label not in [ "children", "exception", "invokingState", "parentCtx", "parser", "start", "stop", ] ] return labels
python
def get_label_names(ctx): """Get labels defined in an ANTLR context for a parser rule""" labels = [ label for label in ctx.__dict__ if not label.startswith("_") and label not in [ "children", "exception", "invokingState", "parentCtx", "parser", "start", "stop", ] ] return labels
[ "def", "get_label_names", "(", "ctx", ")", ":", "labels", "=", "[", "label", "for", "label", "in", "ctx", ".", "__dict__", "if", "not", "label", ".", "startswith", "(", "\"_\"", ")", "and", "label", "not", "in", "[", "\"children\"", ",", "\"exception\"",...
Get labels defined in an ANTLR context for a parser rule
[ "Get", "labels", "defined", "in", "an", "ANTLR", "context", "for", "a", "parser", "rule" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L720-L737
train
25,513
datacamp/antlr-ast
antlr_ast/ast.py
Speaker.get_info
def get_info(node_cfg): """Return a tuple with the verbal name of a node, and a dict of field names.""" node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg} return node_cfg.get("name"), node_cfg.get("fields", {})
python
def get_info(node_cfg): """Return a tuple with the verbal name of a node, and a dict of field names.""" node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg} return node_cfg.get("name"), node_cfg.get("fields", {})
[ "def", "get_info", "(", "node_cfg", ")", ":", "node_cfg", "=", "node_cfg", "if", "isinstance", "(", "node_cfg", ",", "dict", ")", "else", "{", "\"name\"", ":", "node_cfg", "}", "return", "node_cfg", ".", "get", "(", "\"name\"", ")", ",", "node_cfg", ".",...
Return a tuple with the verbal name of a node, and a dict of field names.
[ "Return", "a", "tuple", "with", "the", "verbal", "name", "of", "a", "node", "and", "a", "dict", "of", "field", "names", "." ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L143-L148
train
25,514
datacamp/antlr-ast
antlr_ast/ast.py
BaseNodeRegistry.isinstance
def isinstance(self, instance, class_name): """Check if a BaseNode is an instance of a registered dynamic class""" if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) # Not an instance of a class in the registry return False else: raise TypeError("This function can only be used for BaseNode objects")
python
def isinstance(self, instance, class_name): """Check if a BaseNode is an instance of a registered dynamic class""" if isinstance(instance, BaseNode): klass = self.dynamic_node_classes.get(class_name, None) if klass: return isinstance(instance, klass) # Not an instance of a class in the registry return False else: raise TypeError("This function can only be used for BaseNode objects")
[ "def", "isinstance", "(", "self", ",", "instance", ",", "class_name", ")", ":", "if", "isinstance", "(", "instance", ",", "BaseNode", ")", ":", "klass", "=", "self", ".", "dynamic_node_classes", ".", "get", "(", "class_name", ",", "None", ")", "if", "kla...
Check if a BaseNode is an instance of a registered dynamic class
[ "Check", "if", "a", "BaseNode", "is", "an", "instance", "of", "a", "registered", "dynamic", "class" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L207-L216
train
25,515
datacamp/antlr-ast
antlr_ast/ast.py
AliasNode.get_transformer
def get_transformer(cls, method_name): """Get method to bind to visitor""" transform_function = getattr(cls, method_name) assert callable(transform_function) def transformer_method(self, node): kwargs = {} if inspect.signature(transform_function).parameters.get("helper"): kwargs["helper"] = self.helper return transform_function(node, **kwargs) return transformer_method
python
def get_transformer(cls, method_name): """Get method to bind to visitor""" transform_function = getattr(cls, method_name) assert callable(transform_function) def transformer_method(self, node): kwargs = {} if inspect.signature(transform_function).parameters.get("helper"): kwargs["helper"] = self.helper return transform_function(node, **kwargs) return transformer_method
[ "def", "get_transformer", "(", "cls", ",", "method_name", ")", ":", "transform_function", "=", "getattr", "(", "cls", ",", "method_name", ")", "assert", "callable", "(", "transform_function", ")", "def", "transformer_method", "(", "self", ",", "node", ")", ":"...
Get method to bind to visitor
[ "Get", "method", "to", "bind", "to", "visitor" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L445-L456
train
25,516
datacamp/antlr-ast
antlr_ast/ast.py
BaseAstVisitor.visitTerminal
def visitTerminal(self, ctx): """Converts case insensitive keywords and identifiers to lowercase""" text = ctx.getText() return Terminal.from_text(text, ctx)
python
def visitTerminal(self, ctx): """Converts case insensitive keywords and identifiers to lowercase""" text = ctx.getText() return Terminal.from_text(text, ctx)
[ "def", "visitTerminal", "(", "self", ",", "ctx", ")", ":", "text", "=", "ctx", ".", "getText", "(", ")", "return", "Terminal", ".", "from_text", "(", "text", ",", "ctx", ")" ]
Converts case insensitive keywords and identifiers to lowercase
[ "Converts", "case", "insensitive", "keywords", "and", "identifiers", "to", "lowercase" ]
d08d5eb2e663bd40501d0eeddc8a731ac7e96b11
https://github.com/datacamp/antlr-ast/blob/d08d5eb2e663bd40501d0eeddc8a731ac7e96b11/antlr_ast/ast.py#L629-L632
train
25,517
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.run
def run(self, *args): """List, add or delete entries from the blacklist. By default, it prints the list of entries available on the blacklist. """ params = self.parser.parse_args(args) entry = params.entry if params.add: code = self.add(entry) elif params.delete: code = self.delete(entry) else: term = entry code = self.blacklist(term) return code
python
def run(self, *args): """List, add or delete entries from the blacklist. By default, it prints the list of entries available on the blacklist. """ params = self.parser.parse_args(args) entry = params.entry if params.add: code = self.add(entry) elif params.delete: code = self.delete(entry) else: term = entry code = self.blacklist(term) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "entry", "=", "params", ".", "entry", "if", "params", ".", "add", ":", "code", "=", "self", ".", "add", "(", "entry"...
List, add or delete entries from the blacklist. By default, it prints the list of entries available on the blacklist.
[ "List", "add", "or", "delete", "entries", "from", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L80-L98
train
25,518
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.add
def add(self, entry): """Add entries to the blacklist. This method adds the given 'entry' to the blacklist. :param entry: entry to add to the blacklist """ # Empty or None values for organizations are not allowed if not entry: return CMD_SUCCESS try: api.add_to_matching_blacklist(self.db, entry) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because entry cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "%s already exists in the registry" % entry self.error(msg) return e.code return CMD_SUCCESS
python
def add(self, entry): """Add entries to the blacklist. This method adds the given 'entry' to the blacklist. :param entry: entry to add to the blacklist """ # Empty or None values for organizations are not allowed if not entry: return CMD_SUCCESS try: api.add_to_matching_blacklist(self.db, entry) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because entry cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "%s already exists in the registry" % entry self.error(msg) return e.code return CMD_SUCCESS
[ "def", "add", "(", "self", ",", "entry", ")", ":", "# Empty or None values for organizations are not allowed", "if", "not", "entry", ":", "return", "CMD_SUCCESS", "try", ":", "api", ".", "add_to_matching_blacklist", "(", "self", ".", "db", ",", "entry", ")", "ex...
Add entries to the blacklist. This method adds the given 'entry' to the blacklist. :param entry: entry to add to the blacklist
[ "Add", "entries", "to", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L100-L122
train
25,519
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.delete
def delete(self, entry): """Remove entries from the blacklist. The method removes the given 'entry' from the blacklist. :param entry: entry to remove from the blacklist """ if not entry: return CMD_SUCCESS try: api.delete_from_matching_blacklist(self.db, entry) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def delete(self, entry): """Remove entries from the blacklist. The method removes the given 'entry' from the blacklist. :param entry: entry to remove from the blacklist """ if not entry: return CMD_SUCCESS try: api.delete_from_matching_blacklist(self.db, entry) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "delete", "(", "self", ",", "entry", ")", ":", "if", "not", "entry", ":", "return", "CMD_SUCCESS", "try", ":", "api", ".", "delete_from_matching_blacklist", "(", "self", ".", "db", ",", "entry", ")", "except", "NotFoundError", "as", "e", ":", "sel...
Remove entries from the blacklist. The method removes the given 'entry' from the blacklist. :param entry: entry to remove from the blacklist
[ "Remove", "entries", "from", "the", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L124-L140
train
25,520
chaoss/grimoirelab-sortinghat
sortinghat/cmd/blacklist.py
Blacklist.blacklist
def blacklist(self, term=None): """List blacklisted entries. When no term is given, the method will list the entries that exist in the blacklist. If 'term' is set, the method will list only those entries that match with that term. :param term: term to match """ try: bl = api.blacklist(self.db, term) self.display('blacklist.tmpl', blacklist=bl) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def blacklist(self, term=None): """List blacklisted entries. When no term is given, the method will list the entries that exist in the blacklist. If 'term' is set, the method will list only those entries that match with that term. :param term: term to match """ try: bl = api.blacklist(self.db, term) self.display('blacklist.tmpl', blacklist=bl) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "blacklist", "(", "self", ",", "term", "=", "None", ")", ":", "try", ":", "bl", "=", "api", ".", "blacklist", "(", "self", ".", "db", ",", "term", ")", "self", ".", "display", "(", "'blacklist.tmpl'", ",", "blacklist", "=", "bl", ")", "excep...
List blacklisted entries. When no term is given, the method will list the entries that exist in the blacklist. If 'term' is set, the method will list only those entries that match with that term. :param term: term to match
[ "List", "blacklisted", "entries", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/blacklist.py#L142-L158
train
25,521
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.run
def run(self, *args): """Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'. """ params = self.parser.parse_args(args) config_file = os.path.expanduser('~/.sortinghat') if params.action == 'get': code = self.get(params.parameter, config_file) elif params.action == 'set': code = self.set(params.parameter, params.value, config_file) else: raise RuntimeError("Not get or set action given") return code
python
def run(self, *args): """Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'. """ params = self.parser.parse_args(args) config_file = os.path.expanduser('~/.sortinghat') if params.action == 'get': code = self.get(params.parameter, config_file) elif params.action == 'set': code = self.set(params.parameter, params.value, config_file) else: raise RuntimeError("Not get or set action given") return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "config_file", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.sortinghat'", ")", "if", "params", ".", "action", "=...
Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'.
[ "Get", "and", "set", "configuration", "parameters", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L80-L98
train
25,522
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.get
def get(self, key, filepath): """Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists" % key) if not os.path.isfile(filepath): raise RuntimeError("%s config file does not exist" % filepath) section, option = key.split('.') config = configparser.SafeConfigParser() config.read(filepath) try: option = config.get(section, option) self.display('config.tmpl', key=key, option=option) except (configparser.NoSectionError, configparser.NoOptionError): pass return CMD_SUCCESS
python
def get(self, key, filepath): """Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists" % key) if not os.path.isfile(filepath): raise RuntimeError("%s config file does not exist" % filepath) section, option = key.split('.') config = configparser.SafeConfigParser() config.read(filepath) try: option = config.get(section, option) self.display('config.tmpl', key=key, option=option) except (configparser.NoSectionError, configparser.NoOptionError): pass return CMD_SUCCESS
[ "def", "get", "(", "self", ",", "key", ",", "filepath", ")", ":", "if", "not", "filepath", ":", "raise", "RuntimeError", "(", "\"Configuration file not given\"", ")", "if", "not", "self", ".", "__check_config_key", "(", "key", ")", ":", "raise", "RuntimeErro...
Get configuration parameter. Reads 'key' configuration parameter from the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to get :param filepath: configuration file
[ "Get", "configuration", "parameter", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L100-L130
train
25,523
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.set
def set(self, key, value, filepath): """Set configuration parameter. Writes 'value' on 'key' to the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to set :param value: value to set :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists or cannot be set" % key) config = configparser.SafeConfigParser() if os.path.isfile(filepath): config.read(filepath) section, option = key.split('.') if section not in config.sections(): config.add_section(section) try: config.set(section, option, value) except TypeError as e: raise RuntimeError(str(e)) try: with open(filepath, 'w') as f: config.write(f) except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def set(self, key, value, filepath): """Set configuration parameter. Writes 'value' on 'key' to the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to set :param value: value to set :param filepath: configuration file """ if not filepath: raise RuntimeError("Configuration file not given") if not self.__check_config_key(key): raise RuntimeError("%s parameter does not exists or cannot be set" % key) config = configparser.SafeConfigParser() if os.path.isfile(filepath): config.read(filepath) section, option = key.split('.') if section not in config.sections(): config.add_section(section) try: config.set(section, option, value) except TypeError as e: raise RuntimeError(str(e)) try: with open(filepath, 'w') as f: config.write(f) except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "filepath", ")", ":", "if", "not", "filepath", ":", "raise", "RuntimeError", "(", "\"Configuration file not given\"", ")", "if", "not", "self", ".", "__check_config_key", "(", "key", ")", ":", "rais...
Set configuration parameter. Writes 'value' on 'key' to the configuration file given in 'filepath'. Configuration parameter in 'key' must follow the schema <section>.<option> . :param key: key to set :param value: value to set :param filepath: configuration file
[ "Set", "configuration", "parameter", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L132-L170
train
25,524
chaoss/grimoirelab-sortinghat
sortinghat/cmd/config.py
Config.__check_config_key
def __check_config_key(self, key): """Check whether the key is valid. A valid key has the schema <section>.<option>. Keys supported are listed in CONFIG_OPTIONS dict. :param key: <section>.<option> key """ try: section, option = key.split('.') except (AttributeError, ValueError): return False if not section or not option: return False return section in Config.CONFIG_OPTIONS and\ option in Config.CONFIG_OPTIONS[section]
python
def __check_config_key(self, key): """Check whether the key is valid. A valid key has the schema <section>.<option>. Keys supported are listed in CONFIG_OPTIONS dict. :param key: <section>.<option> key """ try: section, option = key.split('.') except (AttributeError, ValueError): return False if not section or not option: return False return section in Config.CONFIG_OPTIONS and\ option in Config.CONFIG_OPTIONS[section]
[ "def", "__check_config_key", "(", "self", ",", "key", ")", ":", "try", ":", "section", ",", "option", "=", "key", ".", "split", "(", "'.'", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "return", "False", "if", "not", "section", "o...
Check whether the key is valid. A valid key has the schema <section>.<option>. Keys supported are listed in CONFIG_OPTIONS dict. :param key: <section>.<option> key
[ "Check", "whether", "the", "key", "is", "valid", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/config.py#L172-L189
train
25,525
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.run
def run(self, *args): """Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file. """ params = self.parser.parse_args(args) with params.outfile as outfile: if params.identities: code = self.export_identities(outfile, params.source) elif params.orgs: code = self.export_organizations(outfile) else: # The running proccess never should reach this section raise RuntimeError("Unexpected export option") return code
python
def run(self, *args): """Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file. """ params = self.parser.parse_args(args) with params.outfile as outfile: if params.identities: code = self.export_identities(outfile, params.source) elif params.orgs: code = self.export_organizations(outfile) else: # The running proccess never should reach this section raise RuntimeError("Unexpected export option") return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "with", "params", ".", "outfile", "as", "outfile", ":", "if", "params", ".", "identities", ":", "code", "=", "self", "...
Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file.
[ "Export", "data", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L82-L100
train
25,526
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.export_identities
def export_identities(self, outfile, source=None): """Export identities information to a file. The method exports information related to unique identities, to the given 'outfile' output file. When 'source' parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param outfile: destination file object :param source: source of the identities to export """ exporter = SortingHatIdentitiesExporter(self.db) dump = exporter.export(source) try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def export_identities(self, outfile, source=None): """Export identities information to a file. The method exports information related to unique identities, to the given 'outfile' output file. When 'source' parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param outfile: destination file object :param source: source of the identities to export """ exporter = SortingHatIdentitiesExporter(self.db) dump = exporter.export(source) try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "export_identities", "(", "self", ",", "outfile", ",", "source", "=", "None", ")", ":", "exporter", "=", "SortingHatIdentitiesExporter", "(", "self", ".", "db", ")", "dump", "=", "exporter", ".", "export", "(", "source", ")", "try", ":", "outfile", ...
Export identities information to a file. The method exports information related to unique identities, to the given 'outfile' output file. When 'source' parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param outfile: destination file object :param source: source of the identities to export
[ "Export", "identities", "information", "to", "a", "file", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L102-L124
train
25,527
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
Export.export_organizations
def export_organizations(self, outfile): """Export organizations information to a file. The method exports information related to organizations, to the given 'outfile' output file. :param outfile: destination file object """ exporter = SortingHatOrganizationsExporter(self.db) dump = exporter.export() try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
python
def export_organizations(self, outfile): """Export organizations information to a file. The method exports information related to organizations, to the given 'outfile' output file. :param outfile: destination file object """ exporter = SortingHatOrganizationsExporter(self.db) dump = exporter.export() try: outfile.write(dump) outfile.write('\n') except IOError as e: raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "export_organizations", "(", "self", ",", "outfile", ")", ":", "exporter", "=", "SortingHatOrganizationsExporter", "(", "self", ".", "db", ")", "dump", "=", "exporter", ".", "export", "(", ")", "try", ":", "outfile", ".", "write", "(", "dump", ")", ...
Export organizations information to a file. The method exports information related to organizations, to the given 'outfile' output file. :param outfile: destination file object
[ "Export", "organizations", "information", "to", "a", "file", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L126-L144
train
25,528
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
SortingHatIdentitiesExporter.export
def export(self, source=None): """Export a set of unique identities. Method to export unique identities from the registry. Identities schema will follow Sorting Hat JSON format. When source parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param source: source of the identities to export :returns: a JSON formatted str """ uidentities = {} uids = api.unique_identities(self.db, source=source) for uid in uids: enrollments = [rol.to_dict() for rol in api.enrollments(self.db, uuid=uid.uuid)] u = uid.to_dict() u['identities'].sort(key=lambda x: x['id']) uidentities[uid.uuid] = u uidentities[uid.uuid]['enrollments'] = enrollments blacklist = [mb.excluded for mb in api.blacklist(self.db)] obj = {'time': str(datetime.datetime.now()), 'source': source, 'blacklist': blacklist, 'organizations': {}, 'uidentities': uidentities} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
python
def export(self, source=None): """Export a set of unique identities. Method to export unique identities from the registry. Identities schema will follow Sorting Hat JSON format. When source parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param source: source of the identities to export :returns: a JSON formatted str """ uidentities = {} uids = api.unique_identities(self.db, source=source) for uid in uids: enrollments = [rol.to_dict() for rol in api.enrollments(self.db, uuid=uid.uuid)] u = uid.to_dict() u['identities'].sort(key=lambda x: x['id']) uidentities[uid.uuid] = u uidentities[uid.uuid]['enrollments'] = enrollments blacklist = [mb.excluded for mb in api.blacklist(self.db)] obj = {'time': str(datetime.datetime.now()), 'source': source, 'blacklist': blacklist, 'organizations': {}, 'uidentities': uidentities} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
[ "def", "export", "(", "self", ",", "source", "=", "None", ")", ":", "uidentities", "=", "{", "}", "uids", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "source", "=", "source", ")", "for", "uid", "in", "uids", ":", "enrollments",...
Export a set of unique identities. Method to export unique identities from the registry. Identities schema will follow Sorting Hat JSON format. When source parameter is given, only those unique identities which have one or more identities from the given source will be exported. :param source: source of the identities to export :returns: a JSON formatted str
[ "Export", "a", "set", "of", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L168-L205
train
25,529
chaoss/grimoirelab-sortinghat
sortinghat/cmd/export.py
SortingHatOrganizationsExporter.export
def export(self): """Export a set of organizations. Method to export organizations from the registry. Organizations schema will follow Sorting Hat JSON format. :returns: a JSON formatted str """ organizations = {} orgs = api.registry(self.db) for org in orgs: domains = [{'domain': dom.domain, 'is_top': dom.is_top_domain} for dom in org.domains] domains.sort(key=lambda x: x['domain']) organizations[org.name] = domains obj = {'time': str(datetime.datetime.now()), 'blacklist': [], 'organizations': organizations, 'uidentities': {}} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
python
def export(self): """Export a set of organizations. Method to export organizations from the registry. Organizations schema will follow Sorting Hat JSON format. :returns: a JSON formatted str """ organizations = {} orgs = api.registry(self.db) for org in orgs: domains = [{'domain': dom.domain, 'is_top': dom.is_top_domain} for dom in org.domains] domains.sort(key=lambda x: x['domain']) organizations[org.name] = domains obj = {'time': str(datetime.datetime.now()), 'blacklist': [], 'organizations': organizations, 'uidentities': {}} return json.dumps(obj, default=self._json_encoder, indent=4, separators=(',', ': '), sort_keys=True)
[ "def", "export", "(", "self", ")", ":", "organizations", "=", "{", "}", "orgs", "=", "api", ".", "registry", "(", "self", ".", "db", ")", "for", "org", "in", "orgs", ":", "domains", "=", "[", "{", "'domain'", ":", "dom", ".", "domain", ",", "'is_...
Export a set of organizations. Method to export organizations from the registry. Organizations schema will follow Sorting Hat JSON format. :returns: a JSON formatted str
[ "Export", "a", "set", "of", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/export.py#L237-L264
train
25,530
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.run
def run(self, *args): """Autocomplete profile information.""" params = self.parser.parse_args(args) sources = params.source code = self.autocomplete(sources) return code
python
def run(self, *args): """Autocomplete profile information.""" params = self.parser.parse_args(args) sources = params.source code = self.autocomplete(sources) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "sources", "=", "params", ".", "source", "code", "=", "self", ".", "autocomplete", "(", "sources", ")", "return", "code"...
Autocomplete profile information.
[ "Autocomplete", "profile", "information", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L71-L78
train
25,531
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.autocomplete
def autocomplete(self, sources): """Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources. """ email_pattern = re.compile(EMAIL_ADDRESS_REGEX) identities = self.__select_autocomplete_identities(sources) for uuid, ids in identities.items(): # Among the identities (with the same priority) selected # to complete the profile, it will choose the longest 'name'. # If no name is available, it will use the field 'username'. name = None email = None for identity in ids: oldname = name if not name: name = identity.name or identity.username elif identity.name and len(identity.name) > len(name): name = identity.name # Do not set email addresses on the name field if name and email_pattern.match(name): name = oldname if not email and identity.email: email = identity.email kw = { 'name': name, 'email': email } try: api.edit_profile(self.db, uuid, **kw) self.display('autoprofile.tmpl', identity=identity) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def autocomplete(self, sources): """Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources. """ email_pattern = re.compile(EMAIL_ADDRESS_REGEX) identities = self.__select_autocomplete_identities(sources) for uuid, ids in identities.items(): # Among the identities (with the same priority) selected # to complete the profile, it will choose the longest 'name'. # If no name is available, it will use the field 'username'. name = None email = None for identity in ids: oldname = name if not name: name = identity.name or identity.username elif identity.name and len(identity.name) > len(name): name = identity.name # Do not set email addresses on the name field if name and email_pattern.match(name): name = oldname if not email and identity.email: email = identity.email kw = { 'name': name, 'email': email } try: api.edit_profile(self.db, uuid, **kw) self.display('autoprofile.tmpl', identity=identity) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "autocomplete", "(", "self", ",", "sources", ")", ":", "email_pattern", "=", "re", ".", "compile", "(", "EMAIL_ADDRESS_REGEX", ")", "identities", "=", "self", ".", "__select_autocomplete_identities", "(", "sources", ")", "for", "uuid", ",", "ids", "in",...
Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources.
[ "Autocomplete", "unique", "identities", "profiles", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L80-L125
train
25,532
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autoprofile.py
AutoProfile.__select_autocomplete_identities
def __select_autocomplete_identities(self, sources): """Select the identities used for autocompleting""" MIN_PRIORITY = 99999999 checked = {} for source in sources: uids = api.unique_identities(self.db, source=source) for uid in uids: if uid.uuid in checked: continue max_priority = MIN_PRIORITY selected = [] for identity in sorted(uid.identities, key=lambda x: x.id): try: priority = sources.index(identity.source) if priority < max_priority: selected = [identity] max_priority = priority elif priority == max_priority: selected.append(identity) except ValueError: continue checked[uid.uuid] = selected identities = collections.OrderedDict(sorted(checked.items(), key=lambda t: t[0])) return identities
python
def __select_autocomplete_identities(self, sources): """Select the identities used for autocompleting""" MIN_PRIORITY = 99999999 checked = {} for source in sources: uids = api.unique_identities(self.db, source=source) for uid in uids: if uid.uuid in checked: continue max_priority = MIN_PRIORITY selected = [] for identity in sorted(uid.identities, key=lambda x: x.id): try: priority = sources.index(identity.source) if priority < max_priority: selected = [identity] max_priority = priority elif priority == max_priority: selected.append(identity) except ValueError: continue checked[uid.uuid] = selected identities = collections.OrderedDict(sorted(checked.items(), key=lambda t: t[0])) return identities
[ "def", "__select_autocomplete_identities", "(", "self", ",", "sources", ")", ":", "MIN_PRIORITY", "=", "99999999", "checked", "=", "{", "}", "for", "source", "in", "sources", ":", "uids", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "...
Select the identities used for autocompleting
[ "Select", "the", "identities", "used", "for", "autocompleting" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autoprofile.py#L127-L161
train
25,533
chaoss/grimoirelab-sortinghat
sortinghat/cmd/show.py
Show.run
def run(self, *args): """Show information about unique identities.""" params = self.parser.parse_args(args) code = self.show(params.uuid, params.term) return code
python
def run(self, *args): """Show information about unique identities.""" params = self.parser.parse_args(args) code = self.show(params.uuid, params.term) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "code", "=", "self", ".", "show", "(", "params", ".", "uuid", ",", "params", ".", "term", ")", "return", "code" ]
Show information about unique identities.
[ "Show", "information", "about", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/show.py#L74-L81
train
25,534
chaoss/grimoirelab-sortinghat
sortinghat/cmd/show.py
Show.show
def show(self, uuid=None, term=None): """Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only show information about those unique identities that have any attribute (name, email, username, source) which match with the given term. This parameter does not have any effect when <uuid> is set. :param uuid: unique identifier :param term: term to match with unique identities data """ try: if uuid: uidentities = api.unique_identities(self.db, uuid) elif term: uidentities = api.search_unique_identities(self.db, term) else: uidentities = api.unique_identities(self.db) for uid in uidentities: # Add enrollments to a new property 'roles' enrollments = api.enrollments(self.db, uid.uuid) uid.roles = enrollments self.display('show.tmpl', uidentities=uidentities) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def show(self, uuid=None, term=None): """Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only show information about those unique identities that have any attribute (name, email, username, source) which match with the given term. This parameter does not have any effect when <uuid> is set. :param uuid: unique identifier :param term: term to match with unique identities data """ try: if uuid: uidentities = api.unique_identities(self.db, uuid) elif term: uidentities = api.search_unique_identities(self.db, term) else: uidentities = api.unique_identities(self.db) for uid in uidentities: # Add enrollments to a new property 'roles' enrollments = api.enrollments(self.db, uid.uuid) uid.roles = enrollments self.display('show.tmpl', uidentities=uidentities) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "show", "(", "self", ",", "uuid", "=", "None", ",", "term", "=", "None", ")", ":", "try", ":", "if", "uuid", ":", "uidentities", "=", "api", ".", "unique_identities", "(", "self", ".", "db", ",", "uuid", ")", "elif", "term", ":", "uidentitie...
Show the information related to unique identities. This method prints information related to unique identities such as identities or enrollments. When <uuid> is given, it will only show information about the unique identity related to <uuid>. When <term> is set, it will only show information about those unique identities that have any attribute (name, email, username, source) which match with the given term. This parameter does not have any effect when <uuid> is set. :param uuid: unique identifier :param term: term to match with unique identities data
[ "Show", "the", "information", "related", "to", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/show.py#L83-L118
train
25,535
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_organizations
def __parse_organizations(self, json): """Parse Stackalytics organizations. The Stackalytics organizations format is a JSON document stored under the "companies" key. The next JSON shows the structure of the document: { "companies" : [ { "domains": ["alcatel-lucent.com"], "company_name": "Alcatel-Lucent", "aliases": ["Alcatel Lucent", "Alcatel-Lcuent"] }, { "domains": ["allegrogroup.com", "allegro.pl"], "company_name": "Allegro", "aliases": ["Allegro Group", "Grupa Allegro", "Grupa Allegro Sp. z o.o."] }, { "domains": ["altiscale.com"], "company_name": "Altiscale" }, ] } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid. """ try: for company in json['companies']: name = self.__encode(company['company_name']) org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org for domain in company['domains']: if not domain: continue dom = Domain(domain=domain) org.domains.append(dom) except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_organizations(self, json): """Parse Stackalytics organizations. The Stackalytics organizations format is a JSON document stored under the "companies" key. The next JSON shows the structure of the document: { "companies" : [ { "domains": ["alcatel-lucent.com"], "company_name": "Alcatel-Lucent", "aliases": ["Alcatel Lucent", "Alcatel-Lcuent"] }, { "domains": ["allegrogroup.com", "allegro.pl"], "company_name": "Allegro", "aliases": ["Allegro Group", "Grupa Allegro", "Grupa Allegro Sp. z o.o."] }, { "domains": ["altiscale.com"], "company_name": "Altiscale" }, ] } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid. """ try: for company in json['companies']: name = self.__encode(company['company_name']) org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org for domain in company['domains']: if not domain: continue dom = Domain(domain=domain) org.domains.append(dom) except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_organizations", "(", "self", ",", "json", ")", ":", "try", ":", "for", "company", "in", "json", "[", "'companies'", "]", ":", "name", "=", "self", ".", "__encode", "(", "company", "[", "'company_name'", "]", ")", "org", "=", "self", "."...
Parse Stackalytics organizations. The Stackalytics organizations format is a JSON document stored under the "companies" key. The next JSON shows the structure of the document: { "companies" : [ { "domains": ["alcatel-lucent.com"], "company_name": "Alcatel-Lucent", "aliases": ["Alcatel Lucent", "Alcatel-Lcuent"] }, { "domains": ["allegrogroup.com", "allegro.pl"], "company_name": "Allegro", "aliases": ["Allegro Group", "Grupa Allegro", "Grupa Allegro Sp. z o.o."] }, { "domains": ["altiscale.com"], "company_name": "Altiscale" }, ] } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "Stackalytics", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L80-L128
train
25,536
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_identities
def __parse_identities(self, json): """Parse identities using Stackalytics format. The Stackalytics identities format is a JSON document under the "users" key. The document should follow the next schema: { "users": [ { "launchpad_id": "0-jsmith", "gerrit_id": "jsmith", "companies": [ { "company_name": "Example", "end_date": null } ], "user_name": "John Smith", "emails": ["jsmith@example.com", "jsmith@example.net"] }, { "companies": [ { "company_name": "Bitergia", "end_date": null }, { "company_name": "Example", "end_date": "2010-Jan-01" } ], "user_name": "John Doe", "emails": ["jdoe@bitergia.com", "jdoe@example.com"] } ] } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for user in json['users']: name = self.__encode(user['user_name']) uuid = name uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=None, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for email_addr in user['emails']: email = self.__encode(email_addr) identity = Identity(name=name, email=email, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for site_id in ['gerrit_id', 'launchpad_id']: username = user.get(site_id, None) if not username: continue username = self.__encode(username) source = self.source + ':' + site_id.replace('_id', '') identity = Identity(name=name, email=None, username=username, source=source, uuid=uuid) uid.identities.append(identity) for rol in self.__parse_enrollments(user): uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_identities(self, json): """Parse identities using Stackalytics format. The Stackalytics identities format is a JSON document under the "users" key. The document should follow the next schema: { "users": [ { "launchpad_id": "0-jsmith", "gerrit_id": "jsmith", "companies": [ { "company_name": "Example", "end_date": null } ], "user_name": "John Smith", "emails": ["jsmith@example.com", "jsmith@example.net"] }, { "companies": [ { "company_name": "Bitergia", "end_date": null }, { "company_name": "Example", "end_date": "2010-Jan-01" } ], "user_name": "John Doe", "emails": ["jdoe@bitergia.com", "jdoe@example.com"] } ] } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for user in json['users']: name = self.__encode(user['user_name']) uuid = name uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=None, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for email_addr in user['emails']: email = self.__encode(email_addr) identity = Identity(name=name, email=email, username=None, source=self.source, uuid=uuid) uid.identities.append(identity) for site_id in ['gerrit_id', 'launchpad_id']: username = user.get(site_id, None) if not username: continue username = self.__encode(username) source = self.source + ':' + site_id.replace('_id', '') identity = Identity(name=name, email=None, username=username, source=source, uuid=uuid) uid.identities.append(identity) for rol in self.__parse_enrollments(user): uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_identities", "(", "self", ",", "json", ")", ":", "try", ":", "for", "user", "in", "json", "[", "'users'", "]", ":", "name", "=", "self", ".", "__encode", "(", "user", "[", "'user_name'", "]", ")", "uuid", "=", "name", "uid", "=", "U...
Parse identities using Stackalytics format. The Stackalytics identities format is a JSON document under the "users" key. The document should follow the next schema: { "users": [ { "launchpad_id": "0-jsmith", "gerrit_id": "jsmith", "companies": [ { "company_name": "Example", "end_date": null } ], "user_name": "John Smith", "emails": ["jsmith@example.com", "jsmith@example.net"] }, { "companies": [ { "company_name": "Bitergia", "end_date": null }, { "company_name": "Example", "end_date": "2010-Jan-01" } ], "user_name": "John Doe", "emails": ["jdoe@bitergia.com", "jdoe@example.com"] } ] } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "identities", "using", "Stackalytics", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L130-L207
train
25,537
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__parse_enrollments
def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org start_date = MIN_PERIOD_DATE end_date = MAX_PERIOD_DATE if company['end_date']: end_date = str_to_datetime(company['end_date']) rol = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(rol) return enrollments
python
def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) self._organizations[name] = org start_date = MIN_PERIOD_DATE end_date = MAX_PERIOD_DATE if company['end_date']: end_date = str_to_datetime(company['end_date']) rol = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(rol) return enrollments
[ "def", "__parse_enrollments", "(", "self", ",", "user", ")", ":", "enrollments", "=", "[", "]", "for", "company", "in", "user", "[", "'companies'", "]", ":", "name", "=", "company", "[", "'company_name'", "]", "org", "=", "self", ".", "_organizations", "...
Parse user enrollments
[ "Parse", "user", "enrollments" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L209-L233
train
25,538
chaoss/grimoirelab-sortinghat
sortinghat/parsing/stackalytics.py
StackalyticsParser.__load_json
def __load_json(self, stream): """Load json stream into a dict object """ import json try: return json.loads(stream) except ValueError as e: cause = "invalid json format. %s" % str(e) raise InvalidFormatError(cause=cause)
python
def __load_json(self, stream): """Load json stream into a dict object """ import json try: return json.loads(stream) except ValueError as e: cause = "invalid json format. %s" % str(e) raise InvalidFormatError(cause=cause)
[ "def", "__load_json", "(", "self", ",", "stream", ")", ":", "import", "json", "try", ":", "return", "json", ".", "loads", "(", "stream", ")", "except", "ValueError", "as", "e", ":", "cause", "=", "\"invalid json format. %s\"", "%", "str", "(", "e", ")", ...
Load json stream into a dict object
[ "Load", "json", "stream", "into", "a", "dict", "object" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/stackalytics.py#L235-L244
train
25,539
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse
def __parse(self, stream, has_orgs): """Parse identities and organizations using mailmap format. Mailmap format is a text plain document that stores on each line a map between an email address and its aliases. Each line follows any of the next formats: Proper Name <commit@email.xx> <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> Commit Name <commit@email.xx> When the flag `has_orgs` is set, the stream maps organizations an identities, following the next format: Organization Name <org@email.xx> Proper Name <proper@email.xx> :parse data: mailmap stream to parse :raise InvalidFormatError: raised when the format of the stream is not valid. """ if has_orgs: self.__parse_organizations(stream) else: self.__parse_identities(stream)
python
def __parse(self, stream, has_orgs): """Parse identities and organizations using mailmap format. Mailmap format is a text plain document that stores on each line a map between an email address and its aliases. Each line follows any of the next formats: Proper Name <commit@email.xx> <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> Commit Name <commit@email.xx> When the flag `has_orgs` is set, the stream maps organizations an identities, following the next format: Organization Name <org@email.xx> Proper Name <proper@email.xx> :parse data: mailmap stream to parse :raise InvalidFormatError: raised when the format of the stream is not valid. """ if has_orgs: self.__parse_organizations(stream) else: self.__parse_identities(stream)
[ "def", "__parse", "(", "self", ",", "stream", ",", "has_orgs", ")", ":", "if", "has_orgs", ":", "self", ".", "__parse_organizations", "(", "stream", ")", "else", ":", "self", ".", "__parse_identities", "(", "stream", ")" ]
Parse identities and organizations using mailmap format. Mailmap format is a text plain document that stores on each line a map between an email address and its aliases. Each line follows any of the next formats: Proper Name <commit@email.xx> <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> <commit@email.xx> Proper Name <proper@email.xx> Commit Name <commit@email.xx> When the flag `has_orgs` is set, the stream maps organizations an identities, following the next format: Organization Name <org@email.xx> Proper Name <proper@email.xx> :parse data: mailmap stream to parse :raise InvalidFormatError: raised when the format of the stream is not valid.
[ "Parse", "identities", "and", "organizations", "using", "mailmap", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L80-L105
train
25,540
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse_organizations
def __parse_organizations(self, stream): """Parse organizations stream""" for aliases in self.__parse_stream(stream): # Parse identity identity = self.__parse_alias(aliases[1]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid # Parse organization mailmap_id = aliases[0] name = self.__encode(mailmap_id[0]) if name in MAILMAP_NO_ORGS: continue org = Organization(name=name) self._organizations[name] = org enrollment = Enrollment(start=MIN_PERIOD_DATE, end=MAX_PERIOD_DATE, organization=org) uid.enrollments.append(enrollment)
python
def __parse_organizations(self, stream): """Parse organizations stream""" for aliases in self.__parse_stream(stream): # Parse identity identity = self.__parse_alias(aliases[1]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid # Parse organization mailmap_id = aliases[0] name = self.__encode(mailmap_id[0]) if name in MAILMAP_NO_ORGS: continue org = Organization(name=name) self._organizations[name] = org enrollment = Enrollment(start=MIN_PERIOD_DATE, end=MAX_PERIOD_DATE, organization=org) uid.enrollments.append(enrollment)
[ "def", "__parse_organizations", "(", "self", ",", "stream", ")", ":", "for", "aliases", "in", "self", ".", "__parse_stream", "(", "stream", ")", ":", "# Parse identity", "identity", "=", "self", ".", "__parse_alias", "(", "aliases", "[", "1", "]", ")", "uu...
Parse organizations stream
[ "Parse", "organizations", "stream" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L107-L135
train
25,541
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse_identities
def __parse_identities(self, stream): """Parse identities stream""" for aliases in self.__parse_stream(stream): identity = self.__parse_alias(aliases[0]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid profile = Profile(uuid=uuid, name=identity.name, email=identity.email, is_bot=False) uid.profile = profile # Aliases for alias in aliases[1:]: identity = self.__parse_alias(alias, uuid) uid.identities.append(identity) self._identities[uuid] = uid
python
def __parse_identities(self, stream): """Parse identities stream""" for aliases in self.__parse_stream(stream): identity = self.__parse_alias(aliases[0]) uuid = identity.email uid = self._identities.get(uuid, None) if not uid: uid = UniqueIdentity(uuid=uuid) identity.uuid = uuid uid.identities.append(identity) self._identities[uuid] = uid profile = Profile(uuid=uuid, name=identity.name, email=identity.email, is_bot=False) uid.profile = profile # Aliases for alias in aliases[1:]: identity = self.__parse_alias(alias, uuid) uid.identities.append(identity) self._identities[uuid] = uid
[ "def", "__parse_identities", "(", "self", ",", "stream", ")", ":", "for", "aliases", "in", "self", ".", "__parse_stream", "(", "stream", ")", ":", "identity", "=", "self", ".", "__parse_alias", "(", "aliases", "[", "0", "]", ")", "uuid", "=", "identity",...
Parse identities stream
[ "Parse", "identities", "stream" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L137-L161
train
25,542
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mailmap.py
MailmapParser.__parse_stream
def __parse_stream(self, stream): """Generic method to parse mailmap streams""" nline = 0 lines = stream.split('\n') for line in lines: nline += 1 # Ignore blank lines and comments m = re.match(self.LINES_TO_IGNORE_REGEX, line, re.UNICODE) if m: continue line = line.strip('\n').strip(' ') parts = line.split('>') if len(parts) == 0: cause = "line %s: invalid format" % str(nline) raise InvalidFormatError(cause=cause) aliases = [] for part in parts: part = part.replace(',', ' ') part = part.strip('\n').strip(' ') if len(part) == 0: continue if part.find('<') < 0: cause = "line %s: invalid format" % str(nline) raise InvalidFormatError(cause=cause) alias = email.utils.parseaddr(part + '>') aliases.append(alias) yield aliases
python
def __parse_stream(self, stream): """Generic method to parse mailmap streams""" nline = 0 lines = stream.split('\n') for line in lines: nline += 1 # Ignore blank lines and comments m = re.match(self.LINES_TO_IGNORE_REGEX, line, re.UNICODE) if m: continue line = line.strip('\n').strip(' ') parts = line.split('>') if len(parts) == 0: cause = "line %s: invalid format" % str(nline) raise InvalidFormatError(cause=cause) aliases = [] for part in parts: part = part.replace(',', ' ') part = part.strip('\n').strip(' ') if len(part) == 0: continue if part.find('<') < 0: cause = "line %s: invalid format" % str(nline) raise InvalidFormatError(cause=cause) alias = email.utils.parseaddr(part + '>') aliases.append(alias) yield aliases
[ "def", "__parse_stream", "(", "self", ",", "stream", ")", ":", "nline", "=", "0", "lines", "=", "stream", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "nline", "+=", "1", "# Ignore blank lines and comments", "m", "=", "re", ".", ...
Generic method to parse mailmap streams
[ "Generic", "method", "to", "parse", "mailmap", "streams" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L170-L207
train
25,543
chaoss/grimoirelab-sortinghat
sortinghat/cmd/merge.py
Merge.run
def run(self, *args): """Merge two identities. When <from_uuid> or <to_uuid> are empty the command does not have any effect. The same happens when both <from_uuid> and <to_uuid> are the same unique identity. """ params = self.parser.parse_args(args) from_uuid = params.from_uuid to_uuid = params.to_uuid code = self.merge(from_uuid, to_uuid) return code
python
def run(self, *args): """Merge two identities. When <from_uuid> or <to_uuid> are empty the command does not have any effect. The same happens when both <from_uuid> and <to_uuid> are the same unique identity. """ params = self.parser.parse_args(args) from_uuid = params.from_uuid to_uuid = params.to_uuid code = self.merge(from_uuid, to_uuid) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "from_uuid", "=", "params", ".", "from_uuid", "to_uuid", "=", "params", ".", "to_uuid", "code", "=", "self", ".", "merge...
Merge two identities. When <from_uuid> or <to_uuid> are empty the command does not have any effect. The same happens when both <from_uuid> and <to_uuid> are the same unique identity.
[ "Merge", "two", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/merge.py#L67-L81
train
25,544
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
create_identity_matcher
def create_identity_matcher(matcher='default', blacklist=None, sources=None, strict=True): """Create an identity matcher of the given type. Factory function that creates an identity matcher object of the type defined on 'matcher' parameter. A blacklist can also be added to ignore those values while matching. :param matcher: type of the matcher :param blacklist: list of entries to ignore while matching :param sources: only match the identities from these sources :param strict: strict matching (i.e, well-formed email addresses) :returns: a identity matcher object of the given type :raises MatcherNotSupportedError: when the given matcher type is not supported or available """ import sortinghat.matching as matching if matcher not in matching.SORTINGHAT_IDENTITIES_MATCHERS: raise MatcherNotSupportedError(matcher=str(matcher)) klass = matching.SORTINGHAT_IDENTITIES_MATCHERS[matcher] return klass(blacklist=blacklist, sources=sources, strict=strict)
python
def create_identity_matcher(matcher='default', blacklist=None, sources=None, strict=True): """Create an identity matcher of the given type. Factory function that creates an identity matcher object of the type defined on 'matcher' parameter. A blacklist can also be added to ignore those values while matching. :param matcher: type of the matcher :param blacklist: list of entries to ignore while matching :param sources: only match the identities from these sources :param strict: strict matching (i.e, well-formed email addresses) :returns: a identity matcher object of the given type :raises MatcherNotSupportedError: when the given matcher type is not supported or available """ import sortinghat.matching as matching if matcher not in matching.SORTINGHAT_IDENTITIES_MATCHERS: raise MatcherNotSupportedError(matcher=str(matcher)) klass = matching.SORTINGHAT_IDENTITIES_MATCHERS[matcher] return klass(blacklist=blacklist, sources=sources, strict=strict)
[ "def", "create_identity_matcher", "(", "matcher", "=", "'default'", ",", "blacklist", "=", "None", ",", "sources", "=", "None", ",", "strict", "=", "True", ")", ":", "import", "sortinghat", ".", "matching", "as", "matching", "if", "matcher", "not", "in", "...
Create an identity matcher of the given type. Factory function that creates an identity matcher object of the type defined on 'matcher' parameter. A blacklist can also be added to ignore those values while matching. :param matcher: type of the matcher :param blacklist: list of entries to ignore while matching :param sources: only match the identities from these sources :param strict: strict matching (i.e, well-formed email addresses) :returns: a identity matcher object of the given type :raises MatcherNotSupportedError: when the given matcher type is not supported or available
[ "Create", "an", "identity", "matcher", "of", "the", "given", "type", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L125-L150
train
25,545
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
match
def match(uidentities, matcher, fastmode=False): """Find matches in a set of unique identities. This function looks for possible similar or equal identities from a set of unique identities. The result will be a list of subsets where each subset is a list of matching identities. When `fastmode` is set a new and experimental matching algorithm will be used. It consumes more resources (a big amount of memory) but it is, at least, two orders of maginute faster than the classic algorithm. :param uidentities: list of unique identities to match :param matcher: instance of the matcher :param fastmode: use a faster algorithm :returns: a list of subsets with the matched unique identities :raises MatcherNotSupportedError: when matcher does not support fast mode matching :raises TypeError: when matcher is not an instance of IdentityMatcher class """ if not isinstance(matcher, IdentityMatcher): raise TypeError("matcher is not an instance of IdentityMatcher") if fastmode: try: matcher.matching_criteria() except NotImplementedError: name = "'%s (fast mode)'" % matcher.__class__.__name__.lower() raise MatcherNotSupportedError(matcher=name) filtered, no_filtered, uuids = \ _filter_unique_identities(uidentities, matcher) if not fastmode: matched = _match(filtered, matcher) else: matched = _match_with_pandas(filtered, matcher) matched = _build_matches(matched, uuids, no_filtered, fastmode) return matched
python
def match(uidentities, matcher, fastmode=False): """Find matches in a set of unique identities. This function looks for possible similar or equal identities from a set of unique identities. The result will be a list of subsets where each subset is a list of matching identities. When `fastmode` is set a new and experimental matching algorithm will be used. It consumes more resources (a big amount of memory) but it is, at least, two orders of maginute faster than the classic algorithm. :param uidentities: list of unique identities to match :param matcher: instance of the matcher :param fastmode: use a faster algorithm :returns: a list of subsets with the matched unique identities :raises MatcherNotSupportedError: when matcher does not support fast mode matching :raises TypeError: when matcher is not an instance of IdentityMatcher class """ if not isinstance(matcher, IdentityMatcher): raise TypeError("matcher is not an instance of IdentityMatcher") if fastmode: try: matcher.matching_criteria() except NotImplementedError: name = "'%s (fast mode)'" % matcher.__class__.__name__.lower() raise MatcherNotSupportedError(matcher=name) filtered, no_filtered, uuids = \ _filter_unique_identities(uidentities, matcher) if not fastmode: matched = _match(filtered, matcher) else: matched = _match_with_pandas(filtered, matcher) matched = _build_matches(matched, uuids, no_filtered, fastmode) return matched
[ "def", "match", "(", "uidentities", ",", "matcher", ",", "fastmode", "=", "False", ")", ":", "if", "not", "isinstance", "(", "matcher", ",", "IdentityMatcher", ")", ":", "raise", "TypeError", "(", "\"matcher is not an instance of IdentityMatcher\"", ")", "if", "...
Find matches in a set of unique identities. This function looks for possible similar or equal identities from a set of unique identities. The result will be a list of subsets where each subset is a list of matching identities. When `fastmode` is set a new and experimental matching algorithm will be used. It consumes more resources (a big amount of memory) but it is, at least, two orders of maginute faster than the classic algorithm. :param uidentities: list of unique identities to match :param matcher: instance of the matcher :param fastmode: use a faster algorithm :returns: a list of subsets with the matched unique identities :raises MatcherNotSupportedError: when matcher does not support fast mode matching :raises TypeError: when matcher is not an instance of IdentityMatcher class
[ "Find", "matches", "in", "a", "set", "of", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L153-L196
train
25,546
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
_match
def _match(filtered, matcher): """Old method to find matches in a set of filtered identities.""" def match_filtered_identities(x, ids, matcher): """Check if an identity matches a set of identities""" for y in ids: if x.uuid == y.uuid: return True if matcher.match_filtered_identities(x, y): return True return False # Find subsets of matches matched = [] while filtered: candidates = [] no_match = [] x = filtered.pop(0) while matched: ids = matched.pop(0) if match_filtered_identities(x, ids, matcher): candidates += ids else: no_match.append(ids) candidates.append(x) # Generate the new list of matched subsets matched = [candidates] + no_match return matched
python
def _match(filtered, matcher): """Old method to find matches in a set of filtered identities.""" def match_filtered_identities(x, ids, matcher): """Check if an identity matches a set of identities""" for y in ids: if x.uuid == y.uuid: return True if matcher.match_filtered_identities(x, y): return True return False # Find subsets of matches matched = [] while filtered: candidates = [] no_match = [] x = filtered.pop(0) while matched: ids = matched.pop(0) if match_filtered_identities(x, ids, matcher): candidates += ids else: no_match.append(ids) candidates.append(x) # Generate the new list of matched subsets matched = [candidates] + no_match return matched
[ "def", "_match", "(", "filtered", ",", "matcher", ")", ":", "def", "match_filtered_identities", "(", "x", ",", "ids", ",", "matcher", ")", ":", "\"\"\"Check if an identity matches a set of identities\"\"\"", "for", "y", "in", "ids", ":", "if", "x", ".", "uuid", ...
Old method to find matches in a set of filtered identities.
[ "Old", "method", "to", "find", "matches", "in", "a", "set", "of", "filtered", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L199-L234
train
25,547
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
_match_with_pandas
def _match_with_pandas(filtered, matcher): """Find matches in a set using Pandas' library.""" import pandas data = [fl.to_dict() for fl in filtered] if not data: return [] df = pandas.DataFrame(data) df = df.sort_values(['uuid']) cdfs = [] criteria = matcher.matching_criteria() for c in criteria: cdf = df[['id', 'uuid', c]] cdf = cdf.dropna(subset=[c]) cdf = pandas.merge(cdf, cdf, on=c, how='left') cdf = cdf[['uuid_x', 'uuid_y']] cdfs.append(cdf) result = pandas.concat(cdfs) result = result.drop_duplicates() groups = result.groupby(by=['uuid_x'], as_index=True, sort=True) matched = _calculate_matches_closures(groups) return matched
python
def _match_with_pandas(filtered, matcher): """Find matches in a set using Pandas' library.""" import pandas data = [fl.to_dict() for fl in filtered] if not data: return [] df = pandas.DataFrame(data) df = df.sort_values(['uuid']) cdfs = [] criteria = matcher.matching_criteria() for c in criteria: cdf = df[['id', 'uuid', c]] cdf = cdf.dropna(subset=[c]) cdf = pandas.merge(cdf, cdf, on=c, how='left') cdf = cdf[['uuid_x', 'uuid_y']] cdfs.append(cdf) result = pandas.concat(cdfs) result = result.drop_duplicates() groups = result.groupby(by=['uuid_x'], as_index=True, sort=True) matched = _calculate_matches_closures(groups) return matched
[ "def", "_match_with_pandas", "(", "filtered", ",", "matcher", ")", ":", "import", "pandas", "data", "=", "[", "fl", ".", "to_dict", "(", ")", "for", "fl", "in", "filtered", "]", "if", "not", "data", ":", "return", "[", "]", "df", "=", "pandas", ".", ...
Find matches in a set using Pandas' library.
[ "Find", "matches", "in", "a", "set", "using", "Pandas", "library", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L237-L267
train
25,548
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
_filter_unique_identities
def _filter_unique_identities(uidentities, matcher): """Filter a set of unique identities. This function will use the `matcher` to generate a list of `FilteredIdentity` objects. It will return a tuple with the list of filtered objects, the unique identities not filtered and a table mapping uuids with unique identities. """ filtered = [] no_filtered = [] uuids = {} for uidentity in uidentities: n = len(filtered) filtered += matcher.filter(uidentity) if len(filtered) > n: uuids[uidentity.uuid] = uidentity else: no_filtered.append([uidentity]) return filtered, no_filtered, uuids
python
def _filter_unique_identities(uidentities, matcher): """Filter a set of unique identities. This function will use the `matcher` to generate a list of `FilteredIdentity` objects. It will return a tuple with the list of filtered objects, the unique identities not filtered and a table mapping uuids with unique identities. """ filtered = [] no_filtered = [] uuids = {} for uidentity in uidentities: n = len(filtered) filtered += matcher.filter(uidentity) if len(filtered) > n: uuids[uidentity.uuid] = uidentity else: no_filtered.append([uidentity]) return filtered, no_filtered, uuids
[ "def", "_filter_unique_identities", "(", "uidentities", ",", "matcher", ")", ":", "filtered", "=", "[", "]", "no_filtered", "=", "[", "]", "uuids", "=", "{", "}", "for", "uidentity", "in", "uidentities", ":", "n", "=", "len", "(", "filtered", ")", "filte...
Filter a set of unique identities. This function will use the `matcher` to generate a list of `FilteredIdentity` objects. It will return a tuple with the list of filtered objects, the unique identities not filtered and a table mapping uuids with unique identities.
[ "Filter", "a", "set", "of", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L270-L292
train
25,549
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
_build_matches
def _build_matches(matches, uuids, no_filtered, fastmode=False): """Build a list with matching subsets""" result = [] for m in matches: mk = m[0].uuid if not fastmode else m[0] subset = [uuids[mk]] for id_ in m[1:]: uk = id_.uuid if not fastmode else id_ u = uuids[uk] if u not in subset: subset.append(u) result.append(subset) result += no_filtered result.sort(key=len, reverse=True) sresult = [] for r in result: r.sort(key=lambda id_: id_.uuid) sresult.append(r) return sresult
python
def _build_matches(matches, uuids, no_filtered, fastmode=False): """Build a list with matching subsets""" result = [] for m in matches: mk = m[0].uuid if not fastmode else m[0] subset = [uuids[mk]] for id_ in m[1:]: uk = id_.uuid if not fastmode else id_ u = uuids[uk] if u not in subset: subset.append(u) result.append(subset) result += no_filtered result.sort(key=len, reverse=True) sresult = [] for r in result: r.sort(key=lambda id_: id_.uuid) sresult.append(r) return sresult
[ "def", "_build_matches", "(", "matches", ",", "uuids", ",", "no_filtered", ",", "fastmode", "=", "False", ")", ":", "result", "=", "[", "]", "for", "m", "in", "matches", ":", "mk", "=", "m", "[", "0", "]", ".", "uuid", "if", "not", "fastmode", "els...
Build a list with matching subsets
[ "Build", "a", "list", "with", "matching", "subsets" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L295-L321
train
25,550
chaoss/grimoirelab-sortinghat
sortinghat/matcher.py
_calculate_matches_closures
def _calculate_matches_closures(groups): """Find the transitive closure of each unique identity. This function uses a BFS algorithm to build set of matches. For instance, given a list of matched unique identities like A = {A, B}; B = {B,A,C}, C = {C,} and D = {D,} the output will be A = {A, B, C} and D = {D,}. :param groups: groups of unique identities """ matches = [] ns = sorted(groups.groups.keys()) while ns: n = ns.pop(0) visited = [n] vs = [v for v in groups.get_group(n)['uuid_y']] while vs: v = vs.pop(0) if v in visited: continue nvs = [nv for nv in groups.get_group(v)['uuid_y']] vs += nvs visited.append(v) try: ns.remove(v) except: pass matches.append(visited) return matches
python
def _calculate_matches_closures(groups): """Find the transitive closure of each unique identity. This function uses a BFS algorithm to build set of matches. For instance, given a list of matched unique identities like A = {A, B}; B = {B,A,C}, C = {C,} and D = {D,} the output will be A = {A, B, C} and D = {D,}. :param groups: groups of unique identities """ matches = [] ns = sorted(groups.groups.keys()) while ns: n = ns.pop(0) visited = [n] vs = [v for v in groups.get_group(n)['uuid_y']] while vs: v = vs.pop(0) if v in visited: continue nvs = [nv for nv in groups.get_group(v)['uuid_y']] vs += nvs visited.append(v) try: ns.remove(v) except: pass matches.append(visited) return matches
[ "def", "_calculate_matches_closures", "(", "groups", ")", ":", "matches", "=", "[", "]", "ns", "=", "sorted", "(", "groups", ".", "groups", ".", "keys", "(", ")", ")", "while", "ns", ":", "n", "=", "ns", ".", "pop", "(", "0", ")", "visited", "=", ...
Find the transitive closure of each unique identity. This function uses a BFS algorithm to build set of matches. For instance, given a list of matched unique identities like A = {A, B}; B = {B,A,C}, C = {C,} and D = {D,} the output will be A = {A, B, C} and D = {D,}. :param groups: groups of unique identities
[ "Find", "the", "transitive", "closure", "of", "each", "unique", "identity", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L324-L360
train
25,551
chaoss/grimoirelab-sortinghat
sortinghat/matching/email_name.py
EmailNameMatcher.match
def match(self, a, b): """Determine if two unique identities are the same. This method compares the email addresses or the names of each identity to check if the given unique identities are the same. When the given unique identities are the same object or share the same UUID, this will also produce a positive match. Identities which their email addresses or names are in the blacklist will be ignored during the matching. :param a: unique identity to match :param b: unique identity to match :returns: True when both unique identities are likely to be the same. Otherwise, returns False. :raises ValueError: when any of the given unique identities is not an instance of UniqueIdentity class """ if not isinstance(a, UniqueIdentity): raise ValueError("<a> is not an instance of UniqueIdentity") if not isinstance(b, UniqueIdentity): raise ValueError("<b> is not an instance of UniqueIdentity") if a.uuid and b.uuid and a.uuid == b.uuid: return True filtered_a = self.filter(a) filtered_b = self.filter(b) for fa in filtered_a: for fb in filtered_b: if self.match_filtered_identities(fa, fb): return True return False
python
def match(self, a, b): """Determine if two unique identities are the same. This method compares the email addresses or the names of each identity to check if the given unique identities are the same. When the given unique identities are the same object or share the same UUID, this will also produce a positive match. Identities which their email addresses or names are in the blacklist will be ignored during the matching. :param a: unique identity to match :param b: unique identity to match :returns: True when both unique identities are likely to be the same. Otherwise, returns False. :raises ValueError: when any of the given unique identities is not an instance of UniqueIdentity class """ if not isinstance(a, UniqueIdentity): raise ValueError("<a> is not an instance of UniqueIdentity") if not isinstance(b, UniqueIdentity): raise ValueError("<b> is not an instance of UniqueIdentity") if a.uuid and b.uuid and a.uuid == b.uuid: return True filtered_a = self.filter(a) filtered_b = self.filter(b) for fa in filtered_a: for fb in filtered_b: if self.match_filtered_identities(fa, fb): return True return False
[ "def", "match", "(", "self", ",", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "a", ",", "UniqueIdentity", ")", ":", "raise", "ValueError", "(", "\"<a> is not an instance of UniqueIdentity\"", ")", "if", "not", "isinstance", "(", "b", ",", "Uni...
Determine if two unique identities are the same. This method compares the email addresses or the names of each identity to check if the given unique identities are the same. When the given unique identities are the same object or share the same UUID, this will also produce a positive match. Identities which their email addresses or names are in the blacklist will be ignored during the matching. :param a: unique identity to match :param b: unique identity to match :returns: True when both unique identities are likely to be the same. Otherwise, returns False. :raises ValueError: when any of the given unique identities is not an instance of UniqueIdentity class
[ "Determine", "if", "two", "unique", "identities", "are", "the", "same", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matching/email_name.py#L77-L112
train
25,552
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
find_unique_identity
def find_unique_identity(session, uuid): """Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identity to find :returns: a unique identity object; `None` when the unique identity does not exist """ uidentity = session.query(UniqueIdentity). \ filter(UniqueIdentity.uuid == uuid).first() return uidentity
python
def find_unique_identity(session, uuid): """Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identity to find :returns: a unique identity object; `None` when the unique identity does not exist """ uidentity = session.query(UniqueIdentity). \ filter(UniqueIdentity.uuid == uuid).first() return uidentity
[ "def", "find_unique_identity", "(", "session", ",", "uuid", ")", ":", "uidentity", "=", "session", ".", "query", "(", "UniqueIdentity", ")", ".", "filter", "(", "UniqueIdentity", ".", "uuid", "==", "uuid", ")", ".", "first", "(", ")", "return", "uidentity"...
Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identity to find :returns: a unique identity object; `None` when the unique identity does not exist
[ "Find", "a", "unique", "identity", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L40-L56
train
25,553
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
find_identity
def find_identity(session, id_): """Find an identity. Find an identity by its ID using the given `session`. When the identity does not exist the function will return `None`. :param session: database session :param id_: id of the identity to find :returns: an identity object; `None` when the identity does not exist """ identity = session.query(Identity). \ filter(Identity.id == id_).first() return identity
python
def find_identity(session, id_): """Find an identity. Find an identity by its ID using the given `session`. When the identity does not exist the function will return `None`. :param session: database session :param id_: id of the identity to find :returns: an identity object; `None` when the identity does not exist """ identity = session.query(Identity). \ filter(Identity.id == id_).first() return identity
[ "def", "find_identity", "(", "session", ",", "id_", ")", ":", "identity", "=", "session", ".", "query", "(", "Identity", ")", ".", "filter", "(", "Identity", ".", "id", "==", "id_", ")", ".", "first", "(", ")", "return", "identity" ]
Find an identity. Find an identity by its ID using the given `session`. When the identity does not exist the function will return `None`. :param session: database session :param id_: id of the identity to find :returns: an identity object; `None` when the identity does not exist
[ "Find", "an", "identity", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L59-L75
train
25,554
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
find_organization
def find_organization(session, name): """Find an organization. Find an organization by its `name` using the given `session`. When the organization does not exist the function will return `None`. :param session: database session :param name: name of the organization to find :returns: an organization object; `None` when the organization does not exist """ organization = session.query(Organization). \ filter(Organization.name == name).first() return organization
python
def find_organization(session, name): """Find an organization. Find an organization by its `name` using the given `session`. When the organization does not exist the function will return `None`. :param session: database session :param name: name of the organization to find :returns: an organization object; `None` when the organization does not exist """ organization = session.query(Organization). \ filter(Organization.name == name).first() return organization
[ "def", "find_organization", "(", "session", ",", "name", ")", ":", "organization", "=", "session", ".", "query", "(", "Organization", ")", ".", "filter", "(", "Organization", ".", "name", "==", "name", ")", ".", "first", "(", ")", "return", "organization" ...
Find an organization. Find an organization by its `name` using the given `session`. When the organization does not exist the function will return `None`. :param session: database session :param name: name of the organization to find :returns: an organization object; `None` when the organization does not exist
[ "Find", "an", "organization", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L78-L94
train
25,555
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
find_domain
def find_domain(session, name): """Find a domain. Find a domain by its domain name using the given `session`. When the domain does not exist the function will return `None`. :param session: database session :param name: name of the domain to find :returns: a domain object; `None` when the domain does not exist """ domain = session.query(Domain). \ filter(Domain.domain == name).first() return domain
python
def find_domain(session, name): """Find a domain. Find a domain by its domain name using the given `session`. When the domain does not exist the function will return `None`. :param session: database session :param name: name of the domain to find :returns: a domain object; `None` when the domain does not exist """ domain = session.query(Domain). \ filter(Domain.domain == name).first() return domain
[ "def", "find_domain", "(", "session", ",", "name", ")", ":", "domain", "=", "session", ".", "query", "(", "Domain", ")", ".", "filter", "(", "Domain", ".", "domain", "==", "name", ")", ".", "first", "(", ")", "return", "domain" ]
Find a domain. Find a domain by its domain name using the given `session`. When the domain does not exist the function will return `None`. :param session: database session :param name: name of the domain to find :returns: a domain object; `None` when the domain does not exist
[ "Find", "a", "domain", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L97-L113
train
25,556
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
find_country
def find_country(session, code): """Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 code of the country to find :return: a country object; `None` when the country does not exist """ country = session.query(Country).\ filter(Country.code == code).first() return country
python
def find_country(session, code): """Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 code of the country to find :return: a country object; `None` when the country does not exist """ country = session.query(Country).\ filter(Country.code == code).first() return country
[ "def", "find_country", "(", "session", ",", "code", ")", ":", "country", "=", "session", ".", "query", "(", "Country", ")", ".", "filter", "(", "Country", ".", "code", "==", "code", ")", ".", "first", "(", ")", "return", "country" ]
Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 code of the country to find :return: a country object; `None` when the country does not exist
[ "Find", "a", "country", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L116-L133
train
25,557
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
add_unique_identity
def add_unique_identity(session, uuid): """Add a unique identity to the session. This function adds a unique identity to the session with `uuid` string as unique identifier. This identifier cannot be empty or `None`. When the unique identity is added, a new empty profile for this object is created too. As a result, the function returns a new `UniqueIdentity` object. :param session: database session :param uuid: unique identifier for the unique identity :return: a new unique identity :raises ValueError: when `uuid` is `None` or an empty string """ if uuid is None: raise ValueError("'uuid' cannot be None") if uuid == '': raise ValueError("'uuid' cannot be an empty string") uidentity = UniqueIdentity(uuid=uuid) uidentity.profile = Profile() uidentity.last_modified = datetime.datetime.utcnow() session.add(uidentity) return uidentity
python
def add_unique_identity(session, uuid): """Add a unique identity to the session. This function adds a unique identity to the session with `uuid` string as unique identifier. This identifier cannot be empty or `None`. When the unique identity is added, a new empty profile for this object is created too. As a result, the function returns a new `UniqueIdentity` object. :param session: database session :param uuid: unique identifier for the unique identity :return: a new unique identity :raises ValueError: when `uuid` is `None` or an empty string """ if uuid is None: raise ValueError("'uuid' cannot be None") if uuid == '': raise ValueError("'uuid' cannot be an empty string") uidentity = UniqueIdentity(uuid=uuid) uidentity.profile = Profile() uidentity.last_modified = datetime.datetime.utcnow() session.add(uidentity) return uidentity
[ "def", "add_unique_identity", "(", "session", ",", "uuid", ")", ":", "if", "uuid", "is", "None", ":", "raise", "ValueError", "(", "\"'uuid' cannot be None\"", ")", "if", "uuid", "==", "''", ":", "raise", "ValueError", "(", "\"'uuid' cannot be an empty string\"", ...
Add a unique identity to the session. This function adds a unique identity to the session with `uuid` string as unique identifier. This identifier cannot be empty or `None`. When the unique identity is added, a new empty profile for this object is created too. As a result, the function returns a new `UniqueIdentity` object. :param session: database session :param uuid: unique identifier for the unique identity :return: a new unique identity :raises ValueError: when `uuid` is `None` or an empty string
[ "Add", "a", "unique", "identity", "to", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L136-L167
train
25,558
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
add_identity
def add_identity(session, uidentity, identity_id, source, name=None, email=None, username=None): """Add an identity to the session. This function adds a new identity to the session using `identity_id` as its identifier. The new identity will also be linked to the unique identity object of `uidentity`. Neither the values given to `identity_id` nor to `source` can be `None` or empty. Moreover, `name`, `email` or `username` parameters need a non empty value. As a result, the function returns a new `Identity` object. :param session: database session :param uidentity: links the new identity to this unique identity object :param identity_id: identifier for the new identity :param source: data source where this identity was found :param name: full name of the identity :param email: email of the identity :param username: user name used by the identity :return: a new identity :raises ValueError: when `identity_id` and `source` are `None` or empty; when all of the data parameters are `None` or empty. """ if identity_id is None: raise ValueError("'identity_id' cannot be None") if identity_id == '': raise ValueError("'identity_id' cannot be an empty string") if source is None: raise ValueError("'source' cannot be None") if source == '': raise ValueError("'source' cannot be an empty string") if not (name or email or username): raise ValueError("identity data cannot be None or empty") identity = Identity(id=identity_id, name=name, email=email, username=username, source=source) identity.last_modified = datetime.datetime.utcnow() identity.uidentity = uidentity identity.uidentity.last_modified = identity.last_modified session.add(identity) return identity
python
def add_identity(session, uidentity, identity_id, source, name=None, email=None, username=None): """Add an identity to the session. This function adds a new identity to the session using `identity_id` as its identifier. The new identity will also be linked to the unique identity object of `uidentity`. Neither the values given to `identity_id` nor to `source` can be `None` or empty. Moreover, `name`, `email` or `username` parameters need a non empty value. As a result, the function returns a new `Identity` object. :param session: database session :param uidentity: links the new identity to this unique identity object :param identity_id: identifier for the new identity :param source: data source where this identity was found :param name: full name of the identity :param email: email of the identity :param username: user name used by the identity :return: a new identity :raises ValueError: when `identity_id` and `source` are `None` or empty; when all of the data parameters are `None` or empty. """ if identity_id is None: raise ValueError("'identity_id' cannot be None") if identity_id == '': raise ValueError("'identity_id' cannot be an empty string") if source is None: raise ValueError("'source' cannot be None") if source == '': raise ValueError("'source' cannot be an empty string") if not (name or email or username): raise ValueError("identity data cannot be None or empty") identity = Identity(id=identity_id, name=name, email=email, username=username, source=source) identity.last_modified = datetime.datetime.utcnow() identity.uidentity = uidentity identity.uidentity.last_modified = identity.last_modified session.add(identity) return identity
[ "def", "add_identity", "(", "session", ",", "uidentity", ",", "identity_id", ",", "source", ",", "name", "=", "None", ",", "email", "=", "None", ",", "username", "=", "None", ")", ":", "if", "identity_id", "is", "None", ":", "raise", "ValueError", "(", ...
Add an identity to the session. This function adds a new identity to the session using `identity_id` as its identifier. The new identity will also be linked to the unique identity object of `uidentity`. Neither the values given to `identity_id` nor to `source` can be `None` or empty. Moreover, `name`, `email` or `username` parameters need a non empty value. As a result, the function returns a new `Identity` object. :param session: database session :param uidentity: links the new identity to this unique identity object :param identity_id: identifier for the new identity :param source: data source where this identity was found :param name: full name of the identity :param email: email of the identity :param username: user name used by the identity :return: a new identity :raises ValueError: when `identity_id` and `source` are `None` or empty; when all of the data parameters are `None` or empty.
[ "Add", "an", "identity", "to", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L184-L230
train
25,559
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
delete_identity
def delete_identity(session, identity): """Remove an identity from the session. This function removes from the session the identity given in `identity`. Take into account this function does not remove unique identities in the case they get empty. :param session: database session :param identity: identity to remove """ uidentity = identity.uidentity uidentity.last_modified = datetime.datetime.utcnow() session.delete(identity) session.flush()
python
def delete_identity(session, identity): """Remove an identity from the session. This function removes from the session the identity given in `identity`. Take into account this function does not remove unique identities in the case they get empty. :param session: database session :param identity: identity to remove """ uidentity = identity.uidentity uidentity.last_modified = datetime.datetime.utcnow() session.delete(identity) session.flush()
[ "def", "delete_identity", "(", "session", ",", "identity", ")", ":", "uidentity", "=", "identity", ".", "uidentity", "uidentity", ".", "last_modified", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "session", ".", "delete", "(", "identity", ")",...
Remove an identity from the session. This function removes from the session the identity given in `identity`. Take into account this function does not remove unique identities in the case they get empty. :param session: database session :param identity: identity to remove
[ "Remove", "an", "identity", "from", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L233-L247
train
25,560
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
add_organization
def add_organization(session, name): """Add an organization to the session. This function adds a new organization to the session, using the given `name` as an identifier. Name cannot be empty or `None`. It returns a new `Organization` object. :param session: database session :param name: name of the organization :return: a new organization :raises ValueError: when `name` is `None` or empty """ if name is None: raise ValueError("'name' cannot be None") if name == '': raise ValueError("'name' cannot be an empty string") organization = Organization(name=name) session.add(organization) return organization
python
def add_organization(session, name): """Add an organization to the session. This function adds a new organization to the session, using the given `name` as an identifier. Name cannot be empty or `None`. It returns a new `Organization` object. :param session: database session :param name: name of the organization :return: a new organization :raises ValueError: when `name` is `None` or empty """ if name is None: raise ValueError("'name' cannot be None") if name == '': raise ValueError("'name' cannot be an empty string") organization = Organization(name=name) session.add(organization) return organization
[ "def", "add_organization", "(", "session", ",", "name", ")", ":", "if", "name", "is", "None", ":", "raise", "ValueError", "(", "\"'name' cannot be None\"", ")", "if", "name", "==", "''", ":", "raise", "ValueError", "(", "\"'name' cannot be an empty string\"", ")...
Add an organization to the session. This function adds a new organization to the session, using the given `name` as an identifier. Name cannot be empty or `None`. It returns a new `Organization` object. :param session: database session :param name: name of the organization :return: a new organization :raises ValueError: when `name` is `None` or empty
[ "Add", "an", "organization", "to", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L250-L275
train
25,561
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
delete_organization
def delete_organization(session, organization): """Remove an organization from the session. Function that removes from the session the organization given in `organization`. Data related such as domains or enrollments are also removed. :param session: database session :param organization: organization to remove """ last_modified = datetime.datetime.utcnow() for enrollment in organization.enrollments: enrollment.uidentity.last_modified = last_modified session.delete(organization) session.flush()
python
def delete_organization(session, organization): """Remove an organization from the session. Function that removes from the session the organization given in `organization`. Data related such as domains or enrollments are also removed. :param session: database session :param organization: organization to remove """ last_modified = datetime.datetime.utcnow() for enrollment in organization.enrollments: enrollment.uidentity.last_modified = last_modified session.delete(organization) session.flush()
[ "def", "delete_organization", "(", "session", ",", "organization", ")", ":", "last_modified", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "for", "enrollment", "in", "organization", ".", "enrollments", ":", "enrollment", ".", "uidentity", ".", "l...
Remove an organization from the session. Function that removes from the session the organization given in `organization`. Data related such as domains or enrollments are also removed. :param session: database session :param organization: organization to remove
[ "Remove", "an", "organization", "from", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L278-L294
train
25,562
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
add_domain
def add_domain(session, organization, domain_name, is_top_domain=False): """Add a domain to the session. This function adds a new domain to the session using `domain_name` as its identifier. The new domain will also be linked to the organization object of `organization`. Values assigned to `domain_name` cannot be `None` or empty. The parameter `is_top_domain` only accepts `bool` values. As a result, the function returns a new `Domain` object. :param session: database session :param organization: links the new domain to this organization object :param domain_name: name of the domain :param is_top_domain: set this domain as a top domain :return: a new domain :raises ValueError: raised when `domain_name` is `None` or an empty; when `is_top_domain` does not have a `bool` value. """ if domain_name is None: raise ValueError("'domain_name' cannot be None") if domain_name == '': raise ValueError("'domain_name' cannot be an empty string") if not isinstance(is_top_domain, bool): raise ValueError("'is_top_domain' must have a boolean value") dom = Domain(domain=domain_name, is_top_domain=is_top_domain) dom.organization = organization session.add(dom) return dom
python
def add_domain(session, organization, domain_name, is_top_domain=False): """Add a domain to the session. This function adds a new domain to the session using `domain_name` as its identifier. The new domain will also be linked to the organization object of `organization`. Values assigned to `domain_name` cannot be `None` or empty. The parameter `is_top_domain` only accepts `bool` values. As a result, the function returns a new `Domain` object. :param session: database session :param organization: links the new domain to this organization object :param domain_name: name of the domain :param is_top_domain: set this domain as a top domain :return: a new domain :raises ValueError: raised when `domain_name` is `None` or an empty; when `is_top_domain` does not have a `bool` value. """ if domain_name is None: raise ValueError("'domain_name' cannot be None") if domain_name == '': raise ValueError("'domain_name' cannot be an empty string") if not isinstance(is_top_domain, bool): raise ValueError("'is_top_domain' must have a boolean value") dom = Domain(domain=domain_name, is_top_domain=is_top_domain) dom.organization = organization session.add(dom) return dom
[ "def", "add_domain", "(", "session", ",", "organization", ",", "domain_name", ",", "is_top_domain", "=", "False", ")", ":", "if", "domain_name", "is", "None", ":", "raise", "ValueError", "(", "\"'domain_name' cannot be None\"", ")", "if", "domain_name", "==", "'...
Add a domain to the session. This function adds a new domain to the session using `domain_name` as its identifier. The new domain will also be linked to the organization object of `organization`. Values assigned to `domain_name` cannot be `None` or empty. The parameter `is_top_domain` only accepts `bool` values. As a result, the function returns a new `Domain` object. :param session: database session :param organization: links the new domain to this organization object :param domain_name: name of the domain :param is_top_domain: set this domain as a top domain :return: a new domain :raises ValueError: raised when `domain_name` is `None` or an empty; when `is_top_domain` does not have a `bool` value.
[ "Add", "a", "domain", "to", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L297-L331
train
25,563
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
delete_enrollment
def delete_enrollment(session, enrollment): """Remove an enrollment from the session. This function removes from the session the given enrollment. :param session: database session :param enrollment: enrollment to remove """ uidentity = enrollment.uidentity uidentity.last_modified = datetime.datetime.utcnow() session.delete(enrollment) session.flush()
python
def delete_enrollment(session, enrollment): """Remove an enrollment from the session. This function removes from the session the given enrollment. :param session: database session :param enrollment: enrollment to remove """ uidentity = enrollment.uidentity uidentity.last_modified = datetime.datetime.utcnow() session.delete(enrollment) session.flush()
[ "def", "delete_enrollment", "(", "session", ",", "enrollment", ")", ":", "uidentity", "=", "enrollment", ".", "uidentity", "uidentity", ".", "last_modified", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "session", ".", "delete", "(", "enrollment"...
Remove an enrollment from the session. This function removes from the session the given enrollment. :param session: database session :param enrollment: enrollment to remove
[ "Remove", "an", "enrollment", "from", "the", "session", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L453-L465
train
25,564
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
move_enrollment
def move_enrollment(session, enrollment, uidentity): """Move an enrollment to a unique identity. Shifts `enrollment` to the unique identity given in `uidentity`. The function returns whether the operation was executed successfully. When `uidentity` is the unique identity currently related to `enrollment`, this operation does not have any effect and `False` will be returned as result. :param session: database session :param enrollment: enrollment to be moved :param uidentity: unique identity where `enrollment` will be moved :return: `True` if the enrollment was moved; `False` in any other case """ if enrollment.uuid == uidentity.uuid: return False old_uidentity = enrollment.uidentity enrollment.uidentity = uidentity last_modified = datetime.datetime.utcnow() old_uidentity.last_modified = last_modified uidentity.last_modified = last_modified session.add(uidentity) session.add(old_uidentity) return True
python
def move_enrollment(session, enrollment, uidentity): """Move an enrollment to a unique identity. Shifts `enrollment` to the unique identity given in `uidentity`. The function returns whether the operation was executed successfully. When `uidentity` is the unique identity currently related to `enrollment`, this operation does not have any effect and `False` will be returned as result. :param session: database session :param enrollment: enrollment to be moved :param uidentity: unique identity where `enrollment` will be moved :return: `True` if the enrollment was moved; `False` in any other case """ if enrollment.uuid == uidentity.uuid: return False old_uidentity = enrollment.uidentity enrollment.uidentity = uidentity last_modified = datetime.datetime.utcnow() old_uidentity.last_modified = last_modified uidentity.last_modified = last_modified session.add(uidentity) session.add(old_uidentity) return True
[ "def", "move_enrollment", "(", "session", ",", "enrollment", ",", "uidentity", ")", ":", "if", "enrollment", ".", "uuid", "==", "uidentity", ".", "uuid", ":", "return", "False", "old_uidentity", "=", "enrollment", ".", "uidentity", "enrollment", ".", "uidentit...
Move an enrollment to a unique identity. Shifts `enrollment` to the unique identity given in `uidentity`. The function returns whether the operation was executed successfully. When `uidentity` is the unique identity currently related to `enrollment`, this operation does not have any effect and `False` will be returned as result. :param session: database session :param enrollment: enrollment to be moved :param uidentity: unique identity where `enrollment` will be moved :return: `True` if the enrollment was moved; `False` in any other case
[ "Move", "an", "enrollment", "to", "a", "unique", "identity", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L590-L622
train
25,565
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
add_to_matching_blacklist
def add_to_matching_blacklist(session, term): """Add term to the matching blacklist. This function adds a `term` to the matching blacklist. The term to add cannot have a `None` or empty value, on this case an `ValueError` will be raised. :param session: database session :param term: term, word or value to blacklist :return: a new entry in the blacklist :raises ValueError: raised when `term` is `None` or an empty string """ if term is None: raise ValueError("'term' to blacklist cannot be None") if term == '': raise ValueError("'term' to blacklist cannot be an empty string") mb = MatchingBlacklist(excluded=term) session.add(mb) return mb
python
def add_to_matching_blacklist(session, term): """Add term to the matching blacklist. This function adds a `term` to the matching blacklist. The term to add cannot have a `None` or empty value, on this case an `ValueError` will be raised. :param session: database session :param term: term, word or value to blacklist :return: a new entry in the blacklist :raises ValueError: raised when `term` is `None` or an empty string """ if term is None: raise ValueError("'term' to blacklist cannot be None") if term == '': raise ValueError("'term' to blacklist cannot be an empty string") mb = MatchingBlacklist(excluded=term) session.add(mb) return mb
[ "def", "add_to_matching_blacklist", "(", "session", ",", "term", ")", ":", "if", "term", "is", "None", ":", "raise", "ValueError", "(", "\"'term' to blacklist cannot be None\"", ")", "if", "term", "==", "''", ":", "raise", "ValueError", "(", "\"'term' to blacklist...
Add term to the matching blacklist. This function adds a `term` to the matching blacklist. The term to add cannot have a `None` or empty value, on this case an `ValueError` will be raised. :param session: database session :param term: term, word or value to blacklist :return: a new entry in the blacklist :raises ValueError: raised when `term` is `None` or an empty string
[ "Add", "term", "to", "the", "matching", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L625-L647
train
25,566
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autogender.py
genderize
def genderize(name, api_token=None): """Fetch gender from genderize.io""" GENDERIZE_API_URL = "https://api.genderize.io/" TOTAL_RETRIES = 10 MAX_RETRIES = 5 SLEEP_TIME = 0.25 STATUS_FORCELIST = [502] params = { 'name': name } if api_token: params['apikey'] = api_token session = requests.Session() retries = urllib3.util.Retry(total=TOTAL_RETRIES, connect=MAX_RETRIES, status=MAX_RETRIES, status_forcelist=STATUS_FORCELIST, backoff_factor=SLEEP_TIME, raise_on_status=True) session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries)) session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries)) r = session.get(GENDERIZE_API_URL, params=params) r.raise_for_status() result = r.json() gender = result['gender'] prob = result.get('probability', None) acc = int(prob * 100) if prob else None return gender, acc
python
def genderize(name, api_token=None): """Fetch gender from genderize.io""" GENDERIZE_API_URL = "https://api.genderize.io/" TOTAL_RETRIES = 10 MAX_RETRIES = 5 SLEEP_TIME = 0.25 STATUS_FORCELIST = [502] params = { 'name': name } if api_token: params['apikey'] = api_token session = requests.Session() retries = urllib3.util.Retry(total=TOTAL_RETRIES, connect=MAX_RETRIES, status=MAX_RETRIES, status_forcelist=STATUS_FORCELIST, backoff_factor=SLEEP_TIME, raise_on_status=True) session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries)) session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries)) r = session.get(GENDERIZE_API_URL, params=params) r.raise_for_status() result = r.json() gender = result['gender'] prob = result.get('probability', None) acc = int(prob * 100) if prob else None return gender, acc
[ "def", "genderize", "(", "name", ",", "api_token", "=", "None", ")", ":", "GENDERIZE_API_URL", "=", "\"https://api.genderize.io/\"", "TOTAL_RETRIES", "=", "10", "MAX_RETRIES", "=", "5", "SLEEP_TIME", "=", "0.25", "STATUS_FORCELIST", "=", "[", "502", "]", "params...
Fetch gender from genderize.io
[ "Fetch", "gender", "from", "genderize", ".", "io" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L149-L186
train
25,567
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autogender.py
AutoGender.run
def run(self, *args): """Autocomplete gender information.""" params = self.parser.parse_args(args) api_token = params.api_token genderize_all = params.genderize_all code = self.autogender(api_token=api_token, genderize_all=genderize_all) return code
python
def run(self, *args): """Autocomplete gender information.""" params = self.parser.parse_args(args) api_token = params.api_token genderize_all = params.genderize_all code = self.autogender(api_token=api_token, genderize_all=genderize_all) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "api_token", "=", "params", ".", "api_token", "genderize_all", "=", "params", ".", "genderize_all", "code", "=", "self", "...
Autocomplete gender information.
[ "Autocomplete", "gender", "information", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L80-L89
train
25,568
chaoss/grimoirelab-sortinghat
sortinghat/cmd/autogender.py
AutoGender.autogender
def autogender(self, api_token=None, genderize_all=False): """Autocomplete gender information of unique identities. Autocomplete unique identities gender using genderize.io API. Only those unique identities without an assigned gender will be updated unless `genderize_all` option is given. """ name_cache = {} no_gender = not genderize_all pattern = re.compile(r"(^\w+)\s\w+") profiles = api.search_profiles(self.db, no_gender=no_gender) for profile in profiles: if not profile.name: continue name = profile.name.strip() m = pattern.match(name) if not m: continue firstname = m.group(1).lower() if firstname in name_cache: gender_data = name_cache[firstname] else: try: gender, acc = genderize(firstname, api_token) except (requests.exceptions.RequestException, requests.exceptions.RetryError) as e: msg = "Skipping '%s' name (%s) due to a connection error. Error: %s" msg = msg % (firstname, profile.uuid, str(e)) self.warning(msg) continue gender_data = { 'gender': gender, 'gender_acc': acc } name_cache[firstname] = gender_data if not gender_data['gender']: continue try: api.edit_profile(self.db, profile.uuid, **gender_data) self.display('autogender.tmpl', uuid=profile.uuid, name=profile.name, gender_data=gender_data) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def autogender(self, api_token=None, genderize_all=False): """Autocomplete gender information of unique identities. Autocomplete unique identities gender using genderize.io API. Only those unique identities without an assigned gender will be updated unless `genderize_all` option is given. """ name_cache = {} no_gender = not genderize_all pattern = re.compile(r"(^\w+)\s\w+") profiles = api.search_profiles(self.db, no_gender=no_gender) for profile in profiles: if not profile.name: continue name = profile.name.strip() m = pattern.match(name) if not m: continue firstname = m.group(1).lower() if firstname in name_cache: gender_data = name_cache[firstname] else: try: gender, acc = genderize(firstname, api_token) except (requests.exceptions.RequestException, requests.exceptions.RetryError) as e: msg = "Skipping '%s' name (%s) due to a connection error. Error: %s" msg = msg % (firstname, profile.uuid, str(e)) self.warning(msg) continue gender_data = { 'gender': gender, 'gender_acc': acc } name_cache[firstname] = gender_data if not gender_data['gender']: continue try: api.edit_profile(self.db, profile.uuid, **gender_data) self.display('autogender.tmpl', uuid=profile.uuid, name=profile.name, gender_data=gender_data) except (NotFoundError, InvalidValueError) as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "autogender", "(", "self", ",", "api_token", "=", "None", ",", "genderize_all", "=", "False", ")", ":", "name_cache", "=", "{", "}", "no_gender", "=", "not", "genderize_all", "pattern", "=", "re", ".", "compile", "(", "r\"(^\\w+)\\s\\w+\"", ")", "pr...
Autocomplete gender information of unique identities. Autocomplete unique identities gender using genderize.io API. Only those unique identities without an assigned gender will be updated unless `genderize_all` option is given.
[ "Autocomplete", "gender", "information", "of", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L91-L146
train
25,569
chaoss/grimoirelab-sortinghat
sortinghat/parsing/mozilla.py
MozilliansParser.__parse_identities
def __parse_identities(self, json): """Parse identities using Mozillians format. The Mozillians identities format is a JSON document under the "results" key. The document should follow the next schema: { "results" : [ { "_url": "https://example.com/api/v2/users/1/", "alternate_emails": [{ "email": "jsmith@example.net", "privacy": "Public" }], "email": { "privacy": "Public", "value": "jsmith@example.com" }, "full_name": { "privacy": "Public", "value": "John Smith" }, "ircname": { "privacy": "Public", "value": "jsmith" }, "url": "https://mozillians.org/en-US/u/2apreety18/", "username": "2apreety18" } ] } :parse data: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for mozillian in json['results']: name = self.__encode(mozillian['full_name']['value']) email = self.__encode(mozillian['email']['value']) username = self.__encode(mozillian['username']) uuid = username uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) # Alternate emails for alt_email in mozillian['alternate_emails']: alt_email = self.__encode(alt_email['email']) if alt_email == email: continue identity = Identity(name=name, email=alt_email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) # IRC account ircname = self.__encode(mozillian['ircname']['value']) if ircname and ircname != username: identity = Identity(name=None, email=None, username=ircname, source=self.source, uuid=uuid) uid.identities.append(identity) # Mozilla affiliation affiliation = mozillian['date_mozillian'] rol = self.__parse_mozillian_affiliation(affiliation) uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_identities(self, json): """Parse identities using Mozillians format. The Mozillians identities format is a JSON document under the "results" key. The document should follow the next schema: { "results" : [ { "_url": "https://example.com/api/v2/users/1/", "alternate_emails": [{ "email": "jsmith@example.net", "privacy": "Public" }], "email": { "privacy": "Public", "value": "jsmith@example.com" }, "full_name": { "privacy": "Public", "value": "John Smith" }, "ircname": { "privacy": "Public", "value": "jsmith" }, "url": "https://mozillians.org/en-US/u/2apreety18/", "username": "2apreety18" } ] } :parse data: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for mozillian in json['results']: name = self.__encode(mozillian['full_name']['value']) email = self.__encode(mozillian['email']['value']) username = self.__encode(mozillian['username']) uuid = username uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) # Alternate emails for alt_email in mozillian['alternate_emails']: alt_email = self.__encode(alt_email['email']) if alt_email == email: continue identity = Identity(name=name, email=alt_email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) # IRC account ircname = self.__encode(mozillian['ircname']['value']) if ircname and ircname != username: identity = Identity(name=None, email=None, username=ircname, source=self.source, uuid=uuid) uid.identities.append(identity) # Mozilla affiliation affiliation = mozillian['date_mozillian'] rol = self.__parse_mozillian_affiliation(affiliation) uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_identities", "(", "self", ",", "json", ")", ":", "try", ":", "for", "mozillian", "in", "json", "[", "'results'", "]", ":", "name", "=", "self", ".", "__encode", "(", "mozillian", "[", "'full_name'", "]", "[", "'value'", "]", ")", "email...
Parse identities using Mozillians format. The Mozillians identities format is a JSON document under the "results" key. The document should follow the next schema: { "results" : [ { "_url": "https://example.com/api/v2/users/1/", "alternate_emails": [{ "email": "jsmith@example.net", "privacy": "Public" }], "email": { "privacy": "Public", "value": "jsmith@example.com" }, "full_name": { "privacy": "Public", "value": "John Smith" }, "ircname": { "privacy": "Public", "value": "jsmith" }, "url": "https://mozillians.org/en-US/u/2apreety18/", "username": "2apreety18" } ] } :parse data: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "identities", "using", "Mozillians", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mozilla.py#L84-L160
train
25,570
chaoss/grimoirelab-sortinghat
sortinghat/cmd/organizations.py
Organizations.run
def run(self, *args): """List, add or delete organizations and domains from the registry. By default, it prints the list of organizations available on the registry. """ params = self.parser.parse_args(args) organization = params.organization domain = params.domain is_top_domain = params.top_domain overwrite = params.overwrite if params.add: code = self.add(organization, domain, is_top_domain, overwrite) elif params.delete: code = self.delete(organization, domain) else: term = organization code = self.registry(term) return code
python
def run(self, *args): """List, add or delete organizations and domains from the registry. By default, it prints the list of organizations available on the registry. """ params = self.parser.parse_args(args) organization = params.organization domain = params.domain is_top_domain = params.top_domain overwrite = params.overwrite if params.add: code = self.add(organization, domain, is_top_domain, overwrite) elif params.delete: code = self.delete(organization, domain) else: term = organization code = self.registry(term) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "organization", "=", "params", ".", "organization", "domain", "=", "params", ".", "domain", "is_top_domain", "=", "params", ...
List, add or delete organizations and domains from the registry. By default, it prints the list of organizations available on the registry.
[ "List", "add", "or", "delete", "organizations", "and", "domains", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L110-L131
train
25,571
chaoss/grimoirelab-sortinghat
sortinghat/cmd/organizations.py
Organizations.add
def add(self, organization, domain=None, is_top_domain=False, overwrite=False): """Add organizations and domains to the registry. This method adds the given 'organization' or 'domain' to the registry, but not both at the same time. When 'organization' is the only parameter given, it will be added to the registry. When 'domain' parameter is also given, the function will assign it to 'organization'. In this case, 'organization' must exists in the registry prior adding the domain. A domain can only be assigned to one company. If the given domain is already in the registry, the method will fail. Set 'overwrite' to 'True' to create the new relationship. In this case, previous relationships will be removed. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Take into account when 'overwrite' is set it will update 'is_top_domain' flag too. :param organization: name of the organization to add :param domain: domain to add to the registry :param is_top_domain: set the domain as a top domain :param overwrite: force to reassign the domain to the given company """ # Empty or None values for organizations are not allowed if not organization: return CMD_SUCCESS if not domain: try: api.add_organization(self.db, organization) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because organization cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "organization '%s' already exists in the registry" % organization self.error(msg) return e.code else: try: api.add_domain(self.db, organization, domain, is_top_domain=is_top_domain, overwrite=overwrite) except InvalidValueError as e: # Same as above, domains cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "domain '%s' already exists in the registry" % domain self.error(msg) return e.code except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def add(self, organization, domain=None, is_top_domain=False, overwrite=False): """Add organizations and domains to the registry. This method adds the given 'organization' or 'domain' to the registry, but not both at the same time. When 'organization' is the only parameter given, it will be added to the registry. When 'domain' parameter is also given, the function will assign it to 'organization'. In this case, 'organization' must exists in the registry prior adding the domain. A domain can only be assigned to one company. If the given domain is already in the registry, the method will fail. Set 'overwrite' to 'True' to create the new relationship. In this case, previous relationships will be removed. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Take into account when 'overwrite' is set it will update 'is_top_domain' flag too. :param organization: name of the organization to add :param domain: domain to add to the registry :param is_top_domain: set the domain as a top domain :param overwrite: force to reassign the domain to the given company """ # Empty or None values for organizations are not allowed if not organization: return CMD_SUCCESS if not domain: try: api.add_organization(self.db, organization) except InvalidValueError as e: # If the code reaches here, something really wrong has happened # because organization cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "organization '%s' already exists in the registry" % organization self.error(msg) return e.code else: try: api.add_domain(self.db, organization, domain, is_top_domain=is_top_domain, overwrite=overwrite) except InvalidValueError as e: # Same as above, domains cannot be None or empty raise RuntimeError(str(e)) except AlreadyExistsError as e: msg = "domain '%s' already exists in the registry" % domain self.error(msg) return e.code except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "add", "(", "self", ",", "organization", ",", "domain", "=", "None", ",", "is_top_domain", "=", "False", ",", "overwrite", "=", "False", ")", ":", "# Empty or None values for organizations are not allowed", "if", "not", "organization", ":", "return", "CMD_S...
Add organizations and domains to the registry. This method adds the given 'organization' or 'domain' to the registry, but not both at the same time. When 'organization' is the only parameter given, it will be added to the registry. When 'domain' parameter is also given, the function will assign it to 'organization'. In this case, 'organization' must exists in the registry prior adding the domain. A domain can only be assigned to one company. If the given domain is already in the registry, the method will fail. Set 'overwrite' to 'True' to create the new relationship. In this case, previous relationships will be removed. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Take into account when 'overwrite' is set it will update 'is_top_domain' flag too. :param organization: name of the organization to add :param domain: domain to add to the registry :param is_top_domain: set the domain as a top domain :param overwrite: force to reassign the domain to the given company
[ "Add", "organizations", "and", "domains", "to", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L133-L189
train
25,572
chaoss/grimoirelab-sortinghat
sortinghat/cmd/organizations.py
Organizations.delete
def delete(self, organization, domain=None): """Remove organizations and domains from the registry. The method removes the given 'organization' or 'domain' from the registry, but not both at the same time. When 'organization' is the only parameter given, it will be removed from the registry, including those domains related to it. When 'domain' parameter is also given, only the domain will be deleted. 'organization' must exists in the registry prior removing the domain. :param organization: name of the organization to remove :param domain: domain to remove from the registry """ if not organization: return CMD_SUCCESS if not domain: try: api.delete_organization(self.db, organization) except NotFoundError as e: self.error(str(e)) return e.code else: try: api.delete_domain(self.db, organization, domain) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def delete(self, organization, domain=None): """Remove organizations and domains from the registry. The method removes the given 'organization' or 'domain' from the registry, but not both at the same time. When 'organization' is the only parameter given, it will be removed from the registry, including those domains related to it. When 'domain' parameter is also given, only the domain will be deleted. 'organization' must exists in the registry prior removing the domain. :param organization: name of the organization to remove :param domain: domain to remove from the registry """ if not organization: return CMD_SUCCESS if not domain: try: api.delete_organization(self.db, organization) except NotFoundError as e: self.error(str(e)) return e.code else: try: api.delete_domain(self.db, organization, domain) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "delete", "(", "self", ",", "organization", ",", "domain", "=", "None", ")", ":", "if", "not", "organization", ":", "return", "CMD_SUCCESS", "if", "not", "domain", ":", "try", ":", "api", ".", "delete_organization", "(", "self", ".", "db", ",", ...
Remove organizations and domains from the registry. The method removes the given 'organization' or 'domain' from the registry, but not both at the same time. When 'organization' is the only parameter given, it will be removed from the registry, including those domains related to it. When 'domain' parameter is also given, only the domain will be deleted. 'organization' must exists in the registry prior removing the domain. :param organization: name of the organization to remove :param domain: domain to remove from the registry
[ "Remove", "organizations", "and", "domains", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L191-L221
train
25,573
chaoss/grimoirelab-sortinghat
sortinghat/cmd/organizations.py
Organizations.registry
def registry(self, term=None): """List organizations and domains. When no term is given, the method will list the organizations existing in the registry. If 'term' is set, the method will list only those organizations and domains that match with that term. :param term: term to match """ try: orgs = api.registry(self.db, term) self.display('organizations.tmpl', organizations=orgs) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
python
def registry(self, term=None): """List organizations and domains. When no term is given, the method will list the organizations existing in the registry. If 'term' is set, the method will list only those organizations and domains that match with that term. :param term: term to match """ try: orgs = api.registry(self.db, term) self.display('organizations.tmpl', organizations=orgs) except NotFoundError as e: self.error(str(e)) return e.code return CMD_SUCCESS
[ "def", "registry", "(", "self", ",", "term", "=", "None", ")", ":", "try", ":", "orgs", "=", "api", ".", "registry", "(", "self", ".", "db", ",", "term", ")", "self", ".", "display", "(", "'organizations.tmpl'", ",", "organizations", "=", "orgs", ")"...
List organizations and domains. When no term is given, the method will list the organizations existing in the registry. If 'term' is set, the method will list only those organizations and domains that match with that term. :param term: term to match
[ "List", "organizations", "and", "domains", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L223-L239
train
25,574
chaoss/grimoirelab-sortinghat
sortinghat/parser.py
create_organizations_parser
def create_organizations_parser(stream): """Create an organizations parser for the given stream. Factory function that creates an organizations parser for the given stream. The stream is only used to guess the type of the required parser. :param stream: stream used to guess the type of the parser :returns: an organizations parser :raise InvalidFormatError: raised when no one of the available parsers can parse the given stream """ import sortinghat.parsing as parsing # First, try with default parser for p in parsing.SORTINGHAT_ORGS_PARSERS: klass = parsing.SORTINGHAT_ORGS_PARSERS[p] parser = klass() if parser.check(stream): return parser raise InvalidFormatError(cause=INVALID_FORMAT_MSG)
python
def create_organizations_parser(stream): """Create an organizations parser for the given stream. Factory function that creates an organizations parser for the given stream. The stream is only used to guess the type of the required parser. :param stream: stream used to guess the type of the parser :returns: an organizations parser :raise InvalidFormatError: raised when no one of the available parsers can parse the given stream """ import sortinghat.parsing as parsing # First, try with default parser for p in parsing.SORTINGHAT_ORGS_PARSERS: klass = parsing.SORTINGHAT_ORGS_PARSERS[p] parser = klass() if parser.check(stream): return parser raise InvalidFormatError(cause=INVALID_FORMAT_MSG)
[ "def", "create_organizations_parser", "(", "stream", ")", ":", "import", "sortinghat", ".", "parsing", "as", "parsing", "# First, try with default parser", "for", "p", "in", "parsing", ".", "SORTINGHAT_ORGS_PARSERS", ":", "klass", "=", "parsing", ".", "SORTINGHAT_ORGS...
Create an organizations parser for the given stream. Factory function that creates an organizations parser for the given stream. The stream is only used to guess the type of the required parser. :param stream: stream used to guess the type of the parser :returns: an organizations parser :raise InvalidFormatError: raised when no one of the available parsers can parse the given stream
[ "Create", "an", "organizations", "parser", "for", "the", "given", "stream", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parser.py#L44-L68
train
25,575
chaoss/grimoirelab-sortinghat
sortinghat/cmd/enroll.py
Enroll.enroll
def enroll(self, uuid, organization, from_date=MIN_PERIOD_DATE, to_date=MAX_PERIOD_DATE, merge=False): """Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before creating the new enrollment. The period of the enrollment can be given with the parameters <from_date> and <to_date>, where "from_date <= to_date". Default values for these dates are '1900-01-01' and '2100-01-01'. When "merge" parameter is set to True, those overlapped enrollments related to <uuid> and <organization> found on the registry will be merged. The given enrollment will be also merged. :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :param merge: merge overlapped enrollments; by default, it is set to False """ # Empty or None values for uuid and organizations are not allowed if not uuid or not organization: return CMD_SUCCESS try: api.add_enrollment(self.db, uuid, organization, from_date, to_date) code = CMD_SUCCESS except (NotFoundError, InvalidValueError) as e: self.error(str(e)) code = e.code except AlreadyExistsError as e: if not merge: msg_data = { 'uuid': uuid, 'org': organization, 'from_dt': str(from_date), 'to_dt': str(to_date) } msg = "enrollment for '%(uuid)s' at '%(org)s' (from: %(from_dt)s, to: %(to_dt)s) already exists in the registry" msg = msg % msg_data self.error(msg) code = e.code if not merge: return code try: api.merge_enrollments(self.db, uuid, organization) except (NotFoundError, InvalidValueError) as e: # These exceptions were checked above. If any of these raises # is due to something really wrong has happened raise RuntimeError(str(e)) return CMD_SUCCESS
python
def enroll(self, uuid, organization, from_date=MIN_PERIOD_DATE, to_date=MAX_PERIOD_DATE, merge=False): """Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before creating the new enrollment. The period of the enrollment can be given with the parameters <from_date> and <to_date>, where "from_date <= to_date". Default values for these dates are '1900-01-01' and '2100-01-01'. When "merge" parameter is set to True, those overlapped enrollments related to <uuid> and <organization> found on the registry will be merged. The given enrollment will be also merged. :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :param merge: merge overlapped enrollments; by default, it is set to False """ # Empty or None values for uuid and organizations are not allowed if not uuid or not organization: return CMD_SUCCESS try: api.add_enrollment(self.db, uuid, organization, from_date, to_date) code = CMD_SUCCESS except (NotFoundError, InvalidValueError) as e: self.error(str(e)) code = e.code except AlreadyExistsError as e: if not merge: msg_data = { 'uuid': uuid, 'org': organization, 'from_dt': str(from_date), 'to_dt': str(to_date) } msg = "enrollment for '%(uuid)s' at '%(org)s' (from: %(from_dt)s, to: %(to_dt)s) already exists in the registry" msg = msg % msg_data self.error(msg) code = e.code if not merge: return code try: api.merge_enrollments(self.db, uuid, organization) except (NotFoundError, InvalidValueError) as e: # These exceptions were checked above. If any of these raises # is due to something really wrong has happened raise RuntimeError(str(e)) return CMD_SUCCESS
[ "def", "enroll", "(", "self", ",", "uuid", ",", "organization", ",", "from_date", "=", "MIN_PERIOD_DATE", ",", "to_date", "=", "MAX_PERIOD_DATE", ",", "merge", "=", "False", ")", ":", "# Empty or None values for uuid and organizations are not allowed", "if", "not", ...
Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before creating the new enrollment. The period of the enrollment can be given with the parameters <from_date> and <to_date>, where "from_date <= to_date". Default values for these dates are '1900-01-01' and '2100-01-01'. When "merge" parameter is set to True, those overlapped enrollments related to <uuid> and <organization> found on the registry will be merged. The given enrollment will be also merged. :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :param merge: merge overlapped enrollments; by default, it is set to False
[ "Enroll", "a", "unique", "identity", "in", "an", "organization", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/enroll.py#L110-L165
train
25,576
chaoss/grimoirelab-sortinghat
sortinghat/parsing/eclipse.py
EclipseParser.__parse_identities
def __parse_identities(self, json): """Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { 'affiliations': { '1': { 'active': '2001-01-01', 'inactive': null, 'name': 'Organization 1' } }, 'email': [ 'john@example.com' ], 'first': 'John', 'id': 'john', 'last': 'Doe', 'primary': 'john.doe@example.com' } } } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for committer in json['committers'].values(): name = self.__encode(committer['first'] + ' ' + committer['last']) email = self.__encode(committer['primary']) username = self.__encode(committer['id']) uuid = username uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) if 'email' in committer: for alt_email in committer['email']: alt_email = self.__encode(alt_email) if alt_email == email: continue identity = Identity(name=name, email=alt_email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) if 'affiliations' in committer: enrollments = self.__parse_affiliations_json(committer['affiliations'], uuid) for rol in enrollments: uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_identities(self, json): """Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { 'affiliations': { '1': { 'active': '2001-01-01', 'inactive': null, 'name': 'Organization 1' } }, 'email': [ 'john@example.com' ], 'first': 'John', 'id': 'john', 'last': 'Doe', 'primary': 'john.doe@example.com' } } } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid. """ try: for committer in json['committers'].values(): name = self.__encode(committer['first'] + ' ' + committer['last']) email = self.__encode(committer['primary']) username = self.__encode(committer['id']) uuid = username uid = UniqueIdentity(uuid=uuid) identity = Identity(name=name, email=email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) if 'email' in committer: for alt_email in committer['email']: alt_email = self.__encode(alt_email) if alt_email == email: continue identity = Identity(name=name, email=alt_email, username=username, source=self.source, uuid=uuid) uid.identities.append(identity) if 'affiliations' in committer: enrollments = self.__parse_affiliations_json(committer['affiliations'], uuid) for rol in enrollments: uid.enrollments.append(rol) self._identities[uuid] = uid except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_identities", "(", "self", ",", "json", ")", ":", "try", ":", "for", "committer", "in", "json", "[", "'committers'", "]", ".", "values", "(", ")", ":", "name", "=", "self", ".", "__encode", "(", "committer", "[", "'first'", "]", "+", "...
Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { 'affiliations': { '1': { 'active': '2001-01-01', 'inactive': null, 'name': 'Organization 1' } }, 'email': [ 'john@example.com' ], 'first': 'John', 'id': 'john', 'last': 'Doe', 'primary': 'john.doe@example.com' } } } :parse json: JSON object to parse :raise InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "identities", "using", "Eclipse", "format", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L83-L147
train
25,577
chaoss/grimoirelab-sortinghat
sortinghat/parsing/eclipse.py
EclipseParser.__parse_organizations
def __parse_organizations(self, json): """Parse Eclipse organizations. The Eclipse organizations format is a JSON document stored under the "organizations" key. The next JSON shows the structure of the document: { 'organizations' : { '1': { 'active': '2001-01-01 18:00:00', 'id': '1', 'image' : 'http://example.com/image/1', 'inactive' : null, 'isMember': '1', 'name': 'Organization 1', 'url': 'http://example.com/org/1' }, '2': { 'active': '2015-12-31 23:59:59', 'id': '1', 'image' : 'http://example.com/image/2', 'inactive': '2008-01-01 18:00:00', 'isMember': '1', 'name': 'Organization 2', 'url': 'http://example.com/org/2' } } } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid. """ try: for organization in json['organizations'].values(): name = self.__encode(organization['name']) try: active = str_to_datetime(organization['active']) inactive = str_to_datetime(organization['inactive']) # Ignore organization if not active and not inactive: continue if not active: active = MIN_PERIOD_DATE if not inactive: inactive = MAX_PERIOD_DATE except InvalidDateError as e: raise InvalidFormatError(cause=str(e)) org = self._organizations.get(name, None) if not org: org = Organization(name=name) # Store metadata valid for identities parsing org.active = active org.inactive = inactive self._organizations[name] = org except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
python
def __parse_organizations(self, json): """Parse Eclipse organizations. The Eclipse organizations format is a JSON document stored under the "organizations" key. The next JSON shows the structure of the document: { 'organizations' : { '1': { 'active': '2001-01-01 18:00:00', 'id': '1', 'image' : 'http://example.com/image/1', 'inactive' : null, 'isMember': '1', 'name': 'Organization 1', 'url': 'http://example.com/org/1' }, '2': { 'active': '2015-12-31 23:59:59', 'id': '1', 'image' : 'http://example.com/image/2', 'inactive': '2008-01-01 18:00:00', 'isMember': '1', 'name': 'Organization 2', 'url': 'http://example.com/org/2' } } } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid. """ try: for organization in json['organizations'].values(): name = self.__encode(organization['name']) try: active = str_to_datetime(organization['active']) inactive = str_to_datetime(organization['inactive']) # Ignore organization if not active and not inactive: continue if not active: active = MIN_PERIOD_DATE if not inactive: inactive = MAX_PERIOD_DATE except InvalidDateError as e: raise InvalidFormatError(cause=str(e)) org = self._organizations.get(name, None) if not org: org = Organization(name=name) # Store metadata valid for identities parsing org.active = active org.inactive = inactive self._organizations[name] = org except KeyError as e: msg = "invalid json format. Attribute %s not found" % e.args raise InvalidFormatError(cause=msg)
[ "def", "__parse_organizations", "(", "self", ",", "json", ")", ":", "try", ":", "for", "organization", "in", "json", "[", "'organizations'", "]", ".", "values", "(", ")", ":", "name", "=", "self", ".", "__encode", "(", "organization", "[", "'name'", "]",...
Parse Eclipse organizations. The Eclipse organizations format is a JSON document stored under the "organizations" key. The next JSON shows the structure of the document: { 'organizations' : { '1': { 'active': '2001-01-01 18:00:00', 'id': '1', 'image' : 'http://example.com/image/1', 'inactive' : null, 'isMember': '1', 'name': 'Organization 1', 'url': 'http://example.com/org/1' }, '2': { 'active': '2015-12-31 23:59:59', 'id': '1', 'image' : 'http://example.com/image/2', 'inactive': '2008-01-01 18:00:00', 'isMember': '1', 'name': 'Organization 2', 'url': 'http://example.com/org/2' } } } :param json: JSON object to parse :raises InvalidFormatError: raised when the format of the JSON is not valid.
[ "Parse", "Eclipse", "organizations", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L149-L215
train
25,578
chaoss/grimoirelab-sortinghat
sortinghat/parsing/eclipse.py
EclipseParser.__parse_affiliations_json
def __parse_affiliations_json(self, affiliations, uuid): """Parse identity's affiliations from a json dict""" enrollments = [] for affiliation in affiliations.values(): name = self.__encode(affiliation['name']) try: start_date = str_to_datetime(affiliation['active']) end_date = str_to_datetime(affiliation['inactive']) except InvalidDateError as e: raise InvalidFormatError(cause=str(e)) # Ignore affiliation if not start_date and not end_date: continue if not start_date: start_date = MIN_PERIOD_DATE if not end_date: end_date = MAX_PERIOD_DATE org = self._organizations.get(name, None) # Set enrolllment period according to organization data if org: start_date = org.active if start_date < org.active else start_date end_date = org.inactive if end_date > org.inactive else end_date if not org: org = Organization(name=name) org.active = MIN_PERIOD_DATE org.inactive = MAX_PERIOD_DATE enrollment = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(enrollment) return enrollments
python
def __parse_affiliations_json(self, affiliations, uuid): """Parse identity's affiliations from a json dict""" enrollments = [] for affiliation in affiliations.values(): name = self.__encode(affiliation['name']) try: start_date = str_to_datetime(affiliation['active']) end_date = str_to_datetime(affiliation['inactive']) except InvalidDateError as e: raise InvalidFormatError(cause=str(e)) # Ignore affiliation if not start_date and not end_date: continue if not start_date: start_date = MIN_PERIOD_DATE if not end_date: end_date = MAX_PERIOD_DATE org = self._organizations.get(name, None) # Set enrolllment period according to organization data if org: start_date = org.active if start_date < org.active else start_date end_date = org.inactive if end_date > org.inactive else end_date if not org: org = Organization(name=name) org.active = MIN_PERIOD_DATE org.inactive = MAX_PERIOD_DATE enrollment = Enrollment(start=start_date, end=end_date, organization=org) enrollments.append(enrollment) return enrollments
[ "def", "__parse_affiliations_json", "(", "self", ",", "affiliations", ",", "uuid", ")", ":", "enrollments", "=", "[", "]", "for", "affiliation", "in", "affiliations", ".", "values", "(", ")", ":", "name", "=", "self", ".", "__encode", "(", "affiliation", "...
Parse identity's affiliations from a json dict
[ "Parse", "identity", "s", "affiliations", "from", "a", "json", "dict" ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L217-L256
train
25,579
chaoss/grimoirelab-sortinghat
sortinghat/api.py
add_unique_identity
def add_unique_identity(db, uuid): """Add a unique identity to the registry. This function adds a unique identity to the registry. First, it checks if the unique identifier (uuid) used to create the identity is already on the registry. When it is not found, a new unique identity is created. Otherwise, it raises a 'AlreadyExistError' exception. :param db: database manager :param uuid: unique identifier for the identity :raises InvalidValueError: when uuid is None or an empty string :raises AlreadyExistsError: when the identifier already exists in the registry. """ with db.connect() as session: try: add_unique_identity_db(session, uuid) except ValueError as e: raise InvalidValueError(e)
python
def add_unique_identity(db, uuid): """Add a unique identity to the registry. This function adds a unique identity to the registry. First, it checks if the unique identifier (uuid) used to create the identity is already on the registry. When it is not found, a new unique identity is created. Otherwise, it raises a 'AlreadyExistError' exception. :param db: database manager :param uuid: unique identifier for the identity :raises InvalidValueError: when uuid is None or an empty string :raises AlreadyExistsError: when the identifier already exists in the registry. """ with db.connect() as session: try: add_unique_identity_db(session, uuid) except ValueError as e: raise InvalidValueError(e)
[ "def", "add_unique_identity", "(", "db", ",", "uuid", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "try", ":", "add_unique_identity_db", "(", "session", ",", "uuid", ")", "except", "ValueError", "as", "e", ":", "raise", "Invali...
Add a unique identity to the registry. This function adds a unique identity to the registry. First, it checks if the unique identifier (uuid) used to create the identity is already on the registry. When it is not found, a new unique identity is created. Otherwise, it raises a 'AlreadyExistError' exception. :param db: database manager :param uuid: unique identifier for the identity :raises InvalidValueError: when uuid is None or an empty string :raises AlreadyExistsError: when the identifier already exists in the registry.
[ "Add", "a", "unique", "identity", "to", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L54-L73
train
25,580
chaoss/grimoirelab-sortinghat
sortinghat/api.py
add_organization
def add_organization(db, organization): """Add an organization to the registry. This function adds an organization to the registry. It checks first whether the organization is already on the registry. When it is not found, the new organization is added. Otherwise, it raises a 'AlreadyExistsError' exception to notify that the organization already exists. :param db: database manager :param organization: name of the organization :raises InvalidValueError: raised when organization is None or an empty string :raises AlreadyExistsError: raised when the organization already exists in the registry. """ with db.connect() as session: try: add_organization_db(session, organization) except ValueError as e: raise InvalidValueError(e)
python
def add_organization(db, organization): """Add an organization to the registry. This function adds an organization to the registry. It checks first whether the organization is already on the registry. When it is not found, the new organization is added. Otherwise, it raises a 'AlreadyExistsError' exception to notify that the organization already exists. :param db: database manager :param organization: name of the organization :raises InvalidValueError: raised when organization is None or an empty string :raises AlreadyExistsError: raised when the organization already exists in the registry. """ with db.connect() as session: try: add_organization_db(session, organization) except ValueError as e: raise InvalidValueError(e)
[ "def", "add_organization", "(", "db", ",", "organization", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "try", ":", "add_organization_db", "(", "session", ",", "organization", ")", "except", "ValueError", "as", "e", ":", "raise",...
Add an organization to the registry. This function adds an organization to the registry. It checks first whether the organization is already on the registry. When it is not found, the new organization is added. Otherwise, it raises a 'AlreadyExistsError' exception to notify that the organization already exists. :param db: database manager :param organization: name of the organization :raises InvalidValueError: raised when organization is None or an empty string :raises AlreadyExistsError: raised when the organization already exists in the registry.
[ "Add", "an", "organization", "to", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L140-L160
train
25,581
chaoss/grimoirelab-sortinghat
sortinghat/api.py
add_domain
def add_domain(db, organization, domain, is_top_domain=False, overwrite=False): """Add a domain to the registry. This function adds a new domain to the given organization. The organization must exists on the registry prior to insert the new domain. Otherwise, it will raise a 'NotFoundError' exception. Moreover, if the given domain is already in the registry an 'AlreadyExistsError' exception will be raised. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Remember that a domain can only be assigned to one (and only one) organization. When the given domain already exist on the registry, you can use 'overwrite' parameter to update its information. For instance, shift the domain to another organization or to update the top domain flag. Take into account that both fields will be updated at the same time. :param db: database manager :param organization: name of the organization :param domain: domain to add to the registry :param is_top_domain: set this domain as a top domain :param overwrite: force to reassign the domain to the given organization and to update top domain field :raises InvalidValueError: raised when domain is None or an empty string or is_top_domain does not have a boolean value :raises NotFoundError: raised when the given organization is not found in the registry :raises AlreadyExistsError: raised when the domain already exists in the registry """ with db.connect() as session: org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) dom = find_domain(session, domain) if dom and not overwrite: raise AlreadyExistsError(entity='Domain', eid=dom.domain) elif dom: delete_domain_db(session, dom) try: add_domain_db(session, org, domain, is_top_domain=is_top_domain) except ValueError as e: raise InvalidValueError(e)
python
def add_domain(db, organization, domain, is_top_domain=False, overwrite=False): """Add a domain to the registry. This function adds a new domain to the given organization. The organization must exists on the registry prior to insert the new domain. Otherwise, it will raise a 'NotFoundError' exception. Moreover, if the given domain is already in the registry an 'AlreadyExistsError' exception will be raised. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Remember that a domain can only be assigned to one (and only one) organization. When the given domain already exist on the registry, you can use 'overwrite' parameter to update its information. For instance, shift the domain to another organization or to update the top domain flag. Take into account that both fields will be updated at the same time. :param db: database manager :param organization: name of the organization :param domain: domain to add to the registry :param is_top_domain: set this domain as a top domain :param overwrite: force to reassign the domain to the given organization and to update top domain field :raises InvalidValueError: raised when domain is None or an empty string or is_top_domain does not have a boolean value :raises NotFoundError: raised when the given organization is not found in the registry :raises AlreadyExistsError: raised when the domain already exists in the registry """ with db.connect() as session: org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) dom = find_domain(session, domain) if dom and not overwrite: raise AlreadyExistsError(entity='Domain', eid=dom.domain) elif dom: delete_domain_db(session, dom) try: add_domain_db(session, org, domain, is_top_domain=is_top_domain) except ValueError as e: raise InvalidValueError(e)
[ "def", "add_domain", "(", "db", ",", "organization", ",", "domain", ",", "is_top_domain", "=", "False", ",", "overwrite", "=", "False", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "org", "=", "find_organization", "(", "session...
Add a domain to the registry. This function adds a new domain to the given organization. The organization must exists on the registry prior to insert the new domain. Otherwise, it will raise a 'NotFoundError' exception. Moreover, if the given domain is already in the registry an 'AlreadyExistsError' exception will be raised. The new domain can be also set as a top domain. That is useful to avoid the insertion of sub-domains that belong to the same organization (i.e eu.example.com, us.example.com). Remember that a domain can only be assigned to one (and only one) organization. When the given domain already exist on the registry, you can use 'overwrite' parameter to update its information. For instance, shift the domain to another organization or to update the top domain flag. Take into account that both fields will be updated at the same time. :param db: database manager :param organization: name of the organization :param domain: domain to add to the registry :param is_top_domain: set this domain as a top domain :param overwrite: force to reassign the domain to the given organization and to update top domain field :raises InvalidValueError: raised when domain is None or an empty string or is_top_domain does not have a boolean value :raises NotFoundError: raised when the given organization is not found in the registry :raises AlreadyExistsError: raised when the domain already exists in the registry
[ "Add", "a", "domain", "to", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L163-L215
train
25,582
chaoss/grimoirelab-sortinghat
sortinghat/api.py
add_to_matching_blacklist
def add_to_matching_blacklist(db, entity): """Add entity to the matching blacklist. This function adds an 'entity' o term to the matching blacklist. The term to add cannot have a None or empty value, in this case a InvalidValueError will be raised. If the given 'entity' exists in the registry, the function will raise an AlreadyExistsError exception. :param db: database manager :param entity: term, word or value to blacklist :raises InvalidValueError: raised when entity is None or an empty string :raises AlreadyExistsError: raised when the entity already exists in the registry. """ with db.connect() as session: try: add_to_matching_blacklist_db(session, entity) except ValueError as e: raise InvalidValueError(e)
python
def add_to_matching_blacklist(db, entity): """Add entity to the matching blacklist. This function adds an 'entity' o term to the matching blacklist. The term to add cannot have a None or empty value, in this case a InvalidValueError will be raised. If the given 'entity' exists in the registry, the function will raise an AlreadyExistsError exception. :param db: database manager :param entity: term, word or value to blacklist :raises InvalidValueError: raised when entity is None or an empty string :raises AlreadyExistsError: raised when the entity already exists in the registry. """ with db.connect() as session: try: add_to_matching_blacklist_db(session, entity) except ValueError as e: raise InvalidValueError(e)
[ "def", "add_to_matching_blacklist", "(", "db", ",", "entity", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "try", ":", "add_to_matching_blacklist_db", "(", "session", ",", "entity", ")", "except", "ValueError", "as", "e", ":", "r...
Add entity to the matching blacklist. This function adds an 'entity' o term to the matching blacklist. The term to add cannot have a None or empty value, in this case a InvalidValueError will be raised. If the given 'entity' exists in the registry, the function will raise an AlreadyExistsError exception. :param db: database manager :param entity: term, word or value to blacklist :raises InvalidValueError: raised when entity is None or an empty string :raises AlreadyExistsError: raised when the entity already exists in the registry.
[ "Add", "entity", "to", "the", "matching", "blacklist", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L279-L298
train
25,583
chaoss/grimoirelab-sortinghat
sortinghat/api.py
delete_unique_identity
def delete_unique_identity(db, uuid): """Remove a unique identity from the registry. Function that removes from the registry, the unique identity that matches with uuid. Data related to this identity will be also removed. It checks first whether the unique identity is already on the registry. When it is found, the unique identity is removed. Otherwise, it will raise a 'NotFoundError' exception. :param db: database manager :param uuid: unique identifier assigned to the unique identity set for being removed :raises NotFoundError: raised when the unique identity does not exist in the registry. """ with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) delete_unique_identity_db(session, uidentity)
python
def delete_unique_identity(db, uuid): """Remove a unique identity from the registry. Function that removes from the registry, the unique identity that matches with uuid. Data related to this identity will be also removed. It checks first whether the unique identity is already on the registry. When it is found, the unique identity is removed. Otherwise, it will raise a 'NotFoundError' exception. :param db: database manager :param uuid: unique identifier assigned to the unique identity set for being removed :raises NotFoundError: raised when the unique identity does not exist in the registry. """ with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) delete_unique_identity_db(session, uidentity)
[ "def", "delete_unique_identity", "(", "db", ",", "uuid", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "uidentity", "=", "find_unique_identity", "(", "session", ",", "uuid", ")", "if", "not", "uidentity", ":", "raise", "NotFoundEr...
Remove a unique identity from the registry. Function that removes from the registry, the unique identity that matches with uuid. Data related to this identity will be also removed. It checks first whether the unique identity is already on the registry. When it is found, the unique identity is removed. Otherwise, it will raise a 'NotFoundError' exception. :param db: database manager :param uuid: unique identifier assigned to the unique identity set for being removed :raises NotFoundError: raised when the unique identity does not exist in the registry.
[ "Remove", "a", "unique", "identity", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L339-L363
train
25,584
chaoss/grimoirelab-sortinghat
sortinghat/api.py
delete_from_matching_blacklist
def delete_from_matching_blacklist(db, entity): """Remove an blacklisted entity from the registry. This function removes the given blacklisted entity from the registry. It checks first whether the excluded entity is already on the registry. When it is found, the entity is removed. Otherwise, it will raise a 'NotFoundError'. :param db: database manager :param entity: blacklisted entity to remove :raises NotFoundError: raised when the blacklisted entity does not exist in the registry. """ with db.connect() as session: mb = session.query(MatchingBlacklist).\ filter(MatchingBlacklist.excluded == entity).first() if not mb: raise NotFoundError(entity=entity) delete_from_matching_blacklist_db(session, mb)
python
def delete_from_matching_blacklist(db, entity): """Remove an blacklisted entity from the registry. This function removes the given blacklisted entity from the registry. It checks first whether the excluded entity is already on the registry. When it is found, the entity is removed. Otherwise, it will raise a 'NotFoundError'. :param db: database manager :param entity: blacklisted entity to remove :raises NotFoundError: raised when the blacklisted entity does not exist in the registry. """ with db.connect() as session: mb = session.query(MatchingBlacklist).\ filter(MatchingBlacklist.excluded == entity).first() if not mb: raise NotFoundError(entity=entity) delete_from_matching_blacklist_db(session, mb)
[ "def", "delete_from_matching_blacklist", "(", "db", ",", "entity", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "mb", "=", "session", ".", "query", "(", "MatchingBlacklist", ")", ".", "filter", "(", "MatchingBlacklist", ".", "exc...
Remove an blacklisted entity from the registry. This function removes the given blacklisted entity from the registry. It checks first whether the excluded entity is already on the registry. When it is found, the entity is removed. Otherwise, it will raise a 'NotFoundError'. :param db: database manager :param entity: blacklisted entity to remove :raises NotFoundError: raised when the blacklisted entity does not exist in the registry.
[ "Remove", "an", "blacklisted", "entity", "from", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L509-L530
train
25,585
chaoss/grimoirelab-sortinghat
sortinghat/api.py
merge_enrollments
def merge_enrollments(db, uuid, organization): """Merge overlapping enrollments. This function merges those enrollments, related to the given 'uuid' and 'organization', that have overlapping dates. Default start and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)] --> (2008-01-01, 2010-01-01) * [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01) * [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01) It may raise a InvalidValueError when any date is out of bounds. In other words, when any date < 1900-01-01 or date > 2100-01-01. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. It is also raised when there are not enrollments related to 'uuid' and 'organization' :raises InvalidValueError: when any date is out of bounds """ # Merge enrollments with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) disjoint = session.query(Enrollment).\ filter(Enrollment.uidentity == uidentity, Enrollment.organization == org).all() if not disjoint: entity = '-'.join((uuid, organization)) raise NotFoundError(entity=entity) dates = [(enr.start, enr.end) for enr in disjoint] for st, en in utils.merge_date_ranges(dates): # We prefer this method to find duplicates # to avoid integrity exceptions when creating # enrollments that are already in the database is_dup = lambda x, st, en: x.start == st and x.end == en filtered = [x for x in disjoint if not is_dup(x, st, en)] if len(filtered) != len(disjoint): disjoint = filtered continue # This means no dups where found so we need to add a # new enrollment try: enroll_db(session, uidentity, org, from_date=st, to_date=en) except ValueError as e: raise InvalidValueError(e) # Remove disjoint enrollments from the registry for enr in disjoint: delete_enrollment_db(session, enr)
python
def merge_enrollments(db, uuid, organization): """Merge overlapping enrollments. This function merges those enrollments, related to the given 'uuid' and 'organization', that have overlapping dates. Default start and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)] --> (2008-01-01, 2010-01-01) * [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01) * [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01) It may raise a InvalidValueError when any date is out of bounds. In other words, when any date < 1900-01-01 or date > 2100-01-01. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. It is also raised when there are not enrollments related to 'uuid' and 'organization' :raises InvalidValueError: when any date is out of bounds """ # Merge enrollments with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) disjoint = session.query(Enrollment).\ filter(Enrollment.uidentity == uidentity, Enrollment.organization == org).all() if not disjoint: entity = '-'.join((uuid, organization)) raise NotFoundError(entity=entity) dates = [(enr.start, enr.end) for enr in disjoint] for st, en in utils.merge_date_ranges(dates): # We prefer this method to find duplicates # to avoid integrity exceptions when creating # enrollments that are already in the database is_dup = lambda x, st, en: x.start == st and x.end == en filtered = [x for x in disjoint if not is_dup(x, st, en)] if len(filtered) != len(disjoint): disjoint = filtered continue # This means no dups where found so we need to add a # new enrollment try: enroll_db(session, uidentity, org, from_date=st, to_date=en) except ValueError as e: raise InvalidValueError(e) # Remove disjoint enrollments from the registry for enr in disjoint: delete_enrollment_db(session, enr)
[ "def", "merge_enrollments", "(", "db", ",", "uuid", ",", "organization", ")", ":", "# Merge enrollments", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "uidentity", "=", "find_unique_identity", "(", "session", ",", "uuid", ")", "if", "not", ...
Merge overlapping enrollments. This function merges those enrollments, related to the given 'uuid' and 'organization', that have overlapping dates. Default start and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)] --> (2008-01-01, 2010-01-01) * [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01) * [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)] --> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01) It may raise a InvalidValueError when any date is out of bounds. In other words, when any date < 1900-01-01 or date > 2100-01-01. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. It is also raised when there are not enrollments related to 'uuid' and 'organization' :raises InvalidValueError: when any date is out of bounds
[ "Merge", "overlapping", "enrollments", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L632-L703
train
25,586
chaoss/grimoirelab-sortinghat
sortinghat/api.py
match_identities
def match_identities(db, uuid, matcher): """Search for similar unique identities. The function will search in the registry for similar identities to 'uuid'. The result will be a list matches containing unique identities objects. This list will not(!) include the given unique identity. The criteria used to check when an identity matches with another one is defined by 'matcher' parameter. This parameter is an instance of 'IdentityMatcher' class. :param db: database manager :param uuid: identifier of the identity to match :param matcher: criteria used to match identities :returns: list of matched unique identities :raises NotFoundError: raised when 'uuid' does not exist in the registry """ uidentities = [] with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) # Get all identities expect of the one requested one query above (uid) candidates = session.query(UniqueIdentity).\ filter(UniqueIdentity.uuid != uuid).\ order_by(UniqueIdentity.uuid) for candidate in candidates: if not matcher.match(uidentity, candidate): continue uidentities.append(candidate) # Detach objects from the session session.expunge_all() return uidentities
python
def match_identities(db, uuid, matcher): """Search for similar unique identities. The function will search in the registry for similar identities to 'uuid'. The result will be a list matches containing unique identities objects. This list will not(!) include the given unique identity. The criteria used to check when an identity matches with another one is defined by 'matcher' parameter. This parameter is an instance of 'IdentityMatcher' class. :param db: database manager :param uuid: identifier of the identity to match :param matcher: criteria used to match identities :returns: list of matched unique identities :raises NotFoundError: raised when 'uuid' does not exist in the registry """ uidentities = [] with db.connect() as session: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) # Get all identities expect of the one requested one query above (uid) candidates = session.query(UniqueIdentity).\ filter(UniqueIdentity.uuid != uuid).\ order_by(UniqueIdentity.uuid) for candidate in candidates: if not matcher.match(uidentity, candidate): continue uidentities.append(candidate) # Detach objects from the session session.expunge_all() return uidentities
[ "def", "match_identities", "(", "db", ",", "uuid", ",", "matcher", ")", ":", "uidentities", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "uidentity", "=", "find_unique_identity", "(", "session", ",", "uuid", ")", "if", "...
Search for similar unique identities. The function will search in the registry for similar identities to 'uuid'. The result will be a list matches containing unique identities objects. This list will not(!) include the given unique identity. The criteria used to check when an identity matches with another one is defined by 'matcher' parameter. This parameter is an instance of 'IdentityMatcher' class. :param db: database manager :param uuid: identifier of the identity to match :param matcher: criteria used to match identities :returns: list of matched unique identities :raises NotFoundError: raised when 'uuid' does not exist in the registry
[ "Search", "for", "similar", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L745-L786
train
25,587
chaoss/grimoirelab-sortinghat
sortinghat/api.py
unique_identities
def unique_identities(db, uuid=None, source=None): """List the unique identities available in the registry. The function returns a list of unique identities. When 'uuid' parameter is set, it will only return the information related to the unique identity identified by 'uuid'. When 'source' is given, only thouse unique identities with one or more identities related to that source will be returned. When the given 'uuid', assigned to the given 'source', is not in the registry, a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier for the identity :param source: source of the identities :raises NotFoundError: raised when the given uuid is not found in the registry """ uidentities = [] with db.connect() as session: query = session.query(UniqueIdentity) if source: query = query.join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid, Identity.source == source) if uuid: uidentity = query.\ filter(UniqueIdentity.uuid == uuid).first() if not uidentity: raise NotFoundError(entity=uuid) uidentities = [uidentity] else: uidentities = query.\ order_by(UniqueIdentity.uuid).all() # Detach objects from the session session.expunge_all() return uidentities
python
def unique_identities(db, uuid=None, source=None): """List the unique identities available in the registry. The function returns a list of unique identities. When 'uuid' parameter is set, it will only return the information related to the unique identity identified by 'uuid'. When 'source' is given, only thouse unique identities with one or more identities related to that source will be returned. When the given 'uuid', assigned to the given 'source', is not in the registry, a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier for the identity :param source: source of the identities :raises NotFoundError: raised when the given uuid is not found in the registry """ uidentities = [] with db.connect() as session: query = session.query(UniqueIdentity) if source: query = query.join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid, Identity.source == source) if uuid: uidentity = query.\ filter(UniqueIdentity.uuid == uuid).first() if not uidentity: raise NotFoundError(entity=uuid) uidentities = [uidentity] else: uidentities = query.\ order_by(UniqueIdentity.uuid).all() # Detach objects from the session session.expunge_all() return uidentities
[ "def", "unique_identities", "(", "db", ",", "uuid", "=", "None", ",", "source", "=", "None", ")", ":", "uidentities", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "query", "=", "session", ".", "query", "(", "UniqueIden...
List the unique identities available in the registry. The function returns a list of unique identities. When 'uuid' parameter is set, it will only return the information related to the unique identity identified by 'uuid'. When 'source' is given, only thouse unique identities with one or more identities related to that source will be returned. When the given 'uuid', assigned to the given 'source', is not in the registry, a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier for the identity :param source: source of the identities :raises NotFoundError: raised when the given uuid is not found in the registry
[ "List", "the", "unique", "identities", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L789-L833
train
25,588
chaoss/grimoirelab-sortinghat
sortinghat/api.py
search_unique_identities
def search_unique_identities(db, term, source=None): """Look for unique identities. This function returns those unique identities which match with the given 'term'. The term will be compated with name, email, username and source values of each identity. When `source` is given, this search will be only performed on identities linked to this source. :param db: database manater :param term: term to match with unique identities data :param source: search only on identities from this source :raises NotFoundError: raised when the given term is not found on any unique identity from the registry """ uidentities = [] pattern = '%' + term + '%' if term else None with db.connect() as session: query = session.query(UniqueIdentity).\ join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid) if source: query = query.filter(Identity.source == source) if pattern: query = query.filter(Identity.name.like(pattern) | Identity.email.like(pattern) | Identity.username.like(pattern) | Identity.source.like(pattern)) else: query = query.filter((Identity.name == None) | (Identity.email == None) | (Identity.username == None) | (Identity.source == None)) uidentities = query.order_by(UniqueIdentity.uuid).all() if not uidentities: raise NotFoundError(entity=term) # Detach objects from the session session.expunge_all() return uidentities
python
def search_unique_identities(db, term, source=None): """Look for unique identities. This function returns those unique identities which match with the given 'term'. The term will be compated with name, email, username and source values of each identity. When `source` is given, this search will be only performed on identities linked to this source. :param db: database manater :param term: term to match with unique identities data :param source: search only on identities from this source :raises NotFoundError: raised when the given term is not found on any unique identity from the registry """ uidentities = [] pattern = '%' + term + '%' if term else None with db.connect() as session: query = session.query(UniqueIdentity).\ join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid) if source: query = query.filter(Identity.source == source) if pattern: query = query.filter(Identity.name.like(pattern) | Identity.email.like(pattern) | Identity.username.like(pattern) | Identity.source.like(pattern)) else: query = query.filter((Identity.name == None) | (Identity.email == None) | (Identity.username == None) | (Identity.source == None)) uidentities = query.order_by(UniqueIdentity.uuid).all() if not uidentities: raise NotFoundError(entity=term) # Detach objects from the session session.expunge_all() return uidentities
[ "def", "search_unique_identities", "(", "db", ",", "term", ",", "source", "=", "None", ")", ":", "uidentities", "=", "[", "]", "pattern", "=", "'%'", "+", "term", "+", "'%'", "if", "term", "else", "None", "with", "db", ".", "connect", "(", ")", "as",...
Look for unique identities. This function returns those unique identities which match with the given 'term'. The term will be compated with name, email, username and source values of each identity. When `source` is given, this search will be only performed on identities linked to this source. :param db: database manater :param term: term to match with unique identities data :param source: search only on identities from this source :raises NotFoundError: raised when the given term is not found on any unique identity from the registry
[ "Look", "for", "unique", "identities", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L836-L881
train
25,589
chaoss/grimoirelab-sortinghat
sortinghat/api.py
search_unique_identities_slice
def search_unique_identities_slice(db, term, offset, limit): """Look for unique identities using slicing. This function returns those unique identities which match with the given `term`. The term will be compared with name, email, username and source values of each identity. When an empty term is given, all unique identities will be returned. The results are limited by `offset` (starting on 0) and `limit`. Along with the list of unique identities, this function returns the total number of unique identities that match the given `term`. :param db: database manager :param term: term to match with unique identities data :param offset: return results starting on this position :param limit: maximum number of unique identities to return :raises InvalidValueError: raised when either the given value of `offset` or `limit` is lower than zero """ uidentities = [] pattern = '%' + term + '%' if term else None if offset < 0: raise InvalidValueError('offset must be greater than 0 - %s given' % str(offset)) if limit < 0: raise InvalidValueError('limit must be greater than 0 - %s given' % str(limit)) with db.connect() as session: query = session.query(UniqueIdentity).\ join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid) if pattern: query = query.filter(Identity.name.like(pattern) | Identity.email.like(pattern) | Identity.username.like(pattern) | Identity.source.like(pattern)) query = query.group_by(UniqueIdentity).\ order_by(UniqueIdentity.uuid) # Get the total number of unique identities for that search nuids = query.count() start = offset end = offset + limit uidentities = query.slice(start, end).all() # Detach objects from the session session.expunge_all() return uidentities, nuids
python
def search_unique_identities_slice(db, term, offset, limit): """Look for unique identities using slicing. This function returns those unique identities which match with the given `term`. The term will be compared with name, email, username and source values of each identity. When an empty term is given, all unique identities will be returned. The results are limited by `offset` (starting on 0) and `limit`. Along with the list of unique identities, this function returns the total number of unique identities that match the given `term`. :param db: database manager :param term: term to match with unique identities data :param offset: return results starting on this position :param limit: maximum number of unique identities to return :raises InvalidValueError: raised when either the given value of `offset` or `limit` is lower than zero """ uidentities = [] pattern = '%' + term + '%' if term else None if offset < 0: raise InvalidValueError('offset must be greater than 0 - %s given' % str(offset)) if limit < 0: raise InvalidValueError('limit must be greater than 0 - %s given' % str(limit)) with db.connect() as session: query = session.query(UniqueIdentity).\ join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid) if pattern: query = query.filter(Identity.name.like(pattern) | Identity.email.like(pattern) | Identity.username.like(pattern) | Identity.source.like(pattern)) query = query.group_by(UniqueIdentity).\ order_by(UniqueIdentity.uuid) # Get the total number of unique identities for that search nuids = query.count() start = offset end = offset + limit uidentities = query.slice(start, end).all() # Detach objects from the session session.expunge_all() return uidentities, nuids
[ "def", "search_unique_identities_slice", "(", "db", ",", "term", ",", "offset", ",", "limit", ")", ":", "uidentities", "=", "[", "]", "pattern", "=", "'%'", "+", "term", "+", "'%'", "if", "term", "else", "None", "if", "offset", "<", "0", ":", "raise", ...
Look for unique identities using slicing. This function returns those unique identities which match with the given `term`. The term will be compared with name, email, username and source values of each identity. When an empty term is given, all unique identities will be returned. The results are limited by `offset` (starting on 0) and `limit`. Along with the list of unique identities, this function returns the total number of unique identities that match the given `term`. :param db: database manager :param term: term to match with unique identities data :param offset: return results starting on this position :param limit: maximum number of unique identities to return :raises InvalidValueError: raised when either the given value of `offset` or `limit` is lower than zero
[ "Look", "for", "unique", "identities", "using", "slicing", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L884-L939
train
25,590
chaoss/grimoirelab-sortinghat
sortinghat/api.py
search_last_modified_identities
def search_last_modified_identities(db, after): """Look for the uuids of identities modified on or after a given date. This function returns the uuids of identities modified on the given date or after it. The result is a list of uuids identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of identities modified """ with db.connect() as session: query = session.query(Identity.id).\ filter(Identity.last_modified >= after) ids = [id_.id for id_ in query.order_by(Identity.id).all()] return ids
python
def search_last_modified_identities(db, after): """Look for the uuids of identities modified on or after a given date. This function returns the uuids of identities modified on the given date or after it. The result is a list of uuids identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of identities modified """ with db.connect() as session: query = session.query(Identity.id).\ filter(Identity.last_modified >= after) ids = [id_.id for id_ in query.order_by(Identity.id).all()] return ids
[ "def", "search_last_modified_identities", "(", "db", ",", "after", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "query", "=", "session", ".", "query", "(", "Identity", ".", "id", ")", ".", "filter", "(", "Identity", ".", "las...
Look for the uuids of identities modified on or after a given date. This function returns the uuids of identities modified on the given date or after it. The result is a list of uuids identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of identities modified
[ "Look", "for", "the", "uuids", "of", "identities", "modified", "on", "or", "after", "a", "given", "date", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L942-L959
train
25,591
chaoss/grimoirelab-sortinghat
sortinghat/api.py
search_last_modified_unique_identities
def search_last_modified_unique_identities(db, after): """Look for the uuids of unique identities modified on or after a given date. This function returns the uuids of unique identities modified on the given date or after it. The result is a list of uuids unique identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of unique identities modified """ with db.connect() as session: query = session.query(UniqueIdentity.uuid).\ filter(UniqueIdentity.last_modified >= after) uids = [uid.uuid for uid in query.order_by(UniqueIdentity.uuid).all()] return uids
python
def search_last_modified_unique_identities(db, after): """Look for the uuids of unique identities modified on or after a given date. This function returns the uuids of unique identities modified on the given date or after it. The result is a list of uuids unique identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of unique identities modified """ with db.connect() as session: query = session.query(UniqueIdentity.uuid).\ filter(UniqueIdentity.last_modified >= after) uids = [uid.uuid for uid in query.order_by(UniqueIdentity.uuid).all()] return uids
[ "def", "search_last_modified_unique_identities", "(", "db", ",", "after", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "query", "=", "session", ".", "query", "(", "UniqueIdentity", ".", "uuid", ")", ".", "filter", "(", "UniqueIde...
Look for the uuids of unique identities modified on or after a given date. This function returns the uuids of unique identities modified on the given date or after it. The result is a list of uuids unique identities. :param db: database manager :param after: look for identities modified on or after this date :returns: a list of uuids of unique identities modified
[ "Look", "for", "the", "uuids", "of", "unique", "identities", "modified", "on", "or", "after", "a", "given", "date", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L962-L980
train
25,592
chaoss/grimoirelab-sortinghat
sortinghat/api.py
search_profiles
def search_profiles(db, no_gender=False): """List unique identities profiles. The function will return the list of profiles filtered by the given parameters. When `no_gender` is set, only profiles without gender values will be returned. :param db: database manager :param no_gender: return only those profiles without gender :returns: a list of profile entities """ profiles = [] with db.connect() as session: query = session.query(Profile) if no_gender: query = query.filter(Profile.gender == None) profiles = query.order_by(Profile.uuid).all() # Detach objects from the session session.expunge_all() return profiles
python
def search_profiles(db, no_gender=False): """List unique identities profiles. The function will return the list of profiles filtered by the given parameters. When `no_gender` is set, only profiles without gender values will be returned. :param db: database manager :param no_gender: return only those profiles without gender :returns: a list of profile entities """ profiles = [] with db.connect() as session: query = session.query(Profile) if no_gender: query = query.filter(Profile.gender == None) profiles = query.order_by(Profile.uuid).all() # Detach objects from the session session.expunge_all() return profiles
[ "def", "search_profiles", "(", "db", ",", "no_gender", "=", "False", ")", ":", "profiles", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "query", "=", "session", ".", "query", "(", "Profile", ")", "if", "no_gender", ":"...
List unique identities profiles. The function will return the list of profiles filtered by the given parameters. When `no_gender` is set, only profiles without gender values will be returned. :param db: database manager :param no_gender: return only those profiles without gender :returns: a list of profile entities
[ "List", "unique", "identities", "profiles", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L983-L1008
train
25,593
chaoss/grimoirelab-sortinghat
sortinghat/api.py
registry
def registry(db, term=None): """List the organizations available in the registry. The function will return the list of organizations. If term parameter is set, it will only return the information about the organizations which match that term. When the given term does not match with any organization from the registry a 'NotFounError' exception will be raised. :param db: database manager :param term: term to match with organizations names :returns: a list of organizations sorted by their name :raises NotFoundError: raised when the given term is not found on any organization from the registry """ orgs = [] with db.connect() as session: if term: orgs = session.query(Organization).\ filter(Organization.name.like('%' + term + '%')).\ order_by(Organization.name).all() if not orgs: raise NotFoundError(entity=term) else: orgs = session.query(Organization).\ order_by(Organization.name).all() # Detach objects from the session session.expunge_all() return orgs
python
def registry(db, term=None): """List the organizations available in the registry. The function will return the list of organizations. If term parameter is set, it will only return the information about the organizations which match that term. When the given term does not match with any organization from the registry a 'NotFounError' exception will be raised. :param db: database manager :param term: term to match with organizations names :returns: a list of organizations sorted by their name :raises NotFoundError: raised when the given term is not found on any organization from the registry """ orgs = [] with db.connect() as session: if term: orgs = session.query(Organization).\ filter(Organization.name.like('%' + term + '%')).\ order_by(Organization.name).all() if not orgs: raise NotFoundError(entity=term) else: orgs = session.query(Organization).\ order_by(Organization.name).all() # Detach objects from the session session.expunge_all() return orgs
[ "def", "registry", "(", "db", ",", "term", "=", "None", ")", ":", "orgs", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "if", "term", ":", "orgs", "=", "session", ".", "query", "(", "Organization", ")", ".", "filter...
List the organizations available in the registry. The function will return the list of organizations. If term parameter is set, it will only return the information about the organizations which match that term. When the given term does not match with any organization from the registry a 'NotFounError' exception will be raised. :param db: database manager :param term: term to match with organizations names :returns: a list of organizations sorted by their name :raises NotFoundError: raised when the given term is not found on any organization from the registry
[ "List", "the", "organizations", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1011-L1045
train
25,594
chaoss/grimoirelab-sortinghat
sortinghat/api.py
domains
def domains(db, domain=None, top=False): """List the domains available in the registry. The function will return the list of domains. Settting the top flag, it will look for those domains that are top domains. If domain parameter is set, it will only return the information about that domain. When both paramaters are set, it will first search for the given domain. If it is not found, it will look for its top domains. In the case of neither the domain exists nor has top domains, a 'NotFoundError' exception will be raised. :param db: database manager :param domain: name of the domain :param top: filter by top domains :returns: a list of domains :raises NotFoundError: raised when the given domain is not found in the registry """ doms = [] with db.connect() as session: if domain: dom = find_domain(session, domain) if not dom: if not top: raise NotFoundError(entity=domain) else: # Adds a dot to the beggining of the domain. # Useful to compare domains like example.com and # myexample.com add_dot = lambda d: '.' + d if not d.startswith('.') else d d = add_dot(domain) tops = session.query(Domain).\ filter(Domain.is_top_domain).order_by(Domain.domain).all() doms = [t for t in tops if d.endswith(add_dot(t.domain))] if not doms: raise NotFoundError(entity=domain) else: doms = [dom] else: query = session.query(Domain) if top: query = query.filter(Domain.is_top_domain) doms = query.order_by(Domain.domain).all() # Detach objects from the session session.expunge_all() return doms
python
def domains(db, domain=None, top=False): """List the domains available in the registry. The function will return the list of domains. Settting the top flag, it will look for those domains that are top domains. If domain parameter is set, it will only return the information about that domain. When both paramaters are set, it will first search for the given domain. If it is not found, it will look for its top domains. In the case of neither the domain exists nor has top domains, a 'NotFoundError' exception will be raised. :param db: database manager :param domain: name of the domain :param top: filter by top domains :returns: a list of domains :raises NotFoundError: raised when the given domain is not found in the registry """ doms = [] with db.connect() as session: if domain: dom = find_domain(session, domain) if not dom: if not top: raise NotFoundError(entity=domain) else: # Adds a dot to the beggining of the domain. # Useful to compare domains like example.com and # myexample.com add_dot = lambda d: '.' + d if not d.startswith('.') else d d = add_dot(domain) tops = session.query(Domain).\ filter(Domain.is_top_domain).order_by(Domain.domain).all() doms = [t for t in tops if d.endswith(add_dot(t.domain))] if not doms: raise NotFoundError(entity=domain) else: doms = [dom] else: query = session.query(Domain) if top: query = query.filter(Domain.is_top_domain) doms = query.order_by(Domain.domain).all() # Detach objects from the session session.expunge_all() return doms
[ "def", "domains", "(", "db", ",", "domain", "=", "None", ",", "top", "=", "False", ")", ":", "doms", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "if", "domain", ":", "dom", "=", "find_domain", "(", "session", ",",...
List the domains available in the registry. The function will return the list of domains. Settting the top flag, it will look for those domains that are top domains. If domain parameter is set, it will only return the information about that domain. When both paramaters are set, it will first search for the given domain. If it is not found, it will look for its top domains. In the case of neither the domain exists nor has top domains, a 'NotFoundError' exception will be raised. :param db: database manager :param domain: name of the domain :param top: filter by top domains :returns: a list of domains :raises NotFoundError: raised when the given domain is not found in the registry
[ "List", "the", "domains", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1048-L1107
train
25,595
chaoss/grimoirelab-sortinghat
sortinghat/api.py
countries
def countries(db, code=None, term=None): """List the countries available in the registry. The function will return the list of countries. When either 'code' or 'term' parameters are set, it will only return the information about those countries that match them. Take into account that 'code' is a country identifier composed by two letters (i.e ES or US). A 'InvalidValueError' exception will be raised when this identifier is not valid. If this value is valid, 'term' parameter will be ignored. When the given values do not match with any country from the registry a 'NotFounError' exception will be raised. :param db: database manager :param code: country identifier composed by two letters :param term: term to match with countries names :returns: a list of countries sorted by their country id :raises InvalidValueError: raised when 'code' is not a string composed by two letters :raises NotFoundError: raised when the given 'code' or 'term' is not found for any country from the registry """ def _is_code_valid(code): return type(code) == str \ and len(code) == 2 \ and code.isalpha() if code is not None and not _is_code_valid(code): raise InvalidValueError('country code must be a 2 length alpha string - %s given' % str(code)) cs = [] with db.connect() as session: query = session.query(Country) if code or term: if code: query = query.filter(Country.code == code.upper()) elif term: query = query.filter(Country.name.like('%' + term + '%')) cs = query.order_by(Country.code).all() if not cs: e = code if code else term raise NotFoundError(entity=e) else: cs = session.query(Country).\ order_by(Country.code).all() # Detach objects from the session session.expunge_all() return cs
python
def countries(db, code=None, term=None): """List the countries available in the registry. The function will return the list of countries. When either 'code' or 'term' parameters are set, it will only return the information about those countries that match them. Take into account that 'code' is a country identifier composed by two letters (i.e ES or US). A 'InvalidValueError' exception will be raised when this identifier is not valid. If this value is valid, 'term' parameter will be ignored. When the given values do not match with any country from the registry a 'NotFounError' exception will be raised. :param db: database manager :param code: country identifier composed by two letters :param term: term to match with countries names :returns: a list of countries sorted by their country id :raises InvalidValueError: raised when 'code' is not a string composed by two letters :raises NotFoundError: raised when the given 'code' or 'term' is not found for any country from the registry """ def _is_code_valid(code): return type(code) == str \ and len(code) == 2 \ and code.isalpha() if code is not None and not _is_code_valid(code): raise InvalidValueError('country code must be a 2 length alpha string - %s given' % str(code)) cs = [] with db.connect() as session: query = session.query(Country) if code or term: if code: query = query.filter(Country.code == code.upper()) elif term: query = query.filter(Country.name.like('%' + term + '%')) cs = query.order_by(Country.code).all() if not cs: e = code if code else term raise NotFoundError(entity=e) else: cs = session.query(Country).\ order_by(Country.code).all() # Detach objects from the session session.expunge_all() return cs
[ "def", "countries", "(", "db", ",", "code", "=", "None", ",", "term", "=", "None", ")", ":", "def", "_is_code_valid", "(", "code", ")", ":", "return", "type", "(", "code", ")", "==", "str", "and", "len", "(", "code", ")", "==", "2", "and", "code"...
List the countries available in the registry. The function will return the list of countries. When either 'code' or 'term' parameters are set, it will only return the information about those countries that match them. Take into account that 'code' is a country identifier composed by two letters (i.e ES or US). A 'InvalidValueError' exception will be raised when this identifier is not valid. If this value is valid, 'term' parameter will be ignored. When the given values do not match with any country from the registry a 'NotFounError' exception will be raised. :param db: database manager :param code: country identifier composed by two letters :param term: term to match with countries names :returns: a list of countries sorted by their country id :raises InvalidValueError: raised when 'code' is not a string composed by two letters :raises NotFoundError: raised when the given 'code' or 'term' is not found for any country from the registry
[ "List", "the", "countries", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1110-L1169
train
25,596
chaoss/grimoirelab-sortinghat
sortinghat/api.py
enrollments
def enrollments(db, uuid=None, organization=None, from_date=None, to_date=None): """List the enrollment information available in the registry. This function will return a list of enrollments. If 'uuid' parameter is set, it will return the enrollments related to that unique identity; if 'organization' parameter is given, it will return the enrollments related to that organization; if both parameters are set, the function will return the list of enrollments of 'uuid' on the 'organization'. Enrollments between a period can also be listed using 'from_date' and 'to_date' parameters. When these are set, the function will return all those enrollments where Enrollment.start >= from_date AND Enrollment.end <= to_date. Defaults values for these dates are 1900-01-01 and 2100-01-01. When either 'uuid' or 'organization' are not in the registry a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :returns: a list of enrollments sorted by uuid or by organization. :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. :raises InvalidValeError: it is raised in two cases, when "from_date" < 1900-01-01 or "to_date" > 2100-01-01; when "from_date > to_date". """ if not from_date: from_date = MIN_PERIOD_DATE if not to_date: to_date = MAX_PERIOD_DATE if from_date < MIN_PERIOD_DATE or from_date > MAX_PERIOD_DATE: raise InvalidValueError("'from_date' %s is out of bounds" % str(from_date)) if to_date < MIN_PERIOD_DATE or to_date > MAX_PERIOD_DATE: raise InvalidValueError("'to_date' %s is out of bounds" % str(to_date)) if from_date and to_date and from_date > to_date: raise InvalidValueError("'from_date' %s cannot be greater than %s" % (from_date, to_date)) enrollments = [] with db.connect() as session: query = session.query(Enrollment).\ join(UniqueIdentity, Organization).\ filter(Enrollment.start >= from_date, Enrollment.end <= to_date) # Filter by uuid if uuid: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) query = query.filter(Enrollment.uidentity == uidentity) # Filter by organization if organization: org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) query = query.filter(Enrollment.organization == org) # Get the results enrollments = query.order_by(UniqueIdentity.uuid, Organization.name, Enrollment.start, Enrollment.end).all() # Detach objects from the session session.expunge_all() return enrollments
python
def enrollments(db, uuid=None, organization=None, from_date=None, to_date=None): """List the enrollment information available in the registry. This function will return a list of enrollments. If 'uuid' parameter is set, it will return the enrollments related to that unique identity; if 'organization' parameter is given, it will return the enrollments related to that organization; if both parameters are set, the function will return the list of enrollments of 'uuid' on the 'organization'. Enrollments between a period can also be listed using 'from_date' and 'to_date' parameters. When these are set, the function will return all those enrollments where Enrollment.start >= from_date AND Enrollment.end <= to_date. Defaults values for these dates are 1900-01-01 and 2100-01-01. When either 'uuid' or 'organization' are not in the registry a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :returns: a list of enrollments sorted by uuid or by organization. :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. :raises InvalidValeError: it is raised in two cases, when "from_date" < 1900-01-01 or "to_date" > 2100-01-01; when "from_date > to_date". """ if not from_date: from_date = MIN_PERIOD_DATE if not to_date: to_date = MAX_PERIOD_DATE if from_date < MIN_PERIOD_DATE or from_date > MAX_PERIOD_DATE: raise InvalidValueError("'from_date' %s is out of bounds" % str(from_date)) if to_date < MIN_PERIOD_DATE or to_date > MAX_PERIOD_DATE: raise InvalidValueError("'to_date' %s is out of bounds" % str(to_date)) if from_date and to_date and from_date > to_date: raise InvalidValueError("'from_date' %s cannot be greater than %s" % (from_date, to_date)) enrollments = [] with db.connect() as session: query = session.query(Enrollment).\ join(UniqueIdentity, Organization).\ filter(Enrollment.start >= from_date, Enrollment.end <= to_date) # Filter by uuid if uuid: uidentity = find_unique_identity(session, uuid) if not uidentity: raise NotFoundError(entity=uuid) query = query.filter(Enrollment.uidentity == uidentity) # Filter by organization if organization: org = find_organization(session, organization) if not org: raise NotFoundError(entity=organization) query = query.filter(Enrollment.organization == org) # Get the results enrollments = query.order_by(UniqueIdentity.uuid, Organization.name, Enrollment.start, Enrollment.end).all() # Detach objects from the session session.expunge_all() return enrollments
[ "def", "enrollments", "(", "db", ",", "uuid", "=", "None", ",", "organization", "=", "None", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ")", ":", "if", "not", "from_date", ":", "from_date", "=", "MIN_PERIOD_DATE", "if", "not", "to_date",...
List the enrollment information available in the registry. This function will return a list of enrollments. If 'uuid' parameter is set, it will return the enrollments related to that unique identity; if 'organization' parameter is given, it will return the enrollments related to that organization; if both parameters are set, the function will return the list of enrollments of 'uuid' on the 'organization'. Enrollments between a period can also be listed using 'from_date' and 'to_date' parameters. When these are set, the function will return all those enrollments where Enrollment.start >= from_date AND Enrollment.end <= to_date. Defaults values for these dates are 1900-01-01 and 2100-01-01. When either 'uuid' or 'organization' are not in the registry a 'NotFoundError' exception will be raised. :param db: database manager :param uuid: unique identifier :param organization: name of the organization :param from_date: date when the enrollment starts :param to_date: date when the enrollment ends :returns: a list of enrollments sorted by uuid or by organization. :raises NotFoundError: when either 'uuid' or 'organization' are not found in the registry. :raises InvalidValeError: it is raised in two cases, when "from_date" < 1900-01-01 or "to_date" > 2100-01-01; when "from_date > to_date".
[ "List", "the", "enrollment", "information", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1172-L1253
train
25,597
chaoss/grimoirelab-sortinghat
sortinghat/api.py
blacklist
def blacklist(db, term=None): """List the blacklisted entities available in the registry. The function will return the list of blacklisted entities. If term parameter is set, it will only return the information about the entities which match that term. When the given term does not match with any entry on the blacklist a 'NotFoundError' exception will be raised. :param db: database manager :param term: term to match with blacklisted entries :returns: a list of blacklisted entities sorted by their name :raises NotFoundError: raised when the given term is not found on any blacklisted entry from the registry """ mbs = [] with db.connect() as session: if term: mbs = session.query(MatchingBlacklist).\ filter(MatchingBlacklist.excluded.like('%' + term + '%')).\ order_by(MatchingBlacklist.excluded).all() if not mbs: raise NotFoundError(entity=term) else: mbs = session.query(MatchingBlacklist).\ order_by(MatchingBlacklist.excluded).all() # Detach objects from the session session.expunge_all() return mbs
python
def blacklist(db, term=None): """List the blacklisted entities available in the registry. The function will return the list of blacklisted entities. If term parameter is set, it will only return the information about the entities which match that term. When the given term does not match with any entry on the blacklist a 'NotFoundError' exception will be raised. :param db: database manager :param term: term to match with blacklisted entries :returns: a list of blacklisted entities sorted by their name :raises NotFoundError: raised when the given term is not found on any blacklisted entry from the registry """ mbs = [] with db.connect() as session: if term: mbs = session.query(MatchingBlacklist).\ filter(MatchingBlacklist.excluded.like('%' + term + '%')).\ order_by(MatchingBlacklist.excluded).all() if not mbs: raise NotFoundError(entity=term) else: mbs = session.query(MatchingBlacklist).\ order_by(MatchingBlacklist.excluded).all() # Detach objects from the session session.expunge_all() return mbs
[ "def", "blacklist", "(", "db", ",", "term", "=", "None", ")", ":", "mbs", "=", "[", "]", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "if", "term", ":", "mbs", "=", "session", ".", "query", "(", "MatchingBlacklist", ")", ".", "fi...
List the blacklisted entities available in the registry. The function will return the list of blacklisted entities. If term parameter is set, it will only return the information about the entities which match that term. When the given term does not match with any entry on the blacklist a 'NotFoundError' exception will be raised. :param db: database manager :param term: term to match with blacklisted entries :returns: a list of blacklisted entities sorted by their name :raises NotFoundError: raised when the given term is not found on any blacklisted entry from the registry
[ "List", "the", "blacklisted", "entities", "available", "in", "the", "registry", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1256-L1290
train
25,598
chaoss/grimoirelab-sortinghat
sortinghat/cmd/profile.py
Profile.run
def run(self, *args): """Endit profile information.""" uuid, kwargs = self.__parse_arguments(*args) code = self.edit_profile(uuid, **kwargs) return code
python
def run(self, *args): """Endit profile information.""" uuid, kwargs = self.__parse_arguments(*args) code = self.edit_profile(uuid, **kwargs) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "uuid", ",", "kwargs", "=", "self", ".", "__parse_arguments", "(", "*", "args", ")", "code", "=", "self", ".", "edit_profile", "(", "uuid", ",", "*", "*", "kwargs", ")", "return", "code" ]
Endit profile information.
[ "Endit", "profile", "information", "." ]
391cd37a75fea26311dc6908bc1c953c540a8e04
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/profile.py#L89-L95
train
25,599