id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
21,300
Alignak-monitoring/alignak
alignak/log.py
set_log_console
def set_log_console(log_level=logging.INFO): """Set the Alignak daemons logger have a console log handler. This is only used for the arbiter verify mode to add a console log handler. :param log_level: log level :return: n/a """ # Change the logger and all its handlers log level logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) logger_.setLevel(log_level) # Adding a console logger... csh = ColorStreamHandler(sys.stdout) csh.setFormatter(Formatter('[%(asctime)s] %(levelname)s: [%(name)s] %(message)s', "%Y-%m-%d %H:%M:%S")) logger_.addHandler(csh)
python
def set_log_console(log_level=logging.INFO): # Change the logger and all its handlers log level logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) logger_.setLevel(log_level) # Adding a console logger... csh = ColorStreamHandler(sys.stdout) csh.setFormatter(Formatter('[%(asctime)s] %(levelname)s: [%(name)s] %(message)s', "%Y-%m-%d %H:%M:%S")) logger_.addHandler(csh)
[ "def", "set_log_console", "(", "log_level", "=", "logging", ".", "INFO", ")", ":", "# Change the logger and all its handlers log level", "logger_", "=", "logging", ".", "getLogger", "(", "ALIGNAK_LOGGER_NAME", ")", "logger_", ".", "setLevel", "(", "log_level", ")", ...
Set the Alignak daemons logger have a console log handler. This is only used for the arbiter verify mode to add a console log handler. :param log_level: log level :return: n/a
[ "Set", "the", "Alignak", "daemons", "logger", "have", "a", "console", "log", "handler", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/log.py#L201-L217
21,301
Alignak-monitoring/alignak
alignak/log.py
set_log_level
def set_log_level(log_level=logging.INFO, handlers=None): """Set the Alignak logger log level. This is mainly used for the arbiter verify code to set the log level at INFO level whatever the configured log level is set. This is also used when changing the daemon log level thanks to the WS interface If an handlers name list is provided, all the handlers which name is in this list are concerned else only the `daemons` handler log level is changed. :param handlers: list of concerned handlers :type: list :param log_level: log level :return: n/a """ # print("Setting log level: %s" % (log_level)) # Change the logger and all its handlers log level logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) logger_.setLevel(log_level) if handlers is not None: for handler in logger_.handlers: if getattr(handler, '_name', None) in handlers: handler.setLevel(log_level)
python
def set_log_level(log_level=logging.INFO, handlers=None): # print("Setting log level: %s" % (log_level)) # Change the logger and all its handlers log level logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) logger_.setLevel(log_level) if handlers is not None: for handler in logger_.handlers: if getattr(handler, '_name', None) in handlers: handler.setLevel(log_level)
[ "def", "set_log_level", "(", "log_level", "=", "logging", ".", "INFO", ",", "handlers", "=", "None", ")", ":", "# print(\"Setting log level: %s\" % (log_level))", "# Change the logger and all its handlers log level", "logger_", "=", "logging", ".", "getLogger", "(", "ALIG...
Set the Alignak logger log level. This is mainly used for the arbiter verify code to set the log level at INFO level whatever the configured log level is set. This is also used when changing the daemon log level thanks to the WS interface If an handlers name list is provided, all the handlers which name is in this list are concerned else only the `daemons` handler log level is changed. :param handlers: list of concerned handlers :type: list :param log_level: log level :return: n/a
[ "Set", "the", "Alignak", "logger", "log", "level", ".", "This", "is", "mainly", "used", "for", "the", "arbiter", "verify", "code", "to", "set", "the", "log", "level", "at", "INFO", "level", "whatever", "the", "configured", "log", "level", "is", "set", "....
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/log.py#L220-L242
21,302
Alignak-monitoring/alignak
alignak/log.py
make_monitoring_log
def make_monitoring_log(level, message, timestamp=None, to_logger=False): """ Function used to build the monitoring log. Emit a log message with the provided level to the monitoring log logger. Build a Brok typed as monitoring_log with the provided message When to_logger is True, the information is sent to the python logger, else a monitoring_log Brok is returned. The Brok is managed by the daemons to build an Event that will br logged by the Arbiter when it collects all the events. TODO: replace with dedicated brok for each event to log - really useful? :param level: log level as defined in logging :type level: str :param message: message to send to the monitoring log logger :type message: str :param to_logger: when set, send to the logger, else raise a brok :type to_logger: bool :param timestamp: if set, force the log event timestamp :return: a monitoring_log Brok :rtype: alignak.brok.Brok """ level = level.lower() if level not in ['debug', 'info', 'warning', 'error', 'critical']: return False if to_logger: logging.getLogger(ALIGNAK_LOGGER_NAME).debug("Monitoring log: %s / %s", level, message) # Emit to our monitoring log logger message = message.replace('\r', '\\r') message = message.replace('\n', '\\n') logger_ = logging.getLogger(MONITORING_LOGGER_NAME) logging_function = getattr(logger_, level) try: message = message.decode('utf8', 'ignore') except UnicodeEncodeError: pass except AttributeError: # Python 3 raises an exception! pass if timestamp: st = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') logging_function(message, extra={'my_date': st}) else: logging_function(message) return True # ... and returns a brok return Brok({'type': 'monitoring_log', 'data': {'level': level, 'message': message}})
python
def make_monitoring_log(level, message, timestamp=None, to_logger=False): level = level.lower() if level not in ['debug', 'info', 'warning', 'error', 'critical']: return False if to_logger: logging.getLogger(ALIGNAK_LOGGER_NAME).debug("Monitoring log: %s / %s", level, message) # Emit to our monitoring log logger message = message.replace('\r', '\\r') message = message.replace('\n', '\\n') logger_ = logging.getLogger(MONITORING_LOGGER_NAME) logging_function = getattr(logger_, level) try: message = message.decode('utf8', 'ignore') except UnicodeEncodeError: pass except AttributeError: # Python 3 raises an exception! pass if timestamp: st = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') logging_function(message, extra={'my_date': st}) else: logging_function(message) return True # ... and returns a brok return Brok({'type': 'monitoring_log', 'data': {'level': level, 'message': message}})
[ "def", "make_monitoring_log", "(", "level", ",", "message", ",", "timestamp", "=", "None", ",", "to_logger", "=", "False", ")", ":", "level", "=", "level", ".", "lower", "(", ")", "if", "level", "not", "in", "[", "'debug'", ",", "'info'", ",", "'warnin...
Function used to build the monitoring log. Emit a log message with the provided level to the monitoring log logger. Build a Brok typed as monitoring_log with the provided message When to_logger is True, the information is sent to the python logger, else a monitoring_log Brok is returned. The Brok is managed by the daemons to build an Event that will br logged by the Arbiter when it collects all the events. TODO: replace with dedicated brok for each event to log - really useful? :param level: log level as defined in logging :type level: str :param message: message to send to the monitoring log logger :type message: str :param to_logger: when set, send to the logger, else raise a brok :type to_logger: bool :param timestamp: if set, force the log event timestamp :return: a monitoring_log Brok :rtype: alignak.brok.Brok
[ "Function", "used", "to", "build", "the", "monitoring", "log", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/log.py#L256-L308
21,303
Alignak-monitoring/alignak
alignak/objects/contact.py
Contact.want_service_notification
def want_service_notification(self, notifways, timeperiods, timestamp, state, n_type, business_impact, cmd=None): """Check if notification options match the state of the service :param timestamp: time we want to notify the contact (usually now) :type timestamp: int :param state: host or service state ("WARNING", "CRITICAL" ..) :type state: str :param n_type: type of notification ("PROBLEM", "RECOVERY" ..) :type n_type: str :param business_impact: impact of this service :type business_impact: int :param cmd: command launched to notify the contact :type cmd: str :return: True if contact wants notification, otherwise False :rtype: bool """ if not self.service_notifications_enabled: return False # If we are in downtime, we do not want notification for downtime_id in self.downtimes: downtime = self.downtimes[downtime_id] if downtime.is_in_effect: self.in_scheduled_downtime = True return False self.in_scheduled_downtime = False # Now the rest is for sub notificationways. If one is OK, we are ok # We will filter in another phase for notifway_id in self.notificationways: notifway = notifways[notifway_id] nw_b = notifway.want_service_notification(timeperiods, timestamp, state, n_type, business_impact, cmd) if nw_b: return True # Oh... no one is ok for it? so no, sorry return False
python
def want_service_notification(self, notifways, timeperiods, timestamp, state, n_type, business_impact, cmd=None): if not self.service_notifications_enabled: return False # If we are in downtime, we do not want notification for downtime_id in self.downtimes: downtime = self.downtimes[downtime_id] if downtime.is_in_effect: self.in_scheduled_downtime = True return False self.in_scheduled_downtime = False # Now the rest is for sub notificationways. If one is OK, we are ok # We will filter in another phase for notifway_id in self.notificationways: notifway = notifways[notifway_id] nw_b = notifway.want_service_notification(timeperiods, timestamp, state, n_type, business_impact, cmd) if nw_b: return True # Oh... no one is ok for it? so no, sorry return False
[ "def", "want_service_notification", "(", "self", ",", "notifways", ",", "timeperiods", ",", "timestamp", ",", "state", ",", "n_type", ",", "business_impact", ",", "cmd", "=", "None", ")", ":", "if", "not", "self", ".", "service_notifications_enabled", ":", "re...
Check if notification options match the state of the service :param timestamp: time we want to notify the contact (usually now) :type timestamp: int :param state: host or service state ("WARNING", "CRITICAL" ..) :type state: str :param n_type: type of notification ("PROBLEM", "RECOVERY" ..) :type n_type: str :param business_impact: impact of this service :type business_impact: int :param cmd: command launched to notify the contact :type cmd: str :return: True if contact wants notification, otherwise False :rtype: bool
[ "Check", "if", "notification", "options", "match", "the", "state", "of", "the", "service" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contact.py#L243-L281
21,304
Alignak-monitoring/alignak
alignak/objects/contact.py
Contact.want_host_notification
def want_host_notification(self, notifways, timeperiods, timestamp, state, n_type, business_impact, cmd=None): """Check if notification options match the state of the host :param timestamp: time we want to notify the contact (usually now) :type timestamp: int :param state: host or service state ("UP", "DOWN" ..) :type state: str :param n_type: type of notification ("PROBLEM", "RECOVERY" ..) :type n_type: str :param business_impact: impact of this host :type business_impact: int :param cmd: command launch to notify the contact :type cmd: str :return: True if contact wants notification, otherwise False :rtype: bool """ if not self.host_notifications_enabled: return False # If we are in downtime, we do not want notification for downtime in self.downtimes: if downtime.is_in_effect: self.in_scheduled_downtime = True return False self.in_scheduled_downtime = False # Now it's all for sub notificationways. If one is OK, we are OK # We will filter in another phase for notifway_id in self.notificationways: notifway = notifways[notifway_id] nw_b = notifway.want_host_notification(timeperiods, timestamp, state, n_type, business_impact, cmd) if nw_b: return True # Oh, nobody..so NO :) return False
python
def want_host_notification(self, notifways, timeperiods, timestamp, state, n_type, business_impact, cmd=None): if not self.host_notifications_enabled: return False # If we are in downtime, we do not want notification for downtime in self.downtimes: if downtime.is_in_effect: self.in_scheduled_downtime = True return False self.in_scheduled_downtime = False # Now it's all for sub notificationways. If one is OK, we are OK # We will filter in another phase for notifway_id in self.notificationways: notifway = notifways[notifway_id] nw_b = notifway.want_host_notification(timeperiods, timestamp, state, n_type, business_impact, cmd) if nw_b: return True # Oh, nobody..so NO :) return False
[ "def", "want_host_notification", "(", "self", ",", "notifways", ",", "timeperiods", ",", "timestamp", ",", "state", ",", "n_type", ",", "business_impact", ",", "cmd", "=", "None", ")", ":", "if", "not", "self", ".", "host_notifications_enabled", ":", "return",...
Check if notification options match the state of the host :param timestamp: time we want to notify the contact (usually now) :type timestamp: int :param state: host or service state ("UP", "DOWN" ..) :type state: str :param n_type: type of notification ("PROBLEM", "RECOVERY" ..) :type n_type: str :param business_impact: impact of this host :type business_impact: int :param cmd: command launch to notify the contact :type cmd: str :return: True if contact wants notification, otherwise False :rtype: bool
[ "Check", "if", "notification", "options", "match", "the", "state", "of", "the", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contact.py#L283-L320
21,305
Alignak-monitoring/alignak
alignak/objects/contact.py
Contacts.explode
def explode(self, contactgroups, notificationways): """Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notificationways: alignak.objects.notificationway.Notificationways :return: None """ # Contactgroups property need to be fulfill for got the information self.apply_partial_inheritance('contactgroups') # _special properties maybe came from a template, so # import them before grok ourselves for prop in Contact.special_properties: if prop == 'contact_name': continue self.apply_partial_inheritance(prop) # Register ourselves into the contactsgroups we are in for contact in self: if not (hasattr(contact, 'contact_name') and hasattr(contact, 'contactgroups')): continue for contactgroup in contact.contactgroups: contactgroups.add_member(contact.contact_name, contactgroup.strip()) # Now create a notification way with the simple parameter of the # contacts for contact in self: need_notificationway = False params = {} for param in Contact.simple_way_parameters: if hasattr(contact, param): need_notificationway = True params[param] = getattr(contact, param) elif contact.properties[param].has_default: # put a default text value # Remove the value and put a default value setattr(contact, param, contact.properties[param].default) if need_notificationway: cname = getattr(contact, 'contact_name', getattr(contact, 'alias', '')) nw_name = cname + '_inner_nw' notificationways.new_inner_member(nw_name, params) if not hasattr(contact, 'notificationways'): contact.notificationways = [nw_name] else: contact.notificationways = list(contact.notificationways) contact.notificationways.append(nw_name)
python
def explode(self, contactgroups, notificationways): # Contactgroups property need to be fulfill for got the information self.apply_partial_inheritance('contactgroups') # _special properties maybe came from a template, so # import them before grok ourselves for prop in Contact.special_properties: if prop == 'contact_name': continue self.apply_partial_inheritance(prop) # Register ourselves into the contactsgroups we are in for contact in self: if not (hasattr(contact, 'contact_name') and hasattr(contact, 'contactgroups')): continue for contactgroup in contact.contactgroups: contactgroups.add_member(contact.contact_name, contactgroup.strip()) # Now create a notification way with the simple parameter of the # contacts for contact in self: need_notificationway = False params = {} for param in Contact.simple_way_parameters: if hasattr(contact, param): need_notificationway = True params[param] = getattr(contact, param) elif contact.properties[param].has_default: # put a default text value # Remove the value and put a default value setattr(contact, param, contact.properties[param].default) if need_notificationway: cname = getattr(contact, 'contact_name', getattr(contact, 'alias', '')) nw_name = cname + '_inner_nw' notificationways.new_inner_member(nw_name, params) if not hasattr(contact, 'notificationways'): contact.notificationways = [nw_name] else: contact.notificationways = list(contact.notificationways) contact.notificationways.append(nw_name)
[ "def", "explode", "(", "self", ",", "contactgroups", ",", "notificationways", ")", ":", "# Contactgroups property need to be fulfill for got the information", "self", ".", "apply_partial_inheritance", "(", "'contactgroups'", ")", "# _special properties maybe came from a template, s...
Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notificationways: alignak.objects.notificationway.Notificationways :return: None
[ "Explode", "all", "contact", "for", "each", "contactsgroup" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contact.py#L481-L528
21,306
Alignak-monitoring/alignak
alignak/modules/inner_retention.py
InnerRetention.hook_save_retention
def hook_save_retention(self, scheduler): """Save retention data to a Json formated file :param scheduler: scheduler instance of alignak :type scheduler: object :return: None """ if not self.enabled: logger.warning("Alignak retention module is not enabled." "Saving objects state is not possible.") return None try: start_time = time.time() # Get retention data from the scheduler data_to_save = scheduler.get_retention_data() if not data_to_save: logger.warning("Alignak retention data to save are not containing any information.") return None # Move services data to their respective hosts dictionary # Alignak scheduler do not merge the services into the host dictionary! for host_name in data_to_save['hosts']: data_to_save['hosts'][host_name]['services'] = {} data_to_save['hosts'][host_name]['name'] = host_name for host_name, service_description in data_to_save['services']: data_to_save['hosts'][host_name]['services'][service_description] = \ data_to_save['services'][(host_name, service_description)] try: if not self.retention_file: logger.info('Saving retention data to: %s', self.retention_dir) for host_name in data_to_save['hosts']: file_name = os.path.join(self.retention_dir, self.retention_file, "%s.json" % host_name) with open(file_name, "w") as fd: fd.write(json.dumps(data_to_save['hosts'][host_name], indent=2, separators=(',', ': '), sort_keys=True)) logger.debug('- saved: %s', file_name) logger.info('Saved') else: logger.info('Saving retention data to: %s', self.retention_file) with open(self.retention_file, "w") as fd: fd.write(json.dumps(data_to_save['hosts'], indent=2, separators=(',', ': '), sort_keys=True)) logger.info('Saved') except Exception as exp: # pylint: disable=broad-except # pragma: no cover, should never happen... logger.warning("Error when saving retention data to %s", self.retention_file) logger.exception(exp) logger.info('%d hosts saved in retention', len(data_to_save['hosts'])) self.statsmgr.counter('retention-save.hosts', len(data_to_save['hosts'])) logger.info('%d services saved in retention', len(data_to_save['services'])) self.statsmgr.counter('retention-save.services', len(data_to_save['services'])) self.statsmgr.timer('retention-save.time', time.time() - start_time) logger.info("Retention data saved in %s seconds", (time.time() - start_time)) except Exception as exp: # pylint: disable=broad-except self.enabled = False logger.warning("Retention save failed: %s", exp) logger.exception(exp) return False return True
python
def hook_save_retention(self, scheduler): if not self.enabled: logger.warning("Alignak retention module is not enabled." "Saving objects state is not possible.") return None try: start_time = time.time() # Get retention data from the scheduler data_to_save = scheduler.get_retention_data() if not data_to_save: logger.warning("Alignak retention data to save are not containing any information.") return None # Move services data to their respective hosts dictionary # Alignak scheduler do not merge the services into the host dictionary! for host_name in data_to_save['hosts']: data_to_save['hosts'][host_name]['services'] = {} data_to_save['hosts'][host_name]['name'] = host_name for host_name, service_description in data_to_save['services']: data_to_save['hosts'][host_name]['services'][service_description] = \ data_to_save['services'][(host_name, service_description)] try: if not self.retention_file: logger.info('Saving retention data to: %s', self.retention_dir) for host_name in data_to_save['hosts']: file_name = os.path.join(self.retention_dir, self.retention_file, "%s.json" % host_name) with open(file_name, "w") as fd: fd.write(json.dumps(data_to_save['hosts'][host_name], indent=2, separators=(',', ': '), sort_keys=True)) logger.debug('- saved: %s', file_name) logger.info('Saved') else: logger.info('Saving retention data to: %s', self.retention_file) with open(self.retention_file, "w") as fd: fd.write(json.dumps(data_to_save['hosts'], indent=2, separators=(',', ': '), sort_keys=True)) logger.info('Saved') except Exception as exp: # pylint: disable=broad-except # pragma: no cover, should never happen... logger.warning("Error when saving retention data to %s", self.retention_file) logger.exception(exp) logger.info('%d hosts saved in retention', len(data_to_save['hosts'])) self.statsmgr.counter('retention-save.hosts', len(data_to_save['hosts'])) logger.info('%d services saved in retention', len(data_to_save['services'])) self.statsmgr.counter('retention-save.services', len(data_to_save['services'])) self.statsmgr.timer('retention-save.time', time.time() - start_time) logger.info("Retention data saved in %s seconds", (time.time() - start_time)) except Exception as exp: # pylint: disable=broad-except self.enabled = False logger.warning("Retention save failed: %s", exp) logger.exception(exp) return False return True
[ "def", "hook_save_retention", "(", "self", ",", "scheduler", ")", ":", "if", "not", "self", ".", "enabled", ":", "logger", ".", "warning", "(", "\"Alignak retention module is not enabled.\"", "\"Saving objects state is not possible.\"", ")", "return", "None", "try", "...
Save retention data to a Json formated file :param scheduler: scheduler instance of alignak :type scheduler: object :return: None
[ "Save", "retention", "data", "to", "a", "Json", "formated", "file" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_retention.py#L259-L326
21,307
Alignak-monitoring/alignak
alignak/objects/checkmodulation.py
CheckModulation.get_check_command
def get_check_command(self, timeperiods, t_to_go): """Get the check_command if we are in the check period modulation :param t_to_go: time to check if we are in the timeperiod :type t_to_go: :return: A check command if we are in the check period, None otherwise :rtype: alignak.objects.command.Command """ if not self.check_period or timeperiods[self.check_period].is_time_valid(t_to_go): return self.check_command return None
python
def get_check_command(self, timeperiods, t_to_go): if not self.check_period or timeperiods[self.check_period].is_time_valid(t_to_go): return self.check_command return None
[ "def", "get_check_command", "(", "self", ",", "timeperiods", ",", "t_to_go", ")", ":", "if", "not", "self", ".", "check_period", "or", "timeperiods", "[", "self", ".", "check_period", "]", ".", "is_time_valid", "(", "t_to_go", ")", ":", "return", "self", "...
Get the check_command if we are in the check period modulation :param t_to_go: time to check if we are in the timeperiod :type t_to_go: :return: A check command if we are in the check period, None otherwise :rtype: alignak.objects.command.Command
[ "Get", "the", "check_command", "if", "we", "are", "in", "the", "check", "period", "modulation" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/checkmodulation.py#L113-L123
21,308
Alignak-monitoring/alignak
alignak/objects/checkmodulation.py
CheckModulations.linkify
def linkify(self, timeperiods, commands): """Replace check_period by real Timeperiod object into each CheckModulation Replace check_command by real Command object into each CheckModulation :param timeperiods: timeperiods to link to :type timeperiods: alignak.objects.timeperiod.Timeperiods :param commands: commands to link to :type commands: alignak.objects.command.Commands :return: None """ self.linkify_with_timeperiods(timeperiods, 'check_period') self.linkify_one_command_with_commands(commands, 'check_command')
python
def linkify(self, timeperiods, commands): self.linkify_with_timeperiods(timeperiods, 'check_period') self.linkify_one_command_with_commands(commands, 'check_command')
[ "def", "linkify", "(", "self", ",", "timeperiods", ",", "commands", ")", ":", "self", ".", "linkify_with_timeperiods", "(", "timeperiods", ",", "'check_period'", ")", "self", ".", "linkify_one_command_with_commands", "(", "commands", ",", "'check_command'", ")" ]
Replace check_period by real Timeperiod object into each CheckModulation Replace check_command by real Command object into each CheckModulation :param timeperiods: timeperiods to link to :type timeperiods: alignak.objects.timeperiod.Timeperiods :param commands: commands to link to :type commands: alignak.objects.command.Commands :return: None
[ "Replace", "check_period", "by", "real", "Timeperiod", "object", "into", "each", "CheckModulation", "Replace", "check_command", "by", "real", "Command", "object", "into", "each", "CheckModulation" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/checkmodulation.py#L167-L178
21,309
Alignak-monitoring/alignak
alignak/objects/checkmodulation.py
CheckModulations.new_inner_member
def new_inner_member(self, name=None, params=None): """Create a CheckModulation object and add it to items :param name: CheckModulation name :type name: str :param params: parameters to init CheckModulation :type params: dict :return: None TODO: Remove this default mutable argument. Usually result in unexpected behavior """ if name is None: name = 'Generated_checkmodulation_%s' % uuid.uuid4() if params is None: params = {} params['checkmodulation_name'] = name checkmodulation = CheckModulation(params) self.add_item(checkmodulation)
python
def new_inner_member(self, name=None, params=None): if name is None: name = 'Generated_checkmodulation_%s' % uuid.uuid4() if params is None: params = {} params['checkmodulation_name'] = name checkmodulation = CheckModulation(params) self.add_item(checkmodulation)
[ "def", "new_inner_member", "(", "self", ",", "name", "=", "None", ",", "params", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Generated_checkmodulation_%s'", "%", "uuid", ".", "uuid4", "(", ")", "if", "params", "is", "None", "...
Create a CheckModulation object and add it to items :param name: CheckModulation name :type name: str :param params: parameters to init CheckModulation :type params: dict :return: None TODO: Remove this default mutable argument. Usually result in unexpected behavior
[ "Create", "a", "CheckModulation", "object", "and", "add", "it", "to", "items" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/checkmodulation.py#L180-L198
21,310
harmsm/PyCmdMessenger
PyCmdMessenger/arduino.py
ArduinoBoard.open
def open(self): """ Open the serial connection. """ if not self._is_connected: print("Connecting to arduino on {}... ".format(self.device),end="") self.comm = serial.Serial() self.comm.port = self.device self.comm.baudrate = self.baud_rate self.comm.timeout = self.timeout self.dtr = self.enable_dtr self.comm.open() time.sleep(self.settle_time) self._is_connected = True print("done.")
python
def open(self): if not self._is_connected: print("Connecting to arduino on {}... ".format(self.device),end="") self.comm = serial.Serial() self.comm.port = self.device self.comm.baudrate = self.baud_rate self.comm.timeout = self.timeout self.dtr = self.enable_dtr self.comm.open() time.sleep(self.settle_time) self._is_connected = True print("done.")
[ "def", "open", "(", "self", ")", ":", "if", "not", "self", ".", "_is_connected", ":", "print", "(", "\"Connecting to arduino on {}... \"", ".", "format", "(", "self", ".", "device", ")", ",", "end", "=", "\"\"", ")", "self", ".", "comm", "=", "serial", ...
Open the serial connection.
[ "Open", "the", "serial", "connection", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/arduino.py#L147-L166
21,311
harmsm/PyCmdMessenger
PyCmdMessenger/arduino.py
ArduinoBoard.close
def close(self): """ Close serial connection. """ if self._is_connected: self.comm.close() self._is_connected = False
python
def close(self): if self._is_connected: self.comm.close() self._is_connected = False
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_is_connected", ":", "self", ".", "comm", ".", "close", "(", ")", "self", ".", "_is_connected", "=", "False" ]
Close serial connection.
[ "Close", "serial", "connection", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/arduino.py#L189-L196
21,312
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger.receive
def receive(self,arg_formats=None): """ Recieve commands coming off the serial port. arg_formats is an optimal keyword that specifies the formats to use to parse incoming arguments. If specified here, arg_formats supercedes the formats specified on initialization. """ # Read serial input until a command separator or empty character is # reached msg = [[]] raw_msg = [] escaped = False command_sep_found = False while True: tmp = self.board.read() raw_msg.append(tmp) if escaped: # Either drop the escape character or, if this wasn't really # an escape, keep previous escape character and new character if tmp in self._escaped_characters: msg[-1].append(tmp) escaped = False else: msg[-1].append(self._byte_escape_sep) msg[-1].append(tmp) escaped = False else: # look for escape character if tmp == self._byte_escape_sep: escaped = True # or field separator elif tmp == self._byte_field_sep: msg.append([]) # or command separator elif tmp == self._byte_command_sep: command_sep_found = True break # or any empty characater elif tmp == b'': break # okay, must be something else: msg[-1].append(tmp) # No message received given timeouts if len(msg) == 1 and len(msg[0]) == 0: return None # Make sure the message terminated properly if not command_sep_found: # empty message (likely from line endings being included) joined_raw = b''.join(raw_msg) if joined_raw.strip() == b'': return None err = "Incomplete message ({})".format(joined_raw.decode()) raise EOFError(err) # Turn message into fields fields = [b''.join(m) for m in msg] # Get the command name. cmd = fields[0].strip().decode() try: cmd_name = self._int_to_cmd_name[int(cmd)] except (ValueError,IndexError): if self.give_warnings: cmd_name = "unknown" w = "Recieved unrecognized command ({}).".format(cmd) warnings.warn(w,Warning) # Figure out what formats to use for each argument. arg_format_list = [] if arg_formats != None: # The user specified formats arg_format_list = list(arg_formats) else: try: # See if class was initialized with a format for arguments to this # command arg_format_list = self._cmd_name_to_format[cmd_name] except KeyError: # if not, guess for all arguments arg_format_list = ["g" for i in range(len(fields[1:]))] # Deal with "*" format arg_format_list = self._treat_star_format(arg_format_list,fields[1:]) if len(fields[1:]) > 0: if len(arg_format_list) != len(fields[1:]): err = "Number of argument formats must match the number of recieved arguments." raise ValueError(err) received = [] for i, f in enumerate(fields[1:]): received.append(self._recv_methods[arg_format_list[i]](f)) # Record the time the message arrived message_time = time.time() return cmd_name, received, message_time
python
def receive(self,arg_formats=None): # Read serial input until a command separator or empty character is # reached msg = [[]] raw_msg = [] escaped = False command_sep_found = False while True: tmp = self.board.read() raw_msg.append(tmp) if escaped: # Either drop the escape character or, if this wasn't really # an escape, keep previous escape character and new character if tmp in self._escaped_characters: msg[-1].append(tmp) escaped = False else: msg[-1].append(self._byte_escape_sep) msg[-1].append(tmp) escaped = False else: # look for escape character if tmp == self._byte_escape_sep: escaped = True # or field separator elif tmp == self._byte_field_sep: msg.append([]) # or command separator elif tmp == self._byte_command_sep: command_sep_found = True break # or any empty characater elif tmp == b'': break # okay, must be something else: msg[-1].append(tmp) # No message received given timeouts if len(msg) == 1 and len(msg[0]) == 0: return None # Make sure the message terminated properly if not command_sep_found: # empty message (likely from line endings being included) joined_raw = b''.join(raw_msg) if joined_raw.strip() == b'': return None err = "Incomplete message ({})".format(joined_raw.decode()) raise EOFError(err) # Turn message into fields fields = [b''.join(m) for m in msg] # Get the command name. cmd = fields[0].strip().decode() try: cmd_name = self._int_to_cmd_name[int(cmd)] except (ValueError,IndexError): if self.give_warnings: cmd_name = "unknown" w = "Recieved unrecognized command ({}).".format(cmd) warnings.warn(w,Warning) # Figure out what formats to use for each argument. arg_format_list = [] if arg_formats != None: # The user specified formats arg_format_list = list(arg_formats) else: try: # See if class was initialized with a format for arguments to this # command arg_format_list = self._cmd_name_to_format[cmd_name] except KeyError: # if not, guess for all arguments arg_format_list = ["g" for i in range(len(fields[1:]))] # Deal with "*" format arg_format_list = self._treat_star_format(arg_format_list,fields[1:]) if len(fields[1:]) > 0: if len(arg_format_list) != len(fields[1:]): err = "Number of argument formats must match the number of recieved arguments." raise ValueError(err) received = [] for i, f in enumerate(fields[1:]): received.append(self._recv_methods[arg_format_list[i]](f)) # Record the time the message arrived message_time = time.time() return cmd_name, received, message_time
[ "def", "receive", "(", "self", ",", "arg_formats", "=", "None", ")", ":", "# Read serial input until a command separator or empty character is", "# reached ", "msg", "=", "[", "[", "]", "]", "raw_msg", "=", "[", "]", "escaped", "=", "False", "command_sep_found", "...
Recieve commands coming off the serial port. arg_formats is an optimal keyword that specifies the formats to use to parse incoming arguments. If specified here, arg_formats supercedes the formats specified on initialization.
[ "Recieve", "commands", "coming", "off", "the", "serial", "port", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L175-L289
21,313
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_char
def _send_char(self,value): """ Convert a single char to a bytes object. """ if type(value) != str and type(value) != bytes: err = "char requires a string or bytes array of length 1" raise ValueError(err) if len(value) != 1: err = "char must be a single character, not \"{}\"".format(value) raise ValueError(err) if type(value) != bytes: value = value.encode("ascii") if value in self._escaped_characters: err = "Cannot send a control character as a single char to arduino. Send as string instead." raise OverflowError(err) return struct.pack('c',value)
python
def _send_char(self,value): if type(value) != str and type(value) != bytes: err = "char requires a string or bytes array of length 1" raise ValueError(err) if len(value) != 1: err = "char must be a single character, not \"{}\"".format(value) raise ValueError(err) if type(value) != bytes: value = value.encode("ascii") if value in self._escaped_characters: err = "Cannot send a control character as a single char to arduino. Send as string instead." raise OverflowError(err) return struct.pack('c',value)
[ "def", "_send_char", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "!=", "str", "and", "type", "(", "value", ")", "!=", "bytes", ":", "err", "=", "\"char requires a string or bytes array of length 1\"", "raise", "ValueError", "(", "er...
Convert a single char to a bytes object.
[ "Convert", "a", "single", "char", "to", "a", "bytes", "object", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L319-L339
21,314
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_byte
def _send_byte(self,value): """ Convert a numerical value into an integer, then to a byte object. Check bounds for byte. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > 255 or value < 0: err = "Value {} exceeds the size of the board's byte.".format(value) raise OverflowError(err) return struct.pack("B",value)
python
def _send_byte(self,value): # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > 255 or value < 0: err = "Value {} exceeds the size of the board's byte.".format(value) raise OverflowError(err) return struct.pack("B",value)
[ "def", "_send_byte", "(", "self", ",", "value", ")", ":", "# Coerce to int. This will throw a ValueError if the value can't", "# actually be converted.", "if", "type", "(", "value", ")", "!=", "int", ":", "new_value", "=", "int", "(", "value", ")", "if", "self", "...
Convert a numerical value into an integer, then to a byte object. Check bounds for byte.
[ "Convert", "a", "numerical", "value", "into", "an", "integer", "then", "to", "a", "byte", "object", ".", "Check", "bounds", "for", "byte", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L341-L362
21,315
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_int
def _send_int(self,value): """ Convert a numerical value into an integer, then to a bytes object Check bounds for signed int. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.int_max or value < self.board.int_min: err = "Value {} exceeds the size of the board's int.".format(value) raise OverflowError(err) return struct.pack(self.board.int_type,value)
python
def _send_int(self,value): # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.int_max or value < self.board.int_min: err = "Value {} exceeds the size of the board's int.".format(value) raise OverflowError(err) return struct.pack(self.board.int_type,value)
[ "def", "_send_int", "(", "self", ",", "value", ")", ":", "# Coerce to int. This will throw a ValueError if the value can't ", "# actually be converted.", "if", "type", "(", "value", ")", "!=", "int", ":", "new_value", "=", "int", "(", "value", ")", "if", "self", "...
Convert a numerical value into an integer, then to a bytes object Check bounds for signed int.
[ "Convert", "a", "numerical", "value", "into", "an", "integer", "then", "to", "a", "bytes", "object", "Check", "bounds", "for", "signed", "int", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L364-L385
21,316
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_unsigned_int
def _send_unsigned_int(self,value): """ Convert a numerical value into an integer, then to a bytes object. Check bounds for unsigned int. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.unsigned_int_max or value < self.board.unsigned_int_min: err = "Value {} exceeds the size of the board's unsigned int.".format(value) raise OverflowError(err) return struct.pack(self.board.unsigned_int_type,value)
python
def _send_unsigned_int(self,value): # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.unsigned_int_max or value < self.board.unsigned_int_min: err = "Value {} exceeds the size of the board's unsigned int.".format(value) raise OverflowError(err) return struct.pack(self.board.unsigned_int_type,value)
[ "def", "_send_unsigned_int", "(", "self", ",", "value", ")", ":", "# Coerce to int. This will throw a ValueError if the value can't ", "# actually be converted.", "if", "type", "(", "value", ")", "!=", "int", ":", "new_value", "=", "int", "(", "value", ")", "if", "s...
Convert a numerical value into an integer, then to a bytes object. Check bounds for unsigned int.
[ "Convert", "a", "numerical", "value", "into", "an", "integer", "then", "to", "a", "bytes", "object", ".", "Check", "bounds", "for", "unsigned", "int", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L387-L407
21,317
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_long
def _send_long(self,value): """ Convert a numerical value into an integer, then to a bytes object. Check bounds for signed long. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.long_max or value < self.board.long_min: err = "Value {} exceeds the size of the board's long.".format(value) raise OverflowError(err) return struct.pack(self.board.long_type,value)
python
def _send_long(self,value): # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.long_max or value < self.board.long_min: err = "Value {} exceeds the size of the board's long.".format(value) raise OverflowError(err) return struct.pack(self.board.long_type,value)
[ "def", "_send_long", "(", "self", ",", "value", ")", ":", "# Coerce to int. This will throw a ValueError if the value can't ", "# actually be converted.", "if", "type", "(", "value", ")", "!=", "int", ":", "new_value", "=", "int", "(", "value", ")", "if", "self", ...
Convert a numerical value into an integer, then to a bytes object. Check bounds for signed long.
[ "Convert", "a", "numerical", "value", "into", "an", "integer", "then", "to", "a", "bytes", "object", ".", "Check", "bounds", "for", "signed", "long", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L409-L430
21,318
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_unsigned_long
def _send_unsigned_long(self,value): """ Convert a numerical value into an integer, then to a bytes object. Check bounds for unsigned long. """ # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.unsigned_long_max or value < self.board.unsigned_long_min: err = "Value {} exceeds the size of the board's unsigned long.".format(value) raise OverflowError(err) return struct.pack(self.board.unsigned_long_type,value)
python
def _send_unsigned_long(self,value): # Coerce to int. This will throw a ValueError if the value can't # actually be converted. if type(value) != int: new_value = int(value) if self.give_warnings: w = "Coercing {} into int ({})".format(value,new_value) warnings.warn(w,Warning) value = new_value # Range check if value > self.board.unsigned_long_max or value < self.board.unsigned_long_min: err = "Value {} exceeds the size of the board's unsigned long.".format(value) raise OverflowError(err) return struct.pack(self.board.unsigned_long_type,value)
[ "def", "_send_unsigned_long", "(", "self", ",", "value", ")", ":", "# Coerce to int. This will throw a ValueError if the value can't ", "# actually be converted.", "if", "type", "(", "value", ")", "!=", "int", ":", "new_value", "=", "int", "(", "value", ")", "if", "...
Convert a numerical value into an integer, then to a bytes object. Check bounds for unsigned long.
[ "Convert", "a", "numerical", "value", "into", "an", "integer", "then", "to", "a", "bytes", "object", ".", "Check", "bounds", "for", "unsigned", "long", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L432-L453
21,319
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_string
def _send_string(self,value): """ Convert a string to a bytes object. If value is not a string, it is be converted to one with a standard string.format call. """ if type(value) != bytes: value = "{}".format(value).encode("ascii") return value
python
def _send_string(self,value): if type(value) != bytes: value = "{}".format(value).encode("ascii") return value
[ "def", "_send_string", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "!=", "bytes", ":", "value", "=", "\"{}\"", ".", "format", "(", "value", ")", ".", "encode", "(", "\"ascii\"", ")", "return", "value" ]
Convert a string to a bytes object. If value is not a string, it is be converted to one with a standard string.format call.
[ "Convert", "a", "string", "to", "a", "bytes", "object", ".", "If", "value", "is", "not", "a", "string", "it", "is", "be", "converted", "to", "one", "with", "a", "standard", "string", ".", "format", "call", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L489-L498
21,320
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._send_bool
def _send_bool(self,value): """ Convert a boolean value into a bytes object. Uses 0 and 1 as output. """ # Sanity check. if type(value) != bool and value not in [0,1]: err = "{} is not boolean.".format(value) raise ValueError(err) return struct.pack("?",value)
python
def _send_bool(self,value): # Sanity check. if type(value) != bool and value not in [0,1]: err = "{} is not boolean.".format(value) raise ValueError(err) return struct.pack("?",value)
[ "def", "_send_bool", "(", "self", ",", "value", ")", ":", "# Sanity check.", "if", "type", "(", "value", ")", "!=", "bool", "and", "value", "not", "in", "[", "0", ",", "1", "]", ":", "err", "=", "\"{} is not boolean.\"", ".", "format", "(", "value", ...
Convert a boolean value into a bytes object. Uses 0 and 1 as output.
[ "Convert", "a", "boolean", "value", "into", "a", "bytes", "object", ".", "Uses", "0", "and", "1", "as", "output", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L500-L510
21,321
harmsm/PyCmdMessenger
PyCmdMessenger/PyCmdMessenger.py
CmdMessenger._recv_guess
def _recv_guess(self,value): """ Take the binary spew and try to make it into a float or integer. If that can't be done, return a string. Note: this is generally a bad idea, as values can be seriously mangled by going from float -> string -> float. You'll generally be better off using a format specifier and binary argument passing. """ if self.give_warnings: w = "Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data.".format(value) warnings.warn(w,Warning) tmp_value = value.decode() try: float(tmp_value) if len(tmp_value.split(".")) == 1: # integer return int(tmp_value) else: # float return float(tmp_value) except ValueError: pass # Return as string return self._recv_string(value)
python
def _recv_guess(self,value): if self.give_warnings: w = "Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data.".format(value) warnings.warn(w,Warning) tmp_value = value.decode() try: float(tmp_value) if len(tmp_value.split(".")) == 1: # integer return int(tmp_value) else: # float return float(tmp_value) except ValueError: pass # Return as string return self._recv_string(value)
[ "def", "_recv_guess", "(", "self", ",", "value", ")", ":", "if", "self", ".", "give_warnings", ":", "w", "=", "\"Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data.\"", ".", "format", "(", "value", ...
Take the binary spew and try to make it into a float or integer. If that can't be done, return a string. Note: this is generally a bad idea, as values can be seriously mangled by going from float -> string -> float. You'll generally be better off using a format specifier and binary argument passing.
[ "Take", "the", "binary", "spew", "and", "try", "to", "make", "it", "into", "a", "float", "or", "integer", ".", "If", "that", "can", "t", "be", "done", "return", "a", "string", "." ]
215d6f9402262662a14a2996f532934339639a5b
https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L610-L640
21,322
severb/graypy
graypy/handler.py
BaseGELFHandler._add_full_message
def _add_full_message(gelf_dict, record): """Add the ``full_message`` field to the ``gelf_dict`` if any traceback information exists within the logging record :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract a full logging message from to insert into the given ``gelf_dict``. :type record: logging.LogRecord """ # if a traceback exists add it to the log as the full_message field full_message = None # format exception information if present if record.exc_info: full_message = '\n'.join( traceback.format_exception(*record.exc_info)) # use pre-formatted exception information in cases where the primary # exception information was removed, eg. for LogRecord serialization if record.exc_text: full_message = record.exc_text if full_message: gelf_dict["full_message"] = full_message
python
def _add_full_message(gelf_dict, record): # if a traceback exists add it to the log as the full_message field full_message = None # format exception information if present if record.exc_info: full_message = '\n'.join( traceback.format_exception(*record.exc_info)) # use pre-formatted exception information in cases where the primary # exception information was removed, eg. for LogRecord serialization if record.exc_text: full_message = record.exc_text if full_message: gelf_dict["full_message"] = full_message
[ "def", "_add_full_message", "(", "gelf_dict", ",", "record", ")", ":", "# if a traceback exists add it to the log as the full_message field", "full_message", "=", "None", "# format exception information if present", "if", "record", ".", "exc_info", ":", "full_message", "=", "...
Add the ``full_message`` field to the ``gelf_dict`` if any traceback information exists within the logging record :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract a full logging message from to insert into the given ``gelf_dict``. :type record: logging.LogRecord
[ "Add", "the", "full_message", "field", "to", "the", "gelf_dict", "if", "any", "traceback", "information", "exists", "within", "the", "logging", "record" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L194-L216
21,323
severb/graypy
graypy/handler.py
BaseGELFHandler._resolve_host
def _resolve_host(fqdn, localname): """Resolve the ``host`` GELF field :param fqdn: Boolean indicating whether to use :meth:`socket.getfqdn` to obtain the ``host`` GELF field. :type fqdn: bool :param localname: Use specified hostname as the ``host`` GELF field. :type localname: str or None :return: String value representing the ``host`` GELF field. :rtype: str """ if fqdn: return socket.getfqdn() elif localname is not None: return localname return socket.gethostname()
python
def _resolve_host(fqdn, localname): if fqdn: return socket.getfqdn() elif localname is not None: return localname return socket.gethostname()
[ "def", "_resolve_host", "(", "fqdn", ",", "localname", ")", ":", "if", "fqdn", ":", "return", "socket", ".", "getfqdn", "(", ")", "elif", "localname", "is", "not", "None", ":", "return", "localname", "return", "socket", ".", "gethostname", "(", ")" ]
Resolve the ``host`` GELF field :param fqdn: Boolean indicating whether to use :meth:`socket.getfqdn` to obtain the ``host`` GELF field. :type fqdn: bool :param localname: Use specified hostname as the ``host`` GELF field. :type localname: str or None :return: String value representing the ``host`` GELF field. :rtype: str
[ "Resolve", "the", "host", "GELF", "field" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L219-L236
21,324
severb/graypy
graypy/handler.py
BaseGELFHandler._add_debugging_fields
def _add_debugging_fields(gelf_dict, record): """Add debugging fields to the given ``gelf_dict`` :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract debugging fields from to insert into the given ``gelf_dict``. :type record: logging.LogRecord """ gelf_dict.update({ 'file': record.pathname, 'line': record.lineno, '_function': record.funcName, '_pid': record.process, '_thread_name': record.threadName, }) # record.processName was added in Python 2.6.2 pn = getattr(record, 'processName', None) if pn is not None: gelf_dict['_process_name'] = pn
python
def _add_debugging_fields(gelf_dict, record): gelf_dict.update({ 'file': record.pathname, 'line': record.lineno, '_function': record.funcName, '_pid': record.process, '_thread_name': record.threadName, }) # record.processName was added in Python 2.6.2 pn = getattr(record, 'processName', None) if pn is not None: gelf_dict['_process_name'] = pn
[ "def", "_add_debugging_fields", "(", "gelf_dict", ",", "record", ")", ":", "gelf_dict", ".", "update", "(", "{", "'file'", ":", "record", ".", "pathname", ",", "'line'", ":", "record", ".", "lineno", ",", "'_function'", ":", "record", ".", "funcName", ",",...
Add debugging fields to the given ``gelf_dict`` :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract debugging fields from to insert into the given ``gelf_dict``. :type record: logging.LogRecord
[ "Add", "debugging", "fields", "to", "the", "given", "gelf_dict" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L239-L259
21,325
severb/graypy
graypy/handler.py
BaseGELFHandler._add_extra_fields
def _add_extra_fields(gelf_dict, record): """Add extra fields to the given ``gelf_dict`` However, this does not add additional fields in to ``message_dict`` that are either duplicated from standard :class:`logging.LogRecord` attributes, duplicated from the python logging module source (e.g. ``exc_text``), or violate GLEF format (i.e. ``id``). .. seealso:: The list of standard :class:`logging.LogRecord` attributes can be found at: http://docs.python.org/library/logging.html#logrecord-attributes :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract extra fields from to insert into the given ``gelf_dict``. :type record: logging.LogRecord """ # skip_list is used to filter additional fields in a log message. skip_list = ( 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName') for key, value in record.__dict__.items(): if key not in skip_list and not key.startswith('_'): gelf_dict['_%s' % key] = value
python
def _add_extra_fields(gelf_dict, record): # skip_list is used to filter additional fields in a log message. skip_list = ( 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'message', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName') for key, value in record.__dict__.items(): if key not in skip_list and not key.startswith('_'): gelf_dict['_%s' % key] = value
[ "def", "_add_extra_fields", "(", "gelf_dict", ",", "record", ")", ":", "# skip_list is used to filter additional fields in a log message.", "skip_list", "=", "(", "'args'", ",", "'asctime'", ",", "'created'", ",", "'exc_info'", ",", "'exc_text'", ",", "'filename'", ",",...
Add extra fields to the given ``gelf_dict`` However, this does not add additional fields in to ``message_dict`` that are either duplicated from standard :class:`logging.LogRecord` attributes, duplicated from the python logging module source (e.g. ``exc_text``), or violate GLEF format (i.e. ``id``). .. seealso:: The list of standard :class:`logging.LogRecord` attributes can be found at: http://docs.python.org/library/logging.html#logrecord-attributes :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :param record: :class:`logging.LogRecord` to extract extra fields from to insert into the given ``gelf_dict``. :type record: logging.LogRecord
[ "Add", "extra", "fields", "to", "the", "given", "gelf_dict" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L262-L294
21,326
severb/graypy
graypy/handler.py
BaseGELFHandler._pack_gelf_dict
def _pack_gelf_dict(gelf_dict): """Convert a given ``gelf_dict`` to a JSON-encoded string, thus, creating an uncompressed GELF log ready for consumption by Graylog. Since we cannot be 100% sure of what is contained in the ``gelf_dict`` we have to do some sanitation. :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :return: A prepped JSON-encoded GELF log as a bytes string encoded in UTF-8. :rtype: bytes """ gelf_dict = BaseGELFHandler._sanitize_to_unicode(gelf_dict) packed = json.dumps( gelf_dict, separators=',:', default=BaseGELFHandler._object_to_json ) return packed.encode('utf-8')
python
def _pack_gelf_dict(gelf_dict): gelf_dict = BaseGELFHandler._sanitize_to_unicode(gelf_dict) packed = json.dumps( gelf_dict, separators=',:', default=BaseGELFHandler._object_to_json ) return packed.encode('utf-8')
[ "def", "_pack_gelf_dict", "(", "gelf_dict", ")", ":", "gelf_dict", "=", "BaseGELFHandler", ".", "_sanitize_to_unicode", "(", "gelf_dict", ")", "packed", "=", "json", ".", "dumps", "(", "gelf_dict", ",", "separators", "=", "',:'", ",", "default", "=", "BaseGELF...
Convert a given ``gelf_dict`` to a JSON-encoded string, thus, creating an uncompressed GELF log ready for consumption by Graylog. Since we cannot be 100% sure of what is contained in the ``gelf_dict`` we have to do some sanitation. :param gelf_dict: dictionary representation of a GELF log. :type gelf_dict: dict :return: A prepped JSON-encoded GELF log as a bytes string encoded in UTF-8. :rtype: bytes
[ "Convert", "a", "given", "gelf_dict", "to", "a", "JSON", "-", "encoded", "string", "thus", "creating", "an", "uncompressed", "GELF", "log", "ready", "for", "consumption", "by", "Graylog", "." ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L297-L317
21,327
severb/graypy
graypy/handler.py
BaseGELFHandler._sanitize_to_unicode
def _sanitize_to_unicode(obj): """Convert all strings records of the object to unicode :param obj: object to sanitize to unicode. :type obj: object :return: Unicode string representation of the given object. :rtype: str """ if isinstance(obj, dict): return dict((BaseGELFHandler._sanitize_to_unicode(k), BaseGELFHandler._sanitize_to_unicode(v)) for k, v in obj.items()) if isinstance(obj, (list, tuple)): return obj.__class__([BaseGELFHandler._sanitize_to_unicode(i) for i in obj]) if isinstance(obj, data): obj = obj.decode('utf-8', errors='replace') return obj
python
def _sanitize_to_unicode(obj): if isinstance(obj, dict): return dict((BaseGELFHandler._sanitize_to_unicode(k), BaseGELFHandler._sanitize_to_unicode(v)) for k, v in obj.items()) if isinstance(obj, (list, tuple)): return obj.__class__([BaseGELFHandler._sanitize_to_unicode(i) for i in obj]) if isinstance(obj, data): obj = obj.decode('utf-8', errors='replace') return obj
[ "def", "_sanitize_to_unicode", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "dict", "(", "(", "BaseGELFHandler", ".", "_sanitize_to_unicode", "(", "k", ")", ",", "BaseGELFHandler", ".", "_sanitize_to_unicode", "(", "...
Convert all strings records of the object to unicode :param obj: object to sanitize to unicode. :type obj: object :return: Unicode string representation of the given object. :rtype: str
[ "Convert", "all", "strings", "records", "of", "the", "object", "to", "unicode" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L320-L335
21,328
severb/graypy
graypy/handler.py
BaseGELFHandler._object_to_json
def _object_to_json(obj): """Convert objects that cannot be natively serialized into JSON into their string representation For datetime based objects convert them into their ISO formatted string as specified by :meth:`datetime.datetime.isoformat`. :param obj: object to convert into a JSON via getting its string representation. :type obj: object :return: String value representing the given object ready to be encoded into a JSON. :rtype: str """ if isinstance(obj, datetime.datetime): return obj.isoformat() return repr(obj)
python
def _object_to_json(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return repr(obj)
[ "def", "_object_to_json", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "return", "repr", "(", "obj", ")" ]
Convert objects that cannot be natively serialized into JSON into their string representation For datetime based objects convert them into their ISO formatted string as specified by :meth:`datetime.datetime.isoformat`. :param obj: object to convert into a JSON via getting its string representation. :type obj: object :return: String value representing the given object ready to be encoded into a JSON. :rtype: str
[ "Convert", "objects", "that", "cannot", "be", "natively", "serialized", "into", "JSON", "into", "their", "string", "representation" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L338-L355
21,329
severb/graypy
graypy/handler.py
GELFTLSHandler.makeSocket
def makeSocket(self, timeout=1): """Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets""" plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(plain_socket, 'settimeout'): plain_socket.settimeout(timeout) wrapped_socket = ssl.wrap_socket( plain_socket, ca_certs=self.ca_certs, cert_reqs=self.reqs, keyfile=self.keyfile, certfile=self.certfile ) wrapped_socket.connect((self.host, self.port)) return wrapped_socket
python
def makeSocket(self, timeout=1): plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(plain_socket, 'settimeout'): plain_socket.settimeout(timeout) wrapped_socket = ssl.wrap_socket( plain_socket, ca_certs=self.ca_certs, cert_reqs=self.reqs, keyfile=self.keyfile, certfile=self.certfile ) wrapped_socket.connect((self.host, self.port)) return wrapped_socket
[ "def", "makeSocket", "(", "self", ",", "timeout", "=", "1", ")", ":", "plain_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "if", "hasattr", "(", "plain_socket", ",", "'settimeout'", ")", ":"...
Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets
[ "Override", "SocketHandler", ".", "makeSocket", "to", "allow", "creating", "wrapped", "TLS", "sockets" ]
32018c41a792e71a8de9f9e14f770d1bc60c2313
https://github.com/severb/graypy/blob/32018c41a792e71a8de9f9e14f770d1bc60c2313/graypy/handler.py#L451-L468
21,330
codeinthehole/purl
purl/url.py
to_unicode
def to_unicode(string): """ Ensure a passed string is unicode """ if isinstance(string, six.binary_type): return string.decode('utf8') if isinstance(string, six.text_type): return string if six.PY2: return unicode(string) return str(string)
python
def to_unicode(string): if isinstance(string, six.binary_type): return string.decode('utf8') if isinstance(string, six.text_type): return string if six.PY2: return unicode(string) return str(string)
[ "def", "to_unicode", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "six", ".", "binary_type", ")", ":", "return", "string", ".", "decode", "(", "'utf8'", ")", "if", "isinstance", "(", "string", ",", "six", ".", "text_type", ")", ":",...
Ensure a passed string is unicode
[ "Ensure", "a", "passed", "string", "is", "unicode" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L22-L32
21,331
codeinthehole/purl
purl/url.py
to_utf8
def to_utf8(string): """ Encode a string as a UTF8 bytestring. This function could be passed a bytestring or unicode string so must distinguish between the two. """ if isinstance(string, six.text_type): return string.encode('utf8') if isinstance(string, six.binary_type): return string return str(string)
python
def to_utf8(string): if isinstance(string, six.text_type): return string.encode('utf8') if isinstance(string, six.binary_type): return string return str(string)
[ "def", "to_utf8", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "six", ".", "text_type", ")", ":", "return", "string", ".", "encode", "(", "'utf8'", ")", "if", "isinstance", "(", "string", ",", "six", ".", "binary_type", ")", ":", ...
Encode a string as a UTF8 bytestring. This function could be passed a bytestring or unicode string so must distinguish between the two.
[ "Encode", "a", "string", "as", "a", "UTF8", "bytestring", ".", "This", "function", "could", "be", "passed", "a", "bytestring", "or", "unicode", "string", "so", "must", "distinguish", "between", "the", "two", "." ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L35-L44
21,332
codeinthehole/purl
purl/url.py
dict_to_unicode
def dict_to_unicode(raw_dict): """ Ensure all keys and values in a dict are unicode. The passed dict is assumed to have lists for all values. """ decoded = {} for key, value in raw_dict.items(): decoded[to_unicode(key)] = map( to_unicode, value) return decoded
python
def dict_to_unicode(raw_dict): decoded = {} for key, value in raw_dict.items(): decoded[to_unicode(key)] = map( to_unicode, value) return decoded
[ "def", "dict_to_unicode", "(", "raw_dict", ")", ":", "decoded", "=", "{", "}", "for", "key", ",", "value", "in", "raw_dict", ".", "items", "(", ")", ":", "decoded", "[", "to_unicode", "(", "key", ")", "]", "=", "map", "(", "to_unicode", ",", "value",...
Ensure all keys and values in a dict are unicode. The passed dict is assumed to have lists for all values.
[ "Ensure", "all", "keys", "and", "values", "in", "a", "dict", "are", "unicode", "." ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L47-L57
21,333
codeinthehole/purl
purl/url.py
unicode_urlencode
def unicode_urlencode(query, doseq=True): """ Custom wrapper around urlencode to support unicode Python urlencode doesn't handle unicode well so we need to convert to bytestrings before using it: http://stackoverflow.com/questions/6480723/urllib-urlencode-doesnt-like-unicode-values-how-about-this-workaround """ pairs = [] for key, value in query.items(): if isinstance(value, list): value = list(map(to_utf8, value)) else: value = to_utf8(value) pairs.append((to_utf8(key), value)) encoded_query = dict(pairs) xx = urlencode(encoded_query, doseq) return xx
python
def unicode_urlencode(query, doseq=True): pairs = [] for key, value in query.items(): if isinstance(value, list): value = list(map(to_utf8, value)) else: value = to_utf8(value) pairs.append((to_utf8(key), value)) encoded_query = dict(pairs) xx = urlencode(encoded_query, doseq) return xx
[ "def", "unicode_urlencode", "(", "query", ",", "doseq", "=", "True", ")", ":", "pairs", "=", "[", "]", "for", "key", ",", "value", "in", "query", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", ...
Custom wrapper around urlencode to support unicode Python urlencode doesn't handle unicode well so we need to convert to bytestrings before using it: http://stackoverflow.com/questions/6480723/urllib-urlencode-doesnt-like-unicode-values-how-about-this-workaround
[ "Custom", "wrapper", "around", "urlencode", "to", "support", "unicode" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L80-L97
21,334
codeinthehole/purl
purl/url.py
parse
def parse(url_str): """ Extract all parts from a URL string and return them as a dictionary """ url_str = to_unicode(url_str) result = urlparse(url_str) netloc_parts = result.netloc.rsplit('@', 1) if len(netloc_parts) == 1: username = password = None host = netloc_parts[0] else: user_and_pass = netloc_parts[0].split(':') if len(user_and_pass) == 2: username, password = user_and_pass elif len(user_and_pass) == 1: username = user_and_pass[0] password = None host = netloc_parts[1] if host and ':' in host: host = host.split(':')[0] return {'host': host, 'username': username, 'password': password, 'scheme': result.scheme, 'port': result.port, 'path': result.path, 'query': result.query, 'fragment': result.fragment}
python
def parse(url_str): url_str = to_unicode(url_str) result = urlparse(url_str) netloc_parts = result.netloc.rsplit('@', 1) if len(netloc_parts) == 1: username = password = None host = netloc_parts[0] else: user_and_pass = netloc_parts[0].split(':') if len(user_and_pass) == 2: username, password = user_and_pass elif len(user_and_pass) == 1: username = user_and_pass[0] password = None host = netloc_parts[1] if host and ':' in host: host = host.split(':')[0] return {'host': host, 'username': username, 'password': password, 'scheme': result.scheme, 'port': result.port, 'path': result.path, 'query': result.query, 'fragment': result.fragment}
[ "def", "parse", "(", "url_str", ")", ":", "url_str", "=", "to_unicode", "(", "url_str", ")", "result", "=", "urlparse", "(", "url_str", ")", "netloc_parts", "=", "result", ".", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "if", "len", "(", "ne...
Extract all parts from a URL string and return them as a dictionary
[ "Extract", "all", "parts", "from", "a", "URL", "string", "and", "return", "them", "as", "a", "dictionary" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L100-L129
21,335
codeinthehole/purl
purl/url.py
URL.netloc
def netloc(self): """ Return the netloc """ url = self._tuple if url.username and url.password: netloc = '%s:%s@%s' % (url.username, url.password, url.host) elif url.username and not url.password: netloc = '%s@%s' % (url.username, url.host) else: netloc = url.host if url.port: netloc = '%s:%s' % (netloc, url.port) return netloc
python
def netloc(self): url = self._tuple if url.username and url.password: netloc = '%s:%s@%s' % (url.username, url.password, url.host) elif url.username and not url.password: netloc = '%s@%s' % (url.username, url.host) else: netloc = url.host if url.port: netloc = '%s:%s' % (netloc, url.port) return netloc
[ "def", "netloc", "(", "self", ")", ":", "url", "=", "self", ".", "_tuple", "if", "url", ".", "username", "and", "url", ".", "password", ":", "netloc", "=", "'%s:%s@%s'", "%", "(", "url", ".", "username", ",", "url", ".", "password", ",", "url", "."...
Return the netloc
[ "Return", "the", "netloc" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L221-L234
21,336
codeinthehole/purl
purl/url.py
URL.host
def host(self, value=None): """ Return the host :param string value: new host string """ if value is not None: return URL._mutate(self, host=value) return self._tuple.host
python
def host(self, value=None): if value is not None: return URL._mutate(self, host=value) return self._tuple.host
[ "def", "host", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "host", "=", "value", ")", "return", "self", ".", "_tuple", ".", "host" ]
Return the host :param string value: new host string
[ "Return", "the", "host" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L236-L244
21,337
codeinthehole/purl
purl/url.py
URL.username
def username(self, value=None): """ Return or set the username :param string value: the new username to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, username=value) return unicode_unquote(self._tuple.username)
python
def username(self, value=None): if value is not None: return URL._mutate(self, username=value) return unicode_unquote(self._tuple.username)
[ "def", "username", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "username", "=", "value", ")", "return", "unicode_unquote", "(", "self", ".", "_tuple", "...
Return or set the username :param string value: the new username to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "username" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L248-L257
21,338
codeinthehole/purl
purl/url.py
URL.password
def password(self, value=None): """ Return or set the password :param string value: the new password to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, password=value) return unicode_unquote(self._tuple.password)
python
def password(self, value=None): if value is not None: return URL._mutate(self, password=value) return unicode_unquote(self._tuple.password)
[ "def", "password", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "password", "=", "value", ")", "return", "unicode_unquote", "(", "self", ".", "_tuple", "...
Return or set the password :param string value: the new password to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "password" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L259-L268
21,339
codeinthehole/purl
purl/url.py
URL.scheme
def scheme(self, value=None): """ Return or set the scheme. :param string value: the new scheme to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, scheme=value) return self._tuple.scheme
python
def scheme(self, value=None): if value is not None: return URL._mutate(self, scheme=value) return self._tuple.scheme
[ "def", "scheme", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "scheme", "=", "value", ")", "return", "self", ".", "_tuple", ".", "scheme" ]
Return or set the scheme. :param string value: the new scheme to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "scheme", "." ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L295-L304
21,340
codeinthehole/purl
purl/url.py
URL.path
def path(self, value=None): """ Return or set the path :param string value: the new path to use :returns: string or new :class:`URL` instance """ if value is not None: if not value.startswith('/'): value = '/' + value encoded_value = unicode_quote(value) return URL._mutate(self, path=encoded_value) return self._tuple.path
python
def path(self, value=None): if value is not None: if not value.startswith('/'): value = '/' + value encoded_value = unicode_quote(value) return URL._mutate(self, path=encoded_value) return self._tuple.path
[ "def", "path", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "if", "not", "value", ".", "startswith", "(", "'/'", ")", ":", "value", "=", "'/'", "+", "value", "encoded_value", "=", "unicode_quote", "(", ...
Return or set the path :param string value: the new path to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "path" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L306-L318
21,341
codeinthehole/purl
purl/url.py
URL.query
def query(self, value=None): """ Return or set the query string :param string value: the new query string to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, query=value) return self._tuple.query
python
def query(self, value=None): if value is not None: return URL._mutate(self, query=value) return self._tuple.query
[ "def", "query", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "query", "=", "value", ")", "return", "self", ".", "_tuple", ".", "query" ]
Return or set the query string :param string value: the new query string to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "query", "string" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L320-L329
21,342
codeinthehole/purl
purl/url.py
URL.port
def port(self, value=None): """ Return or set the port :param string value: the new port to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, port=value) return self._tuple.port
python
def port(self, value=None): if value is not None: return URL._mutate(self, port=value) return self._tuple.port
[ "def", "port", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "port", "=", "value", ")", "return", "self", ".", "_tuple", ".", "port" ]
Return or set the port :param string value: the new port to use :returns: string or new :class:`URL` instance
[ "Return", "or", "set", "the", "port" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L331-L340
21,343
codeinthehole/purl
purl/url.py
URL.path_segment
def path_segment(self, index, value=None, default=None): """ Return the path segment at the given index :param integer index: :param string value: the new segment value :param string default: the default value to return if no path segment exists with the given index """ if value is not None: segments = list(self.path_segments()) segments[index] = unicode_quote_path_segment(value) new_path = '/' + '/'.join(segments) if self._tuple.path.endswith('/'): new_path += '/' return URL._mutate(self, path=new_path) try: return self.path_segments()[index] except IndexError: return default
python
def path_segment(self, index, value=None, default=None): if value is not None: segments = list(self.path_segments()) segments[index] = unicode_quote_path_segment(value) new_path = '/' + '/'.join(segments) if self._tuple.path.endswith('/'): new_path += '/' return URL._mutate(self, path=new_path) try: return self.path_segments()[index] except IndexError: return default
[ "def", "path_segment", "(", "self", ",", "index", ",", "value", "=", "None", ",", "default", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "segments", "=", "list", "(", "self", ".", "path_segments", "(", ")", ")", "segments", "[", ...
Return the path segment at the given index :param integer index: :param string value: the new segment value :param string default: the default value to return if no path segment exists with the given index
[ "Return", "the", "path", "segment", "at", "the", "given", "index" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L365-L383
21,344
codeinthehole/purl
purl/url.py
URL.path_segments
def path_segments(self, value=None): """ Return the path segments :param list value: the new path segments to use """ if value is not None: encoded_values = map(unicode_quote_path_segment, value) new_path = '/' + '/'.join(encoded_values) return URL._mutate(self, path=new_path) parts = self._tuple.path.split('/') segments = parts[1:] if self._tuple.path.endswith('/'): segments.pop() segments = map(unicode_unquote, segments) return tuple(segments)
python
def path_segments(self, value=None): if value is not None: encoded_values = map(unicode_quote_path_segment, value) new_path = '/' + '/'.join(encoded_values) return URL._mutate(self, path=new_path) parts = self._tuple.path.split('/') segments = parts[1:] if self._tuple.path.endswith('/'): segments.pop() segments = map(unicode_unquote, segments) return tuple(segments)
[ "def", "path_segments", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "encoded_values", "=", "map", "(", "unicode_quote_path_segment", ",", "value", ")", "new_path", "=", "'/'", "+", "'/'", ".", "join", "(", ...
Return the path segments :param list value: the new path segments to use
[ "Return", "the", "path", "segments" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L385-L400
21,345
codeinthehole/purl
purl/url.py
URL.add_path_segment
def add_path_segment(self, value): """ Add a new path segment to the end of the current string :param string value: the new path segment to use Example:: >>> u = URL('http://example.com/foo/') >>> u.add_path_segment('bar').as_string() 'http://example.com/foo/bar' """ segments = self.path_segments() + (to_unicode(value),) return self.path_segments(segments)
python
def add_path_segment(self, value): segments = self.path_segments() + (to_unicode(value),) return self.path_segments(segments)
[ "def", "add_path_segment", "(", "self", ",", "value", ")", ":", "segments", "=", "self", ".", "path_segments", "(", ")", "+", "(", "to_unicode", "(", "value", ")", ",", ")", "return", "self", ".", "path_segments", "(", "segments", ")" ]
Add a new path segment to the end of the current string :param string value: the new path segment to use Example:: >>> u = URL('http://example.com/foo/') >>> u.add_path_segment('bar').as_string() 'http://example.com/foo/bar'
[ "Add", "a", "new", "path", "segment", "to", "the", "end", "of", "the", "current", "string" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L402-L415
21,346
codeinthehole/purl
purl/url.py
URL.query_param
def query_param(self, key, value=None, default=None, as_list=False): """ Return or set a query parameter for the given key The value can be a list. :param string key: key to look for :param string default: value to return if ``key`` isn't found :param boolean as_list: whether to return the values as a list :param string value: the new query parameter to use """ parse_result = self.query_params() if value is not None: # Need to ensure all strings are unicode if isinstance(value, (list, tuple)): value = list(map(to_unicode, value)) else: value = to_unicode(value) parse_result[to_unicode(key)] = value return URL._mutate( self, query=unicode_urlencode(parse_result, doseq=True)) try: result = parse_result[key] except KeyError: return default if as_list: return result return result[0] if len(result) == 1 else result
python
def query_param(self, key, value=None, default=None, as_list=False): parse_result = self.query_params() if value is not None: # Need to ensure all strings are unicode if isinstance(value, (list, tuple)): value = list(map(to_unicode, value)) else: value = to_unicode(value) parse_result[to_unicode(key)] = value return URL._mutate( self, query=unicode_urlencode(parse_result, doseq=True)) try: result = parse_result[key] except KeyError: return default if as_list: return result return result[0] if len(result) == 1 else result
[ "def", "query_param", "(", "self", ",", "key", ",", "value", "=", "None", ",", "default", "=", "None", ",", "as_list", "=", "False", ")", ":", "parse_result", "=", "self", ".", "query_params", "(", ")", "if", "value", "is", "not", "None", ":", "# Nee...
Return or set a query parameter for the given key The value can be a list. :param string key: key to look for :param string default: value to return if ``key`` isn't found :param boolean as_list: whether to return the values as a list :param string value: the new query parameter to use
[ "Return", "or", "set", "a", "query", "parameter", "for", "the", "given", "key" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L437-L465
21,347
codeinthehole/purl
purl/url.py
URL.append_query_param
def append_query_param(self, key, value): """ Append a query parameter :param string key: The query param key :param string value: The new value """ values = self.query_param(key, as_list=True, default=[]) values.append(value) return self.query_param(key, values)
python
def append_query_param(self, key, value): values = self.query_param(key, as_list=True, default=[]) values.append(value) return self.query_param(key, values)
[ "def", "append_query_param", "(", "self", ",", "key", ",", "value", ")", ":", "values", "=", "self", ".", "query_param", "(", "key", ",", "as_list", "=", "True", ",", "default", "=", "[", "]", ")", "values", ".", "append", "(", "value", ")", "return"...
Append a query parameter :param string key: The query param key :param string value: The new value
[ "Append", "a", "query", "parameter" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L467-L476
21,348
codeinthehole/purl
purl/url.py
URL.query_params
def query_params(self, value=None): """ Return or set a dictionary of query params :param dict value: new dictionary of values """ if value is not None: return URL._mutate(self, query=unicode_urlencode(value, doseq=True)) query = '' if self._tuple.query is None else self._tuple.query # In Python 2.6, urlparse needs a bytestring so we encode and then # decode the result. if not six.PY3: result = parse_qs(to_utf8(query), True) return dict_to_unicode(result) return parse_qs(query, True)
python
def query_params(self, value=None): if value is not None: return URL._mutate(self, query=unicode_urlencode(value, doseq=True)) query = '' if self._tuple.query is None else self._tuple.query # In Python 2.6, urlparse needs a bytestring so we encode and then # decode the result. if not six.PY3: result = parse_qs(to_utf8(query), True) return dict_to_unicode(result) return parse_qs(query, True)
[ "def", "query_params", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "return", "URL", ".", "_mutate", "(", "self", ",", "query", "=", "unicode_urlencode", "(", "value", ",", "doseq", "=", "True", ")", ")",...
Return or set a dictionary of query params :param dict value: new dictionary of values
[ "Return", "or", "set", "a", "dictionary", "of", "query", "params" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L478-L494
21,349
codeinthehole/purl
purl/url.py
URL.remove_query_param
def remove_query_param(self, key, value=None): """ Remove a query param from a URL Set the value parameter if removing from a list. :param string key: The key to delete :param string value: The value of the param to delete (of more than one) """ parse_result = self.query_params() if value is not None: index = parse_result[key].index(value) del parse_result[key][index] else: del parse_result[key] return URL._mutate(self, query=unicode_urlencode(parse_result, doseq=True))
python
def remove_query_param(self, key, value=None): parse_result = self.query_params() if value is not None: index = parse_result[key].index(value) del parse_result[key][index] else: del parse_result[key] return URL._mutate(self, query=unicode_urlencode(parse_result, doseq=True))
[ "def", "remove_query_param", "(", "self", ",", "key", ",", "value", "=", "None", ")", ":", "parse_result", "=", "self", ".", "query_params", "(", ")", "if", "value", "is", "not", "None", ":", "index", "=", "parse_result", "[", "key", "]", ".", "index",...
Remove a query param from a URL Set the value parameter if removing from a list. :param string key: The key to delete :param string value: The value of the param to delete (of more than one)
[ "Remove", "a", "query", "param", "from", "a", "URL" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L496-L511
21,350
codeinthehole/purl
purl/template.py
expand
def expand(template, variables=None): """ Expand a URL template string using the passed variables """ if variables is None: variables = {} return patterns.sub(functools.partial(_replace, variables), template)
python
def expand(template, variables=None): if variables is None: variables = {} return patterns.sub(functools.partial(_replace, variables), template)
[ "def", "expand", "(", "template", ",", "variables", "=", "None", ")", ":", "if", "variables", "is", "None", ":", "variables", "=", "{", "}", "return", "patterns", ".", "sub", "(", "functools", ".", "partial", "(", "_replace", ",", "variables", ")", ","...
Expand a URL template string using the passed variables
[ "Expand", "a", "URL", "template", "string", "using", "the", "passed", "variables" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L31-L37
21,351
codeinthehole/purl
purl/template.py
_format_pair_no_equals
def _format_pair_no_equals(explode, separator, escape, key, value): """ Format a key, value pair but don't include the equals sign when there is no value """ if not value: return key return _format_pair(explode, separator, escape, key, value)
python
def _format_pair_no_equals(explode, separator, escape, key, value): if not value: return key return _format_pair(explode, separator, escape, key, value)
[ "def", "_format_pair_no_equals", "(", "explode", ",", "separator", ",", "escape", ",", "key", ",", "value", ")", ":", "if", "not", "value", ":", "return", "key", "return", "_format_pair", "(", "explode", ",", "separator", ",", "escape", ",", "key", ",", ...
Format a key, value pair but don't include the equals sign when there is no value
[ "Format", "a", "key", "value", "pair", "but", "don", "t", "include", "the", "equals", "sign", "when", "there", "is", "no", "value" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L56-L63
21,352
codeinthehole/purl
purl/template.py
_format_pair_with_equals
def _format_pair_with_equals(explode, separator, escape, key, value): """ Format a key, value pair including the equals sign when there is no value """ if not value: return key + '=' return _format_pair(explode, separator, escape, key, value)
python
def _format_pair_with_equals(explode, separator, escape, key, value): if not value: return key + '=' return _format_pair(explode, separator, escape, key, value)
[ "def", "_format_pair_with_equals", "(", "explode", ",", "separator", ",", "escape", ",", "key", ",", "value", ")", ":", "if", "not", "value", ":", "return", "key", "+", "'='", "return", "_format_pair", "(", "explode", ",", "separator", ",", "escape", ",", ...
Format a key, value pair including the equals sign when there is no value
[ "Format", "a", "key", "value", "pair", "including", "the", "equals", "sign", "when", "there", "is", "no", "value" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L66-L73
21,353
codeinthehole/purl
purl/template.py
_replace
def _replace(variables, match): """ Return the appropriate replacement for `match` using the passed variables """ expression = match.group(1) # Look-up chars and functions for the specified operator (prefix_char, separator_char, split_fn, escape_fn, format_fn) = operator_map.get(expression[0], defaults) replacements = [] for key, modify_fn, explode in split_fn(expression): if key in variables: variable = modify_fn(variables[key]) replacement = format_fn( explode, separator_char, escape_fn, key, variable) replacements.append(replacement) if not replacements: return '' return prefix_char + separator_char.join(replacements)
python
def _replace(variables, match): expression = match.group(1) # Look-up chars and functions for the specified operator (prefix_char, separator_char, split_fn, escape_fn, format_fn) = operator_map.get(expression[0], defaults) replacements = [] for key, modify_fn, explode in split_fn(expression): if key in variables: variable = modify_fn(variables[key]) replacement = format_fn( explode, separator_char, escape_fn, key, variable) replacements.append(replacement) if not replacements: return '' return prefix_char + separator_char.join(replacements)
[ "def", "_replace", "(", "variables", ",", "match", ")", ":", "expression", "=", "match", ".", "group", "(", "1", ")", "# Look-up chars and functions for the specified operator", "(", "prefix_char", ",", "separator_char", ",", "split_fn", ",", "escape_fn", ",", "fo...
Return the appropriate replacement for `match` using the passed variables
[ "Return", "the", "appropriate", "replacement", "for", "match", "using", "the", "passed", "variables" ]
e70ed132f1fdc17d00c78199cedb1e3adcb2bc55
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L195-L214
21,354
LucidtechAI/las-sdk-python
las/api_client.py
ApiClient.predict
def predict(self, document_path: str, model_name: str, consent_id: str = None) -> Prediction: """Run inference and create prediction on document. This method takes care of creating and uploading a document specified by document_path. as well as running inference using model specified by model_name to create prediction on the document. >>> from las import ApiClient >>> api_client = ApiClient(endpoint='<api endpoint>') >>> api_client.predict(document_path='document.jpeg', model_name='invoice') :param document_path: Path to document to run inference on :type document_path: str :param model_name: The name of the model to use for inference :type model_name: str :param consent_id: An identifier to mark the owner of the document handle :type consent_id: str :return: Prediction on document :rtype: Prediction :raises InvalidCredentialsException: If the credentials are invalid :raises TooManyRequestsException: If limit of requests per second is reached :raises LimitExceededException: If limit of total requests per month is reached :raises requests.exception.RequestException: If error was raised by requests """ content_type = self._get_content_type(document_path) consent_id = consent_id or str(uuid4()) document_id = self._upload_document(document_path, content_type, consent_id) prediction_response = self.post_predictions(document_id, model_name) return Prediction(document_id, consent_id, model_name, prediction_response)
python
def predict(self, document_path: str, model_name: str, consent_id: str = None) -> Prediction: content_type = self._get_content_type(document_path) consent_id = consent_id or str(uuid4()) document_id = self._upload_document(document_path, content_type, consent_id) prediction_response = self.post_predictions(document_id, model_name) return Prediction(document_id, consent_id, model_name, prediction_response)
[ "def", "predict", "(", "self", ",", "document_path", ":", "str", ",", "model_name", ":", "str", ",", "consent_id", ":", "str", "=", "None", ")", "->", "Prediction", ":", "content_type", "=", "self", ".", "_get_content_type", "(", "document_path", ")", "con...
Run inference and create prediction on document. This method takes care of creating and uploading a document specified by document_path. as well as running inference using model specified by model_name to create prediction on the document. >>> from las import ApiClient >>> api_client = ApiClient(endpoint='<api endpoint>') >>> api_client.predict(document_path='document.jpeg', model_name='invoice') :param document_path: Path to document to run inference on :type document_path: str :param model_name: The name of the model to use for inference :type model_name: str :param consent_id: An identifier to mark the owner of the document handle :type consent_id: str :return: Prediction on document :rtype: Prediction :raises InvalidCredentialsException: If the credentials are invalid :raises TooManyRequestsException: If limit of requests per second is reached :raises LimitExceededException: If limit of total requests per month is reached :raises requests.exception.RequestException: If error was raised by requests
[ "Run", "inference", "and", "create", "prediction", "on", "document", ".", "This", "method", "takes", "care", "of", "creating", "and", "uploading", "a", "document", "specified", "by", "document_path", ".", "as", "well", "as", "running", "inference", "using", "m...
5f39dee7983baff28a1deb93c12d36414d835d12
https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/api_client.py#L30-L57
21,355
LucidtechAI/las-sdk-python
las/api_client.py
ApiClient.send_feedback
def send_feedback(self, document_id: str, feedback: List[Field]) -> dict: """Send feedback to the model. This method takes care of sending feedback related to document specified by document_id. Feedback consists of ground truth values for the document specified as a list of Field instances. >>> from las import ApiClient >>> api_client = ApiClient(endpoint='<api endpoint>') >>> feedback = [Field(label='total_amount', value='120.00'), Field(label='purchase_date', value='2019-03-10')] >>> api_client.send_feedback('<document id>', feedback) :param document_id: The document id of the document that will receive the feedback :type document_id: str :param feedback: A list of :py:class:`~las.Field` representing the ground truth values for the document :type feedback: List[Field] :return: Feedback response :rtype: dict :raises InvalidCredentialsException: If the credentials are invalid :raises TooManyRequestsException: If limit of requests per second is reached :raises LimitExceededException: If limit of total requests per month is reached :raises requests.exception.RequestException: If error was raised by requests """ return self.post_document_id(document_id, feedback)
python
def send_feedback(self, document_id: str, feedback: List[Field]) -> dict: return self.post_document_id(document_id, feedback)
[ "def", "send_feedback", "(", "self", ",", "document_id", ":", "str", ",", "feedback", ":", "List", "[", "Field", "]", ")", "->", "dict", ":", "return", "self", ".", "post_document_id", "(", "document_id", ",", "feedback", ")" ]
Send feedback to the model. This method takes care of sending feedback related to document specified by document_id. Feedback consists of ground truth values for the document specified as a list of Field instances. >>> from las import ApiClient >>> api_client = ApiClient(endpoint='<api endpoint>') >>> feedback = [Field(label='total_amount', value='120.00'), Field(label='purchase_date', value='2019-03-10')] >>> api_client.send_feedback('<document id>', feedback) :param document_id: The document id of the document that will receive the feedback :type document_id: str :param feedback: A list of :py:class:`~las.Field` representing the ground truth values for the document :type feedback: List[Field] :return: Feedback response :rtype: dict :raises InvalidCredentialsException: If the credentials are invalid :raises TooManyRequestsException: If limit of requests per second is reached :raises LimitExceededException: If limit of total requests per month is reached :raises requests.exception.RequestException: If error was raised by requests
[ "Send", "feedback", "to", "the", "model", ".", "This", "method", "takes", "care", "of", "sending", "feedback", "related", "to", "document", "specified", "by", "document_id", ".", "Feedback", "consists", "of", "ground", "truth", "values", "for", "the", "documen...
5f39dee7983baff28a1deb93c12d36414d835d12
https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/api_client.py#L59-L81
21,356
LucidtechAI/las-sdk-python
las/_extrahdr.py
extra_what
def extra_what(file, h=None): """Code mostly copied from imghdr.what""" tests = [] def test_pdf(h, f): if b'PDF' in h[0:10]: return 'pdf' tests.append(test_pdf) f = None try: if h is None: if isinstance(file, (str, PathLike)): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) for tf in tests: res = tf(h, f) if res: return res finally: if f: f.close() return None
python
def extra_what(file, h=None): tests = [] def test_pdf(h, f): if b'PDF' in h[0:10]: return 'pdf' tests.append(test_pdf) f = None try: if h is None: if isinstance(file, (str, PathLike)): f = open(file, 'rb') h = f.read(32) else: location = file.tell() h = file.read(32) file.seek(location) for tf in tests: res = tf(h, f) if res: return res finally: if f: f.close() return None
[ "def", "extra_what", "(", "file", ",", "h", "=", "None", ")", ":", "tests", "=", "[", "]", "def", "test_pdf", "(", "h", ",", "f", ")", ":", "if", "b'PDF'", "in", "h", "[", "0", ":", "10", "]", ":", "return", "'pdf'", "tests", ".", "append", "...
Code mostly copied from imghdr.what
[ "Code", "mostly", "copied", "from", "imghdr", ".", "what" ]
5f39dee7983baff28a1deb93c12d36414d835d12
https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/_extrahdr.py#L4-L31
21,357
LucidtechAI/las-sdk-python
las/client.py
Client.put_document
def put_document(document_path: str, content_type: str, presigned_url: str) -> str: """Convenience method for putting a document to presigned url. >>> from las import Client >>> client = Client(endpoint='<api endpoint>') >>> client.put_document(document_path='document.jpeg', content_type='image/jpeg', >>> presigned_url='<presigned url>') :param document_path: Path to document to upload :type document_path: str :param content_type: Mime type of document to upload. Same as provided to :py:func:`~las.Client.post_documents` :type content_type: str :param presigned_url: Presigned upload url from :py:func:`~las.Client.post_documents` :type presigned_url: str :return: Response from put operation :rtype: str :raises requests.exception.RequestException: If error was raised by requests """ body = pathlib.Path(document_path).read_bytes() headers = {'Content-Type': content_type} put_document_response = requests.put(presigned_url, data=body, headers=headers) put_document_response.raise_for_status() return put_document_response.content.decode()
python
def put_document(document_path: str, content_type: str, presigned_url: str) -> str: body = pathlib.Path(document_path).read_bytes() headers = {'Content-Type': content_type} put_document_response = requests.put(presigned_url, data=body, headers=headers) put_document_response.raise_for_status() return put_document_response.content.decode()
[ "def", "put_document", "(", "document_path", ":", "str", ",", "content_type", ":", "str", ",", "presigned_url", ":", "str", ")", "->", "str", ":", "body", "=", "pathlib", ".", "Path", "(", "document_path", ")", ".", "read_bytes", "(", ")", "headers", "="...
Convenience method for putting a document to presigned url. >>> from las import Client >>> client = Client(endpoint='<api endpoint>') >>> client.put_document(document_path='document.jpeg', content_type='image/jpeg', >>> presigned_url='<presigned url>') :param document_path: Path to document to upload :type document_path: str :param content_type: Mime type of document to upload. Same as provided to :py:func:`~las.Client.post_documents` :type content_type: str :param presigned_url: Presigned upload url from :py:func:`~las.Client.post_documents` :type presigned_url: str :return: Response from put operation :rtype: str :raises requests.exception.RequestException: If error was raised by requests
[ "Convenience", "method", "for", "putting", "a", "document", "to", "presigned", "url", "." ]
5f39dee7983baff28a1deb93c12d36414d835d12
https://github.com/LucidtechAI/las-sdk-python/blob/5f39dee7983baff28a1deb93c12d36414d835d12/las/client.py#L117-L140
21,358
owncloud/pyocclient
owncloud/owncloud.py
ShareInfo.get_expiration
def get_expiration(self): """Returns the expiration date. :returns: expiration date :rtype: datetime object """ exp = self._get_int('expiration') if exp is not None: return datetime.datetime.fromtimestamp( exp ) return None
python
def get_expiration(self): exp = self._get_int('expiration') if exp is not None: return datetime.datetime.fromtimestamp( exp ) return None
[ "def", "get_expiration", "(", "self", ")", ":", "exp", "=", "self", ".", "_get_int", "(", "'expiration'", ")", "if", "exp", "is", "not", "None", ":", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "exp", ")", "return", "None" ]
Returns the expiration date. :returns: expiration date :rtype: datetime object
[ "Returns", "the", "expiration", "date", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L140-L151
21,359
owncloud/pyocclient
owncloud/owncloud.py
Client.login
def login(self, user_id, password): """Authenticate to ownCloud. This will create a session on the server. :param user_id: user id :param password: password :raises: HTTPResponseError in case an HTTP error status was returned """ self._session = requests.session() self._session.verify = self._verify_certs self._session.auth = (user_id, password) try: self._update_capabilities() url_components = parse.urlparse(self.url) if self._dav_endpoint_version == 1: self._davpath = url_components.path + 'remote.php/dav/files/' + parse.quote(user_id) self._webdav_url = self.url + 'remote.php/dav/files/' + parse.quote(user_id) else: self._davpath = url_components.path + 'remote.php/webdav' self._webdav_url = self.url + 'remote.php/webdav' except HTTPResponseError as e: self._session.close() self._session = None raise e
python
def login(self, user_id, password): self._session = requests.session() self._session.verify = self._verify_certs self._session.auth = (user_id, password) try: self._update_capabilities() url_components = parse.urlparse(self.url) if self._dav_endpoint_version == 1: self._davpath = url_components.path + 'remote.php/dav/files/' + parse.quote(user_id) self._webdav_url = self.url + 'remote.php/dav/files/' + parse.quote(user_id) else: self._davpath = url_components.path + 'remote.php/webdav' self._webdav_url = self.url + 'remote.php/webdav' except HTTPResponseError as e: self._session.close() self._session = None raise e
[ "def", "login", "(", "self", ",", "user_id", ",", "password", ")", ":", "self", ".", "_session", "=", "requests", ".", "session", "(", ")", "self", ".", "_session", ".", "verify", "=", "self", ".", "_verify_certs", "self", ".", "_session", ".", "auth",...
Authenticate to ownCloud. This will create a session on the server. :param user_id: user id :param password: password :raises: HTTPResponseError in case an HTTP error status was returned
[ "Authenticate", "to", "ownCloud", ".", "This", "will", "create", "a", "session", "on", "the", "server", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L339-L366
21,360
owncloud/pyocclient
owncloud/owncloud.py
Client.file_info
def file_info(self, path): """Returns the file info for the given remote file :param path: path to the remote file :returns: file info :rtype: :class:`FileInfo` object or `None` if file was not found :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_dav_request('PROPFIND', path, headers={'Depth': '0'}) if res: return res[0] return None
python
def file_info(self, path): res = self._make_dav_request('PROPFIND', path, headers={'Depth': '0'}) if res: return res[0] return None
[ "def", "file_info", "(", "self", ",", "path", ")", ":", "res", "=", "self", ".", "_make_dav_request", "(", "'PROPFIND'", ",", "path", ",", "headers", "=", "{", "'Depth'", ":", "'0'", "}", ")", "if", "res", ":", "return", "res", "[", "0", "]", "retu...
Returns the file info for the given remote file :param path: path to the remote file :returns: file info :rtype: :class:`FileInfo` object or `None` if file was not found :raises: HTTPResponseError in case an HTTP error status was returned
[ "Returns", "the", "file", "info", "for", "the", "given", "remote", "file" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L378-L390
21,361
owncloud/pyocclient
owncloud/owncloud.py
Client.get_file_contents
def get_file_contents(self, path): """Returns the contents of a remote file :param path: path to the remote file :returns: file contents :rtype: binary data :raises: HTTPResponseError in case an HTTP error status was returned """ path = self._normalize_path(path) res = self._session.get( self._webdav_url + parse.quote(self._encode_string(path)) ) if res.status_code == 200: return res.content elif res.status_code >= 400: raise HTTPResponseError(res) return False
python
def get_file_contents(self, path): path = self._normalize_path(path) res = self._session.get( self._webdav_url + parse.quote(self._encode_string(path)) ) if res.status_code == 200: return res.content elif res.status_code >= 400: raise HTTPResponseError(res) return False
[ "def", "get_file_contents", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_normalize_path", "(", "path", ")", "res", "=", "self", ".", "_session", ".", "get", "(", "self", ".", "_webdav_url", "+", "parse", ".", "quote", "(", "self", ...
Returns the contents of a remote file :param path: path to the remote file :returns: file contents :rtype: binary data :raises: HTTPResponseError in case an HTTP error status was returned
[ "Returns", "the", "contents", "of", "a", "remote", "file" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L414-L430
21,362
owncloud/pyocclient
owncloud/owncloud.py
Client.get_directory_as_zip
def get_directory_as_zip(self, remote_path, local_file): """Downloads a remote directory as zip :param remote_path: path to the remote directory to download :param local_file: path and name of the target local file :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ remote_path = self._normalize_path(remote_path) url = self.url + 'index.php/apps/files/ajax/download.php?dir=' \ + parse.quote(remote_path) res = self._session.get(url, stream=True) if res.status_code == 200: if local_file is None: # use downloaded file name from Content-Disposition # targetFile = res.headers['content-disposition'] local_file = os.path.basename(remote_path) file_handle = open(local_file, 'wb', 8192) for chunk in res.iter_content(8192): file_handle.write(chunk) file_handle.close() return True elif res.status_code >= 400: raise HTTPResponseError(res) return False
python
def get_directory_as_zip(self, remote_path, local_file): remote_path = self._normalize_path(remote_path) url = self.url + 'index.php/apps/files/ajax/download.php?dir=' \ + parse.quote(remote_path) res = self._session.get(url, stream=True) if res.status_code == 200: if local_file is None: # use downloaded file name from Content-Disposition # targetFile = res.headers['content-disposition'] local_file = os.path.basename(remote_path) file_handle = open(local_file, 'wb', 8192) for chunk in res.iter_content(8192): file_handle.write(chunk) file_handle.close() return True elif res.status_code >= 400: raise HTTPResponseError(res) return False
[ "def", "get_directory_as_zip", "(", "self", ",", "remote_path", ",", "local_file", ")", ":", "remote_path", "=", "self", ".", "_normalize_path", "(", "remote_path", ")", "url", "=", "self", ".", "url", "+", "'index.php/apps/files/ajax/download.php?dir='", "+", "pa...
Downloads a remote directory as zip :param remote_path: path to the remote directory to download :param local_file: path and name of the target local file :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Downloads", "a", "remote", "directory", "as", "zip" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L461-L486
21,363
owncloud/pyocclient
owncloud/owncloud.py
Client.put_directory
def put_directory(self, target_path, local_directory, **kwargs): """Upload a directory with all its contents :param target_path: path of the directory to upload into :param local_directory: path to the local directory to upload :param \*\*kwargs: optional arguments that ``put_file`` accepts :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ target_path = self._normalize_path(target_path) if not target_path.endswith('/'): target_path += '/' gathered_files = [] if not local_directory.endswith('/'): local_directory += '/' basedir = os.path.basename(local_directory[0: -1]) + '/' # gather files to upload for path, _, files in os.walk(local_directory): gathered_files.append( (path, basedir + path[len(local_directory):], files) ) for path, remote_path, files in gathered_files: self.mkdir(target_path + remote_path + '/') for name in files: if not self.put_file(target_path + remote_path + '/', path + '/' + name, **kwargs): return False return True
python
def put_directory(self, target_path, local_directory, **kwargs): target_path = self._normalize_path(target_path) if not target_path.endswith('/'): target_path += '/' gathered_files = [] if not local_directory.endswith('/'): local_directory += '/' basedir = os.path.basename(local_directory[0: -1]) + '/' # gather files to upload for path, _, files in os.walk(local_directory): gathered_files.append( (path, basedir + path[len(local_directory):], files) ) for path, remote_path, files in gathered_files: self.mkdir(target_path + remote_path + '/') for name in files: if not self.put_file(target_path + remote_path + '/', path + '/' + name, **kwargs): return False return True
[ "def", "put_directory", "(", "self", ",", "target_path", ",", "local_directory", ",", "*", "*", "kwargs", ")", ":", "target_path", "=", "self", ".", "_normalize_path", "(", "target_path", ")", "if", "not", "target_path", ".", "endswith", "(", "'/'", ")", "...
Upload a directory with all its contents :param target_path: path of the directory to upload into :param local_directory: path to the local directory to upload :param \*\*kwargs: optional arguments that ``put_file`` accepts :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Upload", "a", "directory", "with", "all", "its", "contents" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L536-L566
21,364
owncloud/pyocclient
owncloud/owncloud.py
Client._put_file_chunked
def _put_file_chunked(self, remote_path, local_source_file, **kwargs): """Uploads a file using chunks. If the file is smaller than ``chunk_size`` it will be uploaded directly. :param remote_path: path to the target file. A target directory can also be specified instead by appending a "/" :param local_source_file: path to the local file to upload :param \*\*kwargs: optional arguments that ``put_file`` accepts :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ chunk_size = kwargs.get('chunk_size', 10 * 1024 * 1024) result = True transfer_id = int(time.time()) remote_path = self._normalize_path(remote_path) if remote_path.endswith('/'): remote_path += os.path.basename(local_source_file) stat_result = os.stat(local_source_file) file_handle = open(local_source_file, 'rb', 8192) file_handle.seek(0, os.SEEK_END) size = file_handle.tell() file_handle.seek(0) headers = {} if kwargs.get('keep_mtime', True): headers['X-OC-MTIME'] = str(int(stat_result.st_mtime)) if size == 0: return self._make_dav_request( 'PUT', remote_path, data='', headers=headers ) chunk_count = int(math.ceil(float(size) / float(chunk_size))) if chunk_count > 1: headers['OC-CHUNKED'] = '1' for chunk_index in range(0, int(chunk_count)): data = file_handle.read(chunk_size) if chunk_count > 1: chunk_name = '%s-chunking-%s-%i-%i' % \ (remote_path, transfer_id, chunk_count, chunk_index) else: chunk_name = remote_path if not self._make_dav_request( 'PUT', chunk_name, data=data, headers=headers ): result = False break file_handle.close() return result
python
def _put_file_chunked(self, remote_path, local_source_file, **kwargs): chunk_size = kwargs.get('chunk_size', 10 * 1024 * 1024) result = True transfer_id = int(time.time()) remote_path = self._normalize_path(remote_path) if remote_path.endswith('/'): remote_path += os.path.basename(local_source_file) stat_result = os.stat(local_source_file) file_handle = open(local_source_file, 'rb', 8192) file_handle.seek(0, os.SEEK_END) size = file_handle.tell() file_handle.seek(0) headers = {} if kwargs.get('keep_mtime', True): headers['X-OC-MTIME'] = str(int(stat_result.st_mtime)) if size == 0: return self._make_dav_request( 'PUT', remote_path, data='', headers=headers ) chunk_count = int(math.ceil(float(size) / float(chunk_size))) if chunk_count > 1: headers['OC-CHUNKED'] = '1' for chunk_index in range(0, int(chunk_count)): data = file_handle.read(chunk_size) if chunk_count > 1: chunk_name = '%s-chunking-%s-%i-%i' % \ (remote_path, transfer_id, chunk_count, chunk_index) else: chunk_name = remote_path if not self._make_dav_request( 'PUT', chunk_name, data=data, headers=headers ): result = False break file_handle.close() return result
[ "def", "_put_file_chunked", "(", "self", ",", "remote_path", ",", "local_source_file", ",", "*", "*", "kwargs", ")", ":", "chunk_size", "=", "kwargs", ".", "get", "(", "'chunk_size'", ",", "10", "*", "1024", "*", "1024", ")", "result", "=", "True", "tran...
Uploads a file using chunks. If the file is smaller than ``chunk_size`` it will be uploaded directly. :param remote_path: path to the target file. A target directory can also be specified instead by appending a "/" :param local_source_file: path to the local file to upload :param \*\*kwargs: optional arguments that ``put_file`` accepts :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Uploads", "a", "file", "using", "chunks", ".", "If", "the", "file", "is", "smaller", "than", "chunk_size", "it", "will", "be", "uploaded", "directly", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L568-L630
21,365
owncloud/pyocclient
owncloud/owncloud.py
Client.list_open_remote_share
def list_open_remote_share(self): """List all pending remote shares :returns: array of pending remote shares :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, 'remote_shares/pending' ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) shares = [] for element in tree.find('data').iter('element'): share_attr = {} for child in element: key = child.tag value = child.text share_attr[key] = value shares.append(share_attr) return shares raise HTTPResponseError(res)
python
def list_open_remote_share(self): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, 'remote_shares/pending' ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) shares = [] for element in tree.find('data').iter('element'): share_attr = {} for child in element: key = child.tag value = child.text share_attr[key] = value shares.append(share_attr) return shares raise HTTPResponseError(res)
[ "def", "list_open_remote_share", "(", "self", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_SHARE", ",", "'remote_shares/pending'", ")", "if", "res", ".", "status_code", "==", "200", ":", "tree", "=", "E...
List all pending remote shares :returns: array of pending remote shares :raises: HTTPResponseError in case an HTTP error status was returned
[ "List", "all", "pending", "remote", "shares" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L652-L676
21,366
owncloud/pyocclient
owncloud/owncloud.py
Client.accept_remote_share
def accept_remote_share(self, share_id): """Accepts a remote share :param share_id: Share ID (int) :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ if not isinstance(share_id, int): return False res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'remote_shares/pending/' + str(share_id) ) if res.status_code == 200: return res raise HTTPResponseError(res)
python
def accept_remote_share(self, share_id): if not isinstance(share_id, int): return False res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'remote_shares/pending/' + str(share_id) ) if res.status_code == 200: return res raise HTTPResponseError(res)
[ "def", "accept_remote_share", "(", "self", ",", "share_id", ")", ":", "if", "not", "isinstance", "(", "share_id", ",", "int", ")", ":", "return", "False", "res", "=", "self", ".", "_make_ocs_request", "(", "'POST'", ",", "self", ".", "OCS_SERVICE_SHARE", "...
Accepts a remote share :param share_id: Share ID (int) :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Accepts", "a", "remote", "share" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L678-L695
21,367
owncloud/pyocclient
owncloud/owncloud.py
Client.update_share
def update_share(self, share_id, **kwargs): """Updates a given share :param share_id: (int) Share ID :param perms: (int) update permissions (see share_file_with_user() below) :param password: (string) updated password for public link Share :param public_upload: (boolean) enable/disable public upload for public shares :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ perms = kwargs.get('perms', None) password = kwargs.get('password', None) public_upload = kwargs.get('public_upload', None) if (isinstance(perms, int)) and (perms > self.OCS_PERMISSION_ALL): perms = None if not (perms or password or (public_upload is not None)): return False if not isinstance(share_id, int): return False data = {} if perms: data['permissions'] = perms if isinstance(password, six.string_types): data['password'] = password if (public_upload is not None) and (isinstance(public_upload, bool)): data['publicUpload'] = str(public_upload).lower() res = self._make_ocs_request( 'PUT', self.OCS_SERVICE_SHARE, 'shares/' + str(share_id), data=data ) if res.status_code == 200: return True raise HTTPResponseError(res)
python
def update_share(self, share_id, **kwargs): perms = kwargs.get('perms', None) password = kwargs.get('password', None) public_upload = kwargs.get('public_upload', None) if (isinstance(perms, int)) and (perms > self.OCS_PERMISSION_ALL): perms = None if not (perms or password or (public_upload is not None)): return False if not isinstance(share_id, int): return False data = {} if perms: data['permissions'] = perms if isinstance(password, six.string_types): data['password'] = password if (public_upload is not None) and (isinstance(public_upload, bool)): data['publicUpload'] = str(public_upload).lower() res = self._make_ocs_request( 'PUT', self.OCS_SERVICE_SHARE, 'shares/' + str(share_id), data=data ) if res.status_code == 200: return True raise HTTPResponseError(res)
[ "def", "update_share", "(", "self", ",", "share_id", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "kwargs", ".", "get", "(", "'perms'", ",", "None", ")", "password", "=", "kwargs", ".", "get", "(", "'password'", ",", "None", ")", "public_upload", ...
Updates a given share :param share_id: (int) Share ID :param perms: (int) update permissions (see share_file_with_user() below) :param password: (string) updated password for public link Share :param public_upload: (boolean) enable/disable public upload for public shares :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Updates", "a", "given", "share" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L735-L772
21,368
owncloud/pyocclient
owncloud/owncloud.py
Client.share_file_with_link
def share_file_with_link(self, path, **kwargs): """Shares a remote file with link :param path: path to the remote file to share :param perms (optional): permission of the shared object defaults to read only (1) :param public_upload (optional): allows users to upload files or folders :param password (optional): sets a password http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned """ perms = kwargs.get('perms', None) public_upload = kwargs.get('public_upload', 'false') password = kwargs.get('password', None) path = self._normalize_path(path) post_data = { 'shareType': self.OCS_SHARE_TYPE_LINK, 'path': self._encode_string(path), } if (public_upload is not None) and (isinstance(public_upload, bool)): post_data['publicUpload'] = str(public_upload).lower() if isinstance(password, six.string_types): post_data['password'] = password if perms: post_data['permissions'] = perms res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'url': data_el.find('url').text, 'token': data_el.find('token').text } ) raise HTTPResponseError(res)
python
def share_file_with_link(self, path, **kwargs): perms = kwargs.get('perms', None) public_upload = kwargs.get('public_upload', 'false') password = kwargs.get('password', None) path = self._normalize_path(path) post_data = { 'shareType': self.OCS_SHARE_TYPE_LINK, 'path': self._encode_string(path), } if (public_upload is not None) and (isinstance(public_upload, bool)): post_data['publicUpload'] = str(public_upload).lower() if isinstance(password, six.string_types): post_data['password'] = password if perms: post_data['permissions'] = perms res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'url': data_el.find('url').text, 'token': data_el.find('token').text } ) raise HTTPResponseError(res)
[ "def", "share_file_with_link", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "kwargs", ".", "get", "(", "'perms'", ",", "None", ")", "public_upload", "=", "kwargs", ".", "get", "(", "'public_upload'", ",", "'false'", ")", "...
Shares a remote file with link :param path: path to the remote file to share :param perms (optional): permission of the shared object defaults to read only (1) :param public_upload (optional): allows users to upload files or folders :param password (optional): sets a password http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned
[ "Shares", "a", "remote", "file", "with", "link" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L800-L847
21,369
owncloud/pyocclient
owncloud/owncloud.py
Client.is_shared
def is_shared(self, path): """Checks whether a path is already shared :param path: path to the share to be checked :returns: True if the path is already shared, else False :raises: HTTPResponseError in case an HTTP error status was returned """ # make sure that the path exist - if not, raise HTTPResponseError self.file_info(path) try: result = self.get_shares(path) if result: return len(result) > 0 except OCSResponseError as e: if e.status_code != 404: raise e return False return False
python
def is_shared(self, path): # make sure that the path exist - if not, raise HTTPResponseError self.file_info(path) try: result = self.get_shares(path) if result: return len(result) > 0 except OCSResponseError as e: if e.status_code != 404: raise e return False return False
[ "def", "is_shared", "(", "self", ",", "path", ")", ":", "# make sure that the path exist - if not, raise HTTPResponseError", "self", ".", "file_info", "(", "path", ")", "try", ":", "result", "=", "self", ".", "get_shares", "(", "path", ")", "if", "result", ":", ...
Checks whether a path is already shared :param path: path to the share to be checked :returns: True if the path is already shared, else False :raises: HTTPResponseError in case an HTTP error status was returned
[ "Checks", "whether", "a", "path", "is", "already", "shared" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L849-L866
21,370
owncloud/pyocclient
owncloud/owncloud.py
Client.get_share
def get_share(self, share_id): """Returns share information about known share :param share_id: id of the share to be checked :returns: instance of ShareInfo class :raises: ResponseError in case an HTTP error status was returned """ if (share_id is None) or not (isinstance(share_id, int)): return None res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, 'shares/' + str(share_id) ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) return self._get_shareinfo(tree.find('data').find('element')) raise HTTPResponseError(res)
python
def get_share(self, share_id): if (share_id is None) or not (isinstance(share_id, int)): return None res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, 'shares/' + str(share_id) ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) return self._get_shareinfo(tree.find('data').find('element')) raise HTTPResponseError(res)
[ "def", "get_share", "(", "self", ",", "share_id", ")", ":", "if", "(", "share_id", "is", "None", ")", "or", "not", "(", "isinstance", "(", "share_id", ",", "int", ")", ")", ":", "return", "None", "res", "=", "self", ".", "_make_ocs_request", "(", "'G...
Returns share information about known share :param share_id: id of the share to be checked :returns: instance of ShareInfo class :raises: ResponseError in case an HTTP error status was returned
[ "Returns", "share", "information", "about", "known", "share" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L868-L887
21,371
owncloud/pyocclient
owncloud/owncloud.py
Client.get_shares
def get_shares(self, path='', **kwargs): """Returns array of shares :param path: path to the share to be checked :param reshares: (optional, boolean) returns not only the shares from the current user but all shares from the given file (default: False) :param subfiles: (optional, boolean) returns all shares within a folder, given that path defines a folder (default: False) :param shared_with_me: (optional, boolean) returns all shares which are shared with me (default: False) :returns: array of shares ShareInfo instances or empty array if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned """ if not (isinstance(path, six.string_types)): return None data = 'shares' if path != '': data += '?' path = self._encode_string(self._normalize_path(path)) args = {'path': path} reshares = kwargs.get('reshares', False) if isinstance(reshares, bool) and reshares: args['reshares'] = reshares subfiles = kwargs.get('subfiles', False) if isinstance(subfiles, bool) and subfiles: args['subfiles'] = str(subfiles).lower() shared_with_me = kwargs.get('shared_with_me', False) if isinstance(shared_with_me, bool) and shared_with_me: args['shared_with_me'] = "true" del args['path'] data += parse.urlencode(args) res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) shares = [] for element in tree.find('data').iter('element'): '''share_attr = {} for child in element: key = child.tag value = child.text share_attr[key] = value shares.append(share_attr)''' shares.append(self._get_shareinfo(element)) return shares raise HTTPResponseError(res)
python
def get_shares(self, path='', **kwargs): if not (isinstance(path, six.string_types)): return None data = 'shares' if path != '': data += '?' path = self._encode_string(self._normalize_path(path)) args = {'path': path} reshares = kwargs.get('reshares', False) if isinstance(reshares, bool) and reshares: args['reshares'] = reshares subfiles = kwargs.get('subfiles', False) if isinstance(subfiles, bool) and subfiles: args['subfiles'] = str(subfiles).lower() shared_with_me = kwargs.get('shared_with_me', False) if isinstance(shared_with_me, bool) and shared_with_me: args['shared_with_me'] = "true" del args['path'] data += parse.urlencode(args) res = self._make_ocs_request( 'GET', self.OCS_SERVICE_SHARE, data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) shares = [] for element in tree.find('data').iter('element'): '''share_attr = {} for child in element: key = child.tag value = child.text share_attr[key] = value shares.append(share_attr)''' shares.append(self._get_shareinfo(element)) return shares raise HTTPResponseError(res)
[ "def", "get_shares", "(", "self", ",", "path", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", ")", ":", "return", "None", "data", "=", "'shares'", "if", "path", "!=",...
Returns array of shares :param path: path to the share to be checked :param reshares: (optional, boolean) returns not only the shares from the current user but all shares from the given file (default: False) :param subfiles: (optional, boolean) returns all shares within a folder, given that path defines a folder (default: False) :param shared_with_me: (optional, boolean) returns all shares which are shared with me (default: False) :returns: array of shares ShareInfo instances or empty array if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned
[ "Returns", "array", "of", "shares" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L889-L943
21,372
owncloud/pyocclient
owncloud/owncloud.py
Client.create_user
def create_user(self, user_name, initial_password): """Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be created :param initial_password: password for user being created :returns: True on success :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'POST', self.OCS_SERVICE_CLOUD, 'users', data={'password': initial_password, 'userid': user_name} ) # We get 200 when the user was just created. if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
python
def create_user(self, user_name, initial_password): res = self._make_ocs_request( 'POST', self.OCS_SERVICE_CLOUD, 'users', data={'password': initial_password, 'userid': user_name} ) # We get 200 when the user was just created. if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
[ "def", "create_user", "(", "self", ",", "user_name", ",", "initial_password", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'POST'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users'", ",", "data", "=", "{", "'password'", ":", "initial_pas...
Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be created :param initial_password: password for user being created :returns: True on success :raises: HTTPResponseError in case an HTTP error status was returned
[ "Create", "a", "new", "user", "with", "an", "initial", "password", "via", "provisioning", "API", ".", "It", "is", "not", "an", "error", "if", "the", "user", "already", "existed", "before", ".", "If", "you", "get", "back", "an", "error", "999", "then", ...
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L945-L969
21,373
owncloud/pyocclient
owncloud/owncloud.py
Client.delete_user
def delete_user(self, user_name): """Deletes a user via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be deleted :returns: True on success :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'DELETE', self.OCS_SERVICE_CLOUD, 'users/' + user_name ) # We get 200 when the user was deleted. if res.status_code == 200: return True raise HTTPResponseError(res)
python
def delete_user(self, user_name): res = self._make_ocs_request( 'DELETE', self.OCS_SERVICE_CLOUD, 'users/' + user_name ) # We get 200 when the user was deleted. if res.status_code == 200: return True raise HTTPResponseError(res)
[ "def", "delete_user", "(", "self", ",", "user_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'DELETE'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "user_name", ")", "# We get 200 when the user was deleted.", "if", "res", "...
Deletes a user via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be deleted :returns: True on success :raises: HTTPResponseError in case an HTTP error status was returned
[ "Deletes", "a", "user", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L971-L990
21,374
owncloud/pyocclient
owncloud/owncloud.py
Client.search_users
def search_users(self, user_name): """Searches for users via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be searched for :returns: list of usernames that contain user_name as substring :raises: HTTPResponseError in case an HTTP error status was returned """ action_path = 'users' if user_name: action_path += '?search={}'.format(user_name) res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, action_path ) if res.status_code == 200: tree = ET.fromstring(res.content) users = [x.text for x in tree.findall('data/users/element')] return users raise HTTPResponseError(res)
python
def search_users(self, user_name): action_path = 'users' if user_name: action_path += '?search={}'.format(user_name) res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, action_path ) if res.status_code == 200: tree = ET.fromstring(res.content) users = [x.text for x in tree.findall('data/users/element')] return users raise HTTPResponseError(res)
[ "def", "search_users", "(", "self", ",", "user_name", ")", ":", "action_path", "=", "'users'", "if", "user_name", ":", "action_path", "+=", "'?search={}'", ".", "format", "(", "user_name", ")", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",",...
Searches for users via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be searched for :returns: list of usernames that contain user_name as substring :raises: HTTPResponseError in case an HTTP error status was returned
[ "Searches", "for", "users", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1004-L1029
21,375
owncloud/pyocclient
owncloud/owncloud.py
Client.set_user_attribute
def set_user_attribute(self, user_name, key, value): """Sets a user attribute :param user_name: name of user to modify :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'PUT', self.OCS_SERVICE_CLOUD, 'users/' + parse.quote(user_name), data={'key': self._encode_string(key), 'value': self._encode_string(value)} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
python
def set_user_attribute(self, user_name, key, value): res = self._make_ocs_request( 'PUT', self.OCS_SERVICE_CLOUD, 'users/' + parse.quote(user_name), data={'key': self._encode_string(key), 'value': self._encode_string(value)} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
[ "def", "set_user_attribute", "(", "self", ",", "user_name", ",", "key", ",", "value", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'PUT'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "parse", ".", "quote", "(", "user_name"...
Sets a user attribute :param user_name: name of user to modify :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Sets", "a", "user", "attribute" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1041-L1063
21,376
owncloud/pyocclient
owncloud/owncloud.py
Client.add_user_to_group
def add_user_to_group(self, user_name, group_name): """Adds a user to a group. :param user_name: name of user to be added :param group_name: name of group user is to be added to :returns: True if user added :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'POST', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/groups', data={'groupid': group_name} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
python
def add_user_to_group(self, user_name, group_name): res = self._make_ocs_request( 'POST', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/groups', data={'groupid': group_name} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return True raise HTTPResponseError(res)
[ "def", "add_user_to_group", "(", "self", ",", "user_name", ",", "group_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'POST'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "user_name", "+", "'/groups'", ",", "data", "=",...
Adds a user to a group. :param user_name: name of user to be added :param group_name: name of group user is to be added to :returns: True if user added :raises: HTTPResponseError in case an HTTP error status was returned
[ "Adds", "a", "user", "to", "a", "group", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1065-L1087
21,377
owncloud/pyocclient
owncloud/owncloud.py
Client.get_user_groups
def get_user_groups(self, user_name): """Get a list of groups associated to a user. :param user_name: name of user to list groups :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/groups', ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return [group.text for group in tree.find('data/groups')] raise HTTPResponseError(res)
python
def get_user_groups(self, user_name): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/groups', ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return [group.text for group in tree.find('data/groups')] raise HTTPResponseError(res)
[ "def", "get_user_groups", "(", "self", ",", "user_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "user_name", "+", "'/groups'", ",", ")", "if", "res", ".", "status_c...
Get a list of groups associated to a user. :param user_name: name of user to list groups :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned
[ "Get", "a", "list", "of", "groups", "associated", "to", "a", "user", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1089-L1109
21,378
owncloud/pyocclient
owncloud/owncloud.py
Client.get_user
def get_user(self, user_name): """Retrieves information about a user :param user_name: name of user to query :returns: Dictionary of information about user :raises: ResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + parse.quote(user_name), data={} ) tree = ET.fromstring(res.content) self._check_ocs_status(tree) # <ocs><meta><statuscode>100</statuscode><status>ok</status></meta> # <data> # <email>frank@example.org</email><quota>0</quota><enabled>true</enabled> # </data> # </ocs> data_element = tree.find('data') return self._xml_to_dict(data_element)
python
def get_user(self, user_name): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + parse.quote(user_name), data={} ) tree = ET.fromstring(res.content) self._check_ocs_status(tree) # <ocs><meta><statuscode>100</statuscode><status>ok</status></meta> # <data> # <email>frank@example.org</email><quota>0</quota><enabled>true</enabled> # </data> # </ocs> data_element = tree.find('data') return self._xml_to_dict(data_element)
[ "def", "get_user", "(", "self", ",", "user_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "parse", ".", "quote", "(", "user_name", ")", ",", "data", "=", "{", "}...
Retrieves information about a user :param user_name: name of user to query :returns: Dictionary of information about user :raises: ResponseError in case an HTTP error status was returned
[ "Retrieves", "information", "about", "a", "user" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1121-L1145
21,379
owncloud/pyocclient
owncloud/owncloud.py
Client.get_user_subadmin_groups
def get_user_subadmin_groups(self, user_name): """Get a list of subadmin groups associated to a user. :param user_name: name of user :returns: list of subadmin groups :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/subadmins', ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) groups = tree.find('data') return groups raise HTTPResponseError(res)
python
def get_user_subadmin_groups(self, user_name): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'users/' + user_name + '/subadmins', ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) groups = tree.find('data') return groups raise HTTPResponseError(res)
[ "def", "get_user_subadmin_groups", "(", "self", ",", "user_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "user_name", "+", "'/subadmins'", ",", ")", "if", "res", ".",...
Get a list of subadmin groups associated to a user. :param user_name: name of user :returns: list of subadmin groups :raises: HTTPResponseError in case an HTTP error status was returned
[ "Get", "a", "list", "of", "subadmin", "groups", "associated", "to", "a", "user", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1194-L1217
21,380
owncloud/pyocclient
owncloud/owncloud.py
Client.share_file_with_user
def share_file_with_user(self, path, user, **kwargs): """Shares a remote file with specified user :param path: path to the remote file to share :param user: name of the user whom we want to share a file/folder :param perms (optional): permissions of the shared object defaults to read only (1) http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :param remote_user (optional): True if it is a federated users defaults to False if it is a local user :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned """ remote_user = kwargs.get('remote_user', False) perms = kwargs.get('perms', self.OCS_PERMISSION_READ) if (((not isinstance(perms, int)) or (perms > self.OCS_PERMISSION_ALL)) or ((not isinstance(user, six.string_types)) or (user == ''))): return False if remote_user and (not user.endswith('/')): user = user + '/' path = self._normalize_path(path) post_data = { 'shareType': self.OCS_SHARE_TYPE_REMOTE if remote_user else self.OCS_SHARE_TYPE_USER, 'shareWith': user, 'path': self._encode_string(path), 'permissions': perms } res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if self._debug: print('OCS share_file request for file %s with permissions %i ' 'returned: %i' % (path, perms, res.status_code)) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'permissions': perms } ) raise HTTPResponseError(res)
python
def share_file_with_user(self, path, user, **kwargs): remote_user = kwargs.get('remote_user', False) perms = kwargs.get('perms', self.OCS_PERMISSION_READ) if (((not isinstance(perms, int)) or (perms > self.OCS_PERMISSION_ALL)) or ((not isinstance(user, six.string_types)) or (user == ''))): return False if remote_user and (not user.endswith('/')): user = user + '/' path = self._normalize_path(path) post_data = { 'shareType': self.OCS_SHARE_TYPE_REMOTE if remote_user else self.OCS_SHARE_TYPE_USER, 'shareWith': user, 'path': self._encode_string(path), 'permissions': perms } res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if self._debug: print('OCS share_file request for file %s with permissions %i ' 'returned: %i' % (path, perms, res.status_code)) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'permissions': perms } ) raise HTTPResponseError(res)
[ "def", "share_file_with_user", "(", "self", ",", "path", ",", "user", ",", "*", "*", "kwargs", ")", ":", "remote_user", "=", "kwargs", ".", "get", "(", "'remote_user'", ",", "False", ")", "perms", "=", "kwargs", ".", "get", "(", "'perms'", ",", "self",...
Shares a remote file with specified user :param path: path to the remote file to share :param user: name of the user whom we want to share a file/folder :param perms (optional): permissions of the shared object defaults to read only (1) http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :param remote_user (optional): True if it is a federated users defaults to False if it is a local user :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned
[ "Shares", "a", "remote", "file", "with", "specified", "user" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1229-L1281
21,381
owncloud/pyocclient
owncloud/owncloud.py
Client.delete_group
def delete_group(self, group_name): """Delete a group via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to be deleted :returns: True if group deleted :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'DELETE', self.OCS_SERVICE_CLOUD, 'groups/' + group_name ) # We get 200 when the group was just deleted. if res.status_code == 200: return True raise HTTPResponseError(res)
python
def delete_group(self, group_name): res = self._make_ocs_request( 'DELETE', self.OCS_SERVICE_CLOUD, 'groups/' + group_name ) # We get 200 when the group was just deleted. if res.status_code == 200: return True raise HTTPResponseError(res)
[ "def", "delete_group", "(", "self", ",", "group_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'DELETE'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'groups/'", "+", "group_name", ")", "# We get 200 when the group was just deleted.", "if", ...
Delete a group via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to be deleted :returns: True if group deleted :raises: HTTPResponseError in case an HTTP error status was returned
[ "Delete", "a", "group", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1307-L1326
21,382
owncloud/pyocclient
owncloud/owncloud.py
Client.get_groups
def get_groups(self): """Get groups via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups' ) if res.status_code == 200: tree = ET.fromstring(res.content) groups = [x.text for x in tree.findall('data/groups/element')] return groups raise HTTPResponseError(res)
python
def get_groups(self): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups' ) if res.status_code == 200: tree = ET.fromstring(res.content) groups = [x.text for x in tree.findall('data/groups/element')] return groups raise HTTPResponseError(res)
[ "def", "get_groups", "(", "self", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'groups'", ")", "if", "res", ".", "status_code", "==", "200", ":", "tree", "=", "ET", ".", "fromstring", ...
Get groups via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned
[ "Get", "groups", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1328-L1348
21,383
owncloud/pyocclient
owncloud/owncloud.py
Client.get_group_members
def get_group_members(self, group_name): """Get group members via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to list members :returns: list of group members :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups/' + group_name ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return [group.text for group in tree.find('data/users')] raise HTTPResponseError(res)
python
def get_group_members(self, group_name): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups/' + group_name ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) return [group.text for group in tree.find('data/users')] raise HTTPResponseError(res)
[ "def", "get_group_members", "(", "self", ",", "group_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'groups/'", "+", "group_name", ")", "if", "res", ".", "status_code", "==", "200", ...
Get group members via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to list members :returns: list of group members :raises: HTTPResponseError in case an HTTP error status was returned
[ "Get", "group", "members", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1350-L1370
21,384
owncloud/pyocclient
owncloud/owncloud.py
Client.group_exists
def group_exists(self, group_name): """Checks a group via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to be checked :returns: True if group exists :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups?search=' + group_name ) if res.status_code == 200: tree = ET.fromstring(res.content) for code_el in tree.findall('data/groups/element'): if code_el is not None and code_el.text == group_name: return True return False raise HTTPResponseError(res)
python
def group_exists(self, group_name): res = self._make_ocs_request( 'GET', self.OCS_SERVICE_CLOUD, 'groups?search=' + group_name ) if res.status_code == 200: tree = ET.fromstring(res.content) for code_el in tree.findall('data/groups/element'): if code_el is not None and code_el.text == group_name: return True return False raise HTTPResponseError(res)
[ "def", "group_exists", "(", "self", ",", "group_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'groups?search='", "+", "group_name", ")", "if", "res", ".", "status_code", "==", "200",...
Checks a group via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param group_name: name of group to be checked :returns: True if group exists :raises: HTTPResponseError in case an HTTP error status was returned
[ "Checks", "a", "group", "via", "provisioning", "API", ".", "If", "you", "get", "back", "an", "error", "999", "then", "the", "provisioning", "API", "is", "not", "enabled", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1372-L1396
21,385
owncloud/pyocclient
owncloud/owncloud.py
Client.share_file_with_group
def share_file_with_group(self, path, group, **kwargs): """Shares a remote file with specified group :param path: path to the remote file to share :param group: name of the group with which we want to share a file/folder :param perms (optional): permissions of the shared object defaults to read only (1) http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned """ perms = kwargs.get('perms', self.OCS_PERMISSION_READ) if (((not isinstance(perms, int)) or (perms > self.OCS_PERMISSION_ALL)) or ((not isinstance(group, six.string_types)) or (group == ''))): return False path = self._normalize_path(path) post_data = {'shareType': self.OCS_SHARE_TYPE_GROUP, 'shareWith': group, 'path': path, 'permissions': perms} res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'permissions': perms } ) raise HTTPResponseError(res)
python
def share_file_with_group(self, path, group, **kwargs): perms = kwargs.get('perms', self.OCS_PERMISSION_READ) if (((not isinstance(perms, int)) or (perms > self.OCS_PERMISSION_ALL)) or ((not isinstance(group, six.string_types)) or (group == ''))): return False path = self._normalize_path(path) post_data = {'shareType': self.OCS_SHARE_TYPE_GROUP, 'shareWith': group, 'path': path, 'permissions': perms} res = self._make_ocs_request( 'POST', self.OCS_SERVICE_SHARE, 'shares', data=post_data ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) data_el = tree.find('data') return ShareInfo( { 'id': data_el.find('id').text, 'path': path, 'permissions': perms } ) raise HTTPResponseError(res)
[ "def", "share_file_with_group", "(", "self", ",", "path", ",", "group", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "kwargs", ".", "get", "(", "'perms'", ",", "self", ".", "OCS_PERMISSION_READ", ")", "if", "(", "(", "(", "not", "isinstance", "(", ...
Shares a remote file with specified group :param path: path to the remote file to share :param group: name of the group with which we want to share a file/folder :param perms (optional): permissions of the shared object defaults to read only (1) http://doc.owncloud.org/server/6.0/admin_manual/sharing_api/index.html :returns: instance of :class:`ShareInfo` with the share info or False if the operation failed :raises: HTTPResponseError in case an HTTP error status was returned
[ "Shares", "a", "remote", "file", "with", "specified", "group" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1398-L1438
21,386
owncloud/pyocclient
owncloud/owncloud.py
Client.get_attribute
def get_attribute(self, app=None, key=None): """Returns an application attribute :param app: application id :param key: attribute key or None to retrieve all values for the given application :returns: attribute value if key was specified, or an array of tuples (key, value) for each attribute :raises: HTTPResponseError in case an HTTP error status was returned """ path = 'getattribute' if app is not None: path += '/' + parse.quote(app, '') if key is not None: path += '/' + parse.quote(self._encode_string(key), '') res = self._make_ocs_request( 'GET', self.OCS_SERVICE_PRIVATEDATA, path ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) values = [] for element in tree.find('data').iter('element'): app_text = element.find('app').text key_text = element.find('key').text value_text = element.find('value').text or '' if key is None: if app is None: values.append((app_text, key_text, value_text)) else: values.append((key_text, value_text)) else: return value_text if len(values) == 0 and key is not None: return None return values raise HTTPResponseError(res)
python
def get_attribute(self, app=None, key=None): path = 'getattribute' if app is not None: path += '/' + parse.quote(app, '') if key is not None: path += '/' + parse.quote(self._encode_string(key), '') res = self._make_ocs_request( 'GET', self.OCS_SERVICE_PRIVATEDATA, path ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) values = [] for element in tree.find('data').iter('element'): app_text = element.find('app').text key_text = element.find('key').text value_text = element.find('value').text or '' if key is None: if app is None: values.append((app_text, key_text, value_text)) else: values.append((key_text, value_text)) else: return value_text if len(values) == 0 and key is not None: return None return values raise HTTPResponseError(res)
[ "def", "get_attribute", "(", "self", ",", "app", "=", "None", ",", "key", "=", "None", ")", ":", "path", "=", "'getattribute'", "if", "app", "is", "not", "None", ":", "path", "+=", "'/'", "+", "parse", ".", "quote", "(", "app", ",", "''", ")", "i...
Returns an application attribute :param app: application id :param key: attribute key or None to retrieve all values for the given application :returns: attribute value if key was specified, or an array of tuples (key, value) for each attribute :raises: HTTPResponseError in case an HTTP error status was returned
[ "Returns", "an", "application", "attribute" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1469-L1508
21,387
owncloud/pyocclient
owncloud/owncloud.py
Client.set_attribute
def set_attribute(self, app, key, value): """Sets an application attribute :param app: application id :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ path = 'setattribute/' + parse.quote(app, '') + '/' + parse.quote( self._encode_string(key), '') res = self._make_ocs_request( 'POST', self.OCS_SERVICE_PRIVATEDATA, path, data={'value': self._encode_string(value)} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) return True raise HTTPResponseError(res)
python
def set_attribute(self, app, key, value): path = 'setattribute/' + parse.quote(app, '') + '/' + parse.quote( self._encode_string(key), '') res = self._make_ocs_request( 'POST', self.OCS_SERVICE_PRIVATEDATA, path, data={'value': self._encode_string(value)} ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) return True raise HTTPResponseError(res)
[ "def", "set_attribute", "(", "self", ",", "app", ",", "key", ",", "value", ")", ":", "path", "=", "'setattribute/'", "+", "parse", ".", "quote", "(", "app", ",", "''", ")", "+", "'/'", "+", "parse", ".", "quote", "(", "self", ".", "_encode_string", ...
Sets an application attribute :param app: application id :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Sets", "an", "application", "attribute" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1510-L1531
21,388
owncloud/pyocclient
owncloud/owncloud.py
Client.get_apps
def get_apps(self): """ List all enabled apps through the provisioning api. :returns: a dict of apps, with values True/False, representing the enabled state. :raises: HTTPResponseError in case an HTTP error status was returned """ ena_apps = {} res = self._make_ocs_request('GET', self.OCS_SERVICE_CLOUD, 'apps') if res.status_code != 200: raise HTTPResponseError(res) tree = ET.fromstring(res.content) self._check_ocs_status(tree) # <data><apps><element>files</element><element>activity</element> ... for el in tree.findall('data/apps/element'): ena_apps[el.text] = False res = self._make_ocs_request('GET', self.OCS_SERVICE_CLOUD, 'apps?filter=enabled') if res.status_code != 200: raise HTTPResponseError(res) tree = ET.fromstring(res.content) self._check_ocs_status(tree) for el in tree.findall('data/apps/element'): ena_apps[el.text] = True return ena_apps
python
def get_apps(self): ena_apps = {} res = self._make_ocs_request('GET', self.OCS_SERVICE_CLOUD, 'apps') if res.status_code != 200: raise HTTPResponseError(res) tree = ET.fromstring(res.content) self._check_ocs_status(tree) # <data><apps><element>files</element><element>activity</element> ... for el in tree.findall('data/apps/element'): ena_apps[el.text] = False res = self._make_ocs_request('GET', self.OCS_SERVICE_CLOUD, 'apps?filter=enabled') if res.status_code != 200: raise HTTPResponseError(res) tree = ET.fromstring(res.content) self._check_ocs_status(tree) for el in tree.findall('data/apps/element'): ena_apps[el.text] = True return ena_apps
[ "def", "get_apps", "(", "self", ")", ":", "ena_apps", "=", "{", "}", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'apps'", ")", "if", "res", ".", "status_code", "!=", "200", ":", "raise", "HTT...
List all enabled apps through the provisioning api. :returns: a dict of apps, with values True/False, representing the enabled state. :raises: HTTPResponseError in case an HTTP error status was returned
[ "List", "all", "enabled", "apps", "through", "the", "provisioning", "api", "." ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1554-L1580
21,389
owncloud/pyocclient
owncloud/owncloud.py
Client.enable_app
def enable_app(self, appname): """Enable an app through provisioning_api :param appname: Name of app to be enabled :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request('POST', self.OCS_SERVICE_CLOUD, 'apps/' + appname) if res.status_code == 200: return True raise HTTPResponseError(res)
python
def enable_app(self, appname): res = self._make_ocs_request('POST', self.OCS_SERVICE_CLOUD, 'apps/' + appname) if res.status_code == 200: return True raise HTTPResponseError(res)
[ "def", "enable_app", "(", "self", ",", "appname", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'POST'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'apps/'", "+", "appname", ")", "if", "res", ".", "status_code", "==", "200", ":", "retur...
Enable an app through provisioning_api :param appname: Name of app to be enabled :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Enable", "an", "app", "through", "provisioning_api" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1601-L1614
21,390
owncloud/pyocclient
owncloud/owncloud.py
Client._encode_string
def _encode_string(s): """Encodes a unicode instance to utf-8. If a str is passed it will simply be returned :param s: str or unicode to encode :returns: encoded output as str """ if six.PY2 and isinstance(s, unicode): return s.encode('utf-8') return s
python
def _encode_string(s): if six.PY2 and isinstance(s, unicode): return s.encode('utf-8') return s
[ "def", "_encode_string", "(", "s", ")", ":", "if", "six", ".", "PY2", "and", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", ".", "encode", "(", "'utf-8'", ")", "return", "s" ]
Encodes a unicode instance to utf-8. If a str is passed it will simply be returned :param s: str or unicode to encode :returns: encoded output as str
[ "Encodes", "a", "unicode", "instance", "to", "utf", "-", "8", ".", "If", "a", "str", "is", "passed", "it", "will", "simply", "be", "returned" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1644-L1653
21,391
owncloud/pyocclient
owncloud/owncloud.py
Client._check_ocs_status
def _check_ocs_status(tree, accepted_codes=[100]): """Checks the status code of an OCS request :param tree: response parsed with elementtree :param accepted_codes: list of statuscodes we consider good. E.g. [100,102] can be used to accept a POST returning an 'already exists' condition :raises: HTTPResponseError if the http status is not 200, or OCSResponseError if the OCS status is not one of the accepted_codes. """ code_el = tree.find('meta/statuscode') if code_el is not None and int(code_el.text) not in accepted_codes: r = requests.Response() msg_el = tree.find('meta/message') if msg_el is None: msg_el = tree # fallback to the entire ocs response, if we find no message. r._content = ET.tostring(msg_el) r.status_code = int(code_el.text) raise OCSResponseError(r)
python
def _check_ocs_status(tree, accepted_codes=[100]): code_el = tree.find('meta/statuscode') if code_el is not None and int(code_el.text) not in accepted_codes: r = requests.Response() msg_el = tree.find('meta/message') if msg_el is None: msg_el = tree # fallback to the entire ocs response, if we find no message. r._content = ET.tostring(msg_el) r.status_code = int(code_el.text) raise OCSResponseError(r)
[ "def", "_check_ocs_status", "(", "tree", ",", "accepted_codes", "=", "[", "100", "]", ")", ":", "code_el", "=", "tree", ".", "find", "(", "'meta/statuscode'", ")", "if", "code_el", "is", "not", "None", "and", "int", "(", "code_el", ".", "text", ")", "n...
Checks the status code of an OCS request :param tree: response parsed with elementtree :param accepted_codes: list of statuscodes we consider good. E.g. [100,102] can be used to accept a POST returning an 'already exists' condition :raises: HTTPResponseError if the http status is not 200, or OCSResponseError if the OCS status is not one of the accepted_codes.
[ "Checks", "the", "status", "code", "of", "an", "OCS", "request" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1656-L1672
21,392
owncloud/pyocclient
owncloud/owncloud.py
Client.make_ocs_request
def make_ocs_request(self, method, service, action, **kwargs): """Makes a OCS API request and analyses the response :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance """ accepted_codes = kwargs.pop('accepted_codes', [100]) res = self._make_ocs_request(method, service, action, **kwargs) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, accepted_codes=accepted_codes) return res raise OCSResponseError(res)
python
def make_ocs_request(self, method, service, action, **kwargs): accepted_codes = kwargs.pop('accepted_codes', [100]) res = self._make_ocs_request(method, service, action, **kwargs) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, accepted_codes=accepted_codes) return res raise OCSResponseError(res)
[ "def", "make_ocs_request", "(", "self", ",", "method", ",", "service", ",", "action", ",", "*", "*", "kwargs", ")", ":", "accepted_codes", "=", "kwargs", ".", "pop", "(", "'accepted_codes'", ",", "[", "100", "]", ")", "res", "=", "self", ".", "_make_oc...
Makes a OCS API request and analyses the response :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance
[ "Makes", "a", "OCS", "API", "request", "and", "analyses", "the", "response" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1674-L1692
21,393
owncloud/pyocclient
owncloud/owncloud.py
Client._make_ocs_request
def _make_ocs_request(self, method, service, action, **kwargs): """Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance """ slash = '' if service: slash = '/' path = self.OCS_BASEPATH + service + slash + action attributes = kwargs.copy() if 'headers' not in attributes: attributes['headers'] = {} attributes['headers']['OCS-APIREQUEST'] = 'true' if self._debug: print('OCS request: %s %s %s' % (method, self.url + path, attributes)) res = self._session.request(method, self.url + path, **attributes) return res
python
def _make_ocs_request(self, method, service, action, **kwargs): slash = '' if service: slash = '/' path = self.OCS_BASEPATH + service + slash + action attributes = kwargs.copy() if 'headers' not in attributes: attributes['headers'] = {} attributes['headers']['OCS-APIREQUEST'] = 'true' if self._debug: print('OCS request: %s %s %s' % (method, self.url + path, attributes)) res = self._session.request(method, self.url + path, **attributes) return res
[ "def", "_make_ocs_request", "(", "self", ",", "method", ",", "service", ",", "action", ",", "*", "*", "kwargs", ")", ":", "slash", "=", "''", "if", "service", ":", "slash", "=", "'/'", "path", "=", "self", ".", "OCS_BASEPATH", "+", "service", "+", "s...
Makes a OCS API request :param method: HTTP method :param service: service name :param action: action path :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns :class:`requests.Response` instance
[ "Makes", "a", "OCS", "API", "request" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1694-L1720
21,394
owncloud/pyocclient
owncloud/owncloud.py
Client._make_dav_request
def _make_dav_request(self, method, path, **kwargs): """Makes a WebDAV request :param method: HTTP method :param path: remote path of the targetted file :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns array of :class:`FileInfo` if the response contains it, or True if the operation succeded, False if it didn't """ if self._debug: print('DAV request: %s %s' % (method, path)) if kwargs.get('headers'): print('Headers: ', kwargs.get('headers')) path = self._normalize_path(path) res = self._session.request( method, self._webdav_url + parse.quote(self._encode_string(path)), **kwargs ) if self._debug: print('DAV status: %i' % res.status_code) if res.status_code in [200, 207]: return self._parse_dav_response(res) if res.status_code in [204, 201]: return True raise HTTPResponseError(res)
python
def _make_dav_request(self, method, path, **kwargs): if self._debug: print('DAV request: %s %s' % (method, path)) if kwargs.get('headers'): print('Headers: ', kwargs.get('headers')) path = self._normalize_path(path) res = self._session.request( method, self._webdav_url + parse.quote(self._encode_string(path)), **kwargs ) if self._debug: print('DAV status: %i' % res.status_code) if res.status_code in [200, 207]: return self._parse_dav_response(res) if res.status_code in [204, 201]: return True raise HTTPResponseError(res)
[ "def", "_make_dav_request", "(", "self", ",", "method", ",", "path", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_debug", ":", "print", "(", "'DAV request: %s %s'", "%", "(", "method", ",", "path", ")", ")", "if", "kwargs", ".", "get", "("...
Makes a WebDAV request :param method: HTTP method :param path: remote path of the targetted file :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns array of :class:`FileInfo` if the response contains it, or True if the operation succeded, False if it didn't
[ "Makes", "a", "WebDAV", "request" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1722-L1749
21,395
owncloud/pyocclient
owncloud/owncloud.py
Client._parse_dav_response
def _parse_dav_response(self, res): """Parses the DAV responses from a multi-status response :param res: DAV response :returns array of :class:`FileInfo` or False if the operation did not succeed """ if res.status_code == 207: tree = ET.fromstring(res.content) items = [] for child in tree: items.append(self._parse_dav_element(child)) return items return False
python
def _parse_dav_response(self, res): if res.status_code == 207: tree = ET.fromstring(res.content) items = [] for child in tree: items.append(self._parse_dav_element(child)) return items return False
[ "def", "_parse_dav_response", "(", "self", ",", "res", ")", ":", "if", "res", ".", "status_code", "==", "207", ":", "tree", "=", "ET", ".", "fromstring", "(", "res", ".", "content", ")", "items", "=", "[", "]", "for", "child", "in", "tree", ":", "i...
Parses the DAV responses from a multi-status response :param res: DAV response :returns array of :class:`FileInfo` or False if the operation did not succeed
[ "Parses", "the", "DAV", "responses", "from", "a", "multi", "-", "status", "response" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1751-L1764
21,396
owncloud/pyocclient
owncloud/owncloud.py
Client._parse_dav_element
def _parse_dav_element(self, dav_response): """Parses a single DAV element :param dav_response: DAV response :returns :class:`FileInfo` """ href = parse.unquote( self._strip_dav_path(dav_response.find('{DAV:}href').text) ) if six.PY2: href = href.decode('utf-8') file_type = 'file' if href[-1] == '/': file_type = 'dir' file_attrs = {} attrs = dav_response.find('{DAV:}propstat') attrs = attrs.find('{DAV:}prop') for attr in attrs: file_attrs[attr.tag] = attr.text return FileInfo(href, file_type, file_attrs)
python
def _parse_dav_element(self, dav_response): href = parse.unquote( self._strip_dav_path(dav_response.find('{DAV:}href').text) ) if six.PY2: href = href.decode('utf-8') file_type = 'file' if href[-1] == '/': file_type = 'dir' file_attrs = {} attrs = dav_response.find('{DAV:}propstat') attrs = attrs.find('{DAV:}prop') for attr in attrs: file_attrs[attr.tag] = attr.text return FileInfo(href, file_type, file_attrs)
[ "def", "_parse_dav_element", "(", "self", ",", "dav_response", ")", ":", "href", "=", "parse", ".", "unquote", "(", "self", ".", "_strip_dav_path", "(", "dav_response", ".", "find", "(", "'{DAV:}href'", ")", ".", "text", ")", ")", "if", "six", ".", "PY2"...
Parses a single DAV element :param dav_response: DAV response :returns :class:`FileInfo`
[ "Parses", "a", "single", "DAV", "element" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1766-L1789
21,397
owncloud/pyocclient
owncloud/owncloud.py
Client._webdav_move_copy
def _webdav_move_copy(self, remote_path_source, remote_path_target, operation): """Copies or moves a remote file or directory :param remote_path_source: source file or folder to copy / move :param remote_path_target: target file to which to copy / move :param operation: MOVE or COPY :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned """ if operation != "MOVE" and operation != "COPY": return False if remote_path_target[-1] == '/': remote_path_target += os.path.basename(remote_path_source) if not (remote_path_target[0] == '/'): remote_path_target = '/' + remote_path_target remote_path_source = self._normalize_path(remote_path_source) headers = { 'Destination': self._webdav_url + parse.quote( self._encode_string(remote_path_target)) } return self._make_dav_request( operation, remote_path_source, headers=headers )
python
def _webdav_move_copy(self, remote_path_source, remote_path_target, operation): if operation != "MOVE" and operation != "COPY": return False if remote_path_target[-1] == '/': remote_path_target += os.path.basename(remote_path_source) if not (remote_path_target[0] == '/'): remote_path_target = '/' + remote_path_target remote_path_source = self._normalize_path(remote_path_source) headers = { 'Destination': self._webdav_url + parse.quote( self._encode_string(remote_path_target)) } return self._make_dav_request( operation, remote_path_source, headers=headers )
[ "def", "_webdav_move_copy", "(", "self", ",", "remote_path_source", ",", "remote_path_target", ",", "operation", ")", ":", "if", "operation", "!=", "\"MOVE\"", "and", "operation", "!=", "\"COPY\"", ":", "return", "False", "if", "remote_path_target", "[", "-", "1...
Copies or moves a remote file or directory :param remote_path_source: source file or folder to copy / move :param remote_path_target: target file to which to copy / move :param operation: MOVE or COPY :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
[ "Copies", "or", "moves", "a", "remote", "file", "or", "directory" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1801-L1832
21,398
owncloud/pyocclient
owncloud/owncloud.py
Client._xml_to_dict
def _xml_to_dict(self, element): """ Take an XML element, iterate over it and build a dict :param element: An xml.etree.ElementTree.Element, or a list of the same :returns: A dictionary """ return_dict = {} for el in element: return_dict[el.tag] = None children = el.getchildren() if children: return_dict[el.tag] = self._xml_to_dict(children) else: return_dict[el.tag] = el.text return return_dict
python
def _xml_to_dict(self, element): return_dict = {} for el in element: return_dict[el.tag] = None children = el.getchildren() if children: return_dict[el.tag] = self._xml_to_dict(children) else: return_dict[el.tag] = el.text return return_dict
[ "def", "_xml_to_dict", "(", "self", ",", "element", ")", ":", "return_dict", "=", "{", "}", "for", "el", "in", "element", ":", "return_dict", "[", "el", ".", "tag", "]", "=", "None", "children", "=", "el", ".", "getchildren", "(", ")", "if", "childre...
Take an XML element, iterate over it and build a dict :param element: An xml.etree.ElementTree.Element, or a list of the same :returns: A dictionary
[ "Take", "an", "XML", "element", "iterate", "over", "it", "and", "build", "a", "dict" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1834-L1849
21,399
owncloud/pyocclient
owncloud/owncloud.py
Client._get_shareinfo
def _get_shareinfo(self, data_el): """Simple helper which returns instance of ShareInfo class :param data_el: 'data' element extracted from _make_ocs_request :returns: instance of ShareInfo class """ if (data_el is None) or not (isinstance(data_el, ET.Element)): return None return ShareInfo(self._xml_to_dict(data_el))
python
def _get_shareinfo(self, data_el): if (data_el is None) or not (isinstance(data_el, ET.Element)): return None return ShareInfo(self._xml_to_dict(data_el))
[ "def", "_get_shareinfo", "(", "self", ",", "data_el", ")", ":", "if", "(", "data_el", "is", "None", ")", "or", "not", "(", "isinstance", "(", "data_el", ",", "ET", ".", "Element", ")", ")", ":", "return", "None", "return", "ShareInfo", "(", "self", "...
Simple helper which returns instance of ShareInfo class :param data_el: 'data' element extracted from _make_ocs_request :returns: instance of ShareInfo class
[ "Simple", "helper", "which", "returns", "instance", "of", "ShareInfo", "class" ]
b9e1f04cdbde74588e86f1bebb6144571d82966c
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1851-L1859