sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_age(dt): """Calculate delta between current time and datetime and return a human readable form of the delta object""" delta = datetime.now() - dt days = delta.days hours, rem = divmod(delta.seconds, 3600) minutes, seconds = divmod(rem, 60) if days: re...
Calculate delta between current time and datetime and return a human readable form of the delta object
entailment
def json_obj(self, method, params=None, auth=True): """Return JSON object expected by the Zabbix API""" if params is None: params = {} obj = { 'jsonrpc': '2.0', 'method': method, 'params': params, 'auth': self.__auth if auth else None,...
Return JSON object expected by the Zabbix API
entailment
def do_request(self, json_obj): """Perform one HTTP request to Zabbix API""" self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers) self.debug('Request: body=%s', json_obj) self.r_query.append(json_obj) request = urllib2.Request(url=self._api_url, data=jso...
Perform one HTTP request to Zabbix API
entailment
def login(self, user=None, password=None, save=True): """Perform a user.login API request""" if user and password: if save: self.__username = user self.__password = password elif self.__username and self.__password: user = self.__username ...
Perform a user.login API request
entailment
def relogin(self): """Perform a re-login""" try: self.__auth = None # reset auth before relogin self.login() except ZabbixAPIException as e: self.log(ERROR, 'Zabbix API relogin error (%s)', e) self.__auth = None # logged_in() will always return F...
Perform a re-login
entailment
def check_auth(self): """Perform a re-login if not signed in or raise an exception""" if not self.logged_in: if self.relogin_interval and self.last_login and (time() - self.last_login) > self.relogin_interval: self.log(WARNING, 'Zabbix API not logged in. Performing Zabbix API...
Perform a re-login if not signed in or raise an exception
entailment
def call(self, method, params=None): """Check authentication and perform actual API request and relogin if needed""" start_time = time() self.check_auth() self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method) self.log(DEBUG, '\twith parameters: %...
Check authentication and perform actual API request and relogin if needed
entailment
def download_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1, no_redirects = False, pos = 0, mode = 's'): """ download function to download parallely """ global main_it global exit_flag global total_chunks global file_name global i_max file_name[idx]= url.split('/')[-1] file_addres...
download function to download parallely
entailment
def download_parallel_gui(root, urls, directory, min_file_size, max_file_size, no_redirects): """ called when paralled downloading is true """ global parallel # create directory to save files if not os.path.exists(directory): os.makedirs(directory) parallel = True app = progress_class(root, urls, directory, ...
called when paralled downloading is true
entailment
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects): """ called when user wants serial downloading """ # create directory to save files if not os.path.exists(directory): os.makedirs(directory) app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_...
called when user wants serial downloading
entailment
def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max...
function called when thread is started
entailment
def start(self): """ function to initialize thread for downloading """ global parallel for self.i in range(0, self.length): if parallel: self.thread.append(myThread(self.url[ self.i ], self.directory, self.i, self.min_file_size, self.max_file_size, self.no_redirects)) else: # if not ...
function to initialize thread for downloading
entailment
def read_bytes(self): """ reading bytes; update progress bar after 1 ms """ global exit_flag for self.i in range(0, self.length) : self.bytes[self.i] = i_max[self.i] self.maxbytes[self.i] = total_chunks[self.i] self.progress[self.i]["maximum"] = total_chunks[self.i] self.progress[self.i]["value"]...
reading bytes; update progress bar after 1 ms
entailment
def declare_type(self, declared_type): # type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" if declared_type not in self.collected_types: self.collected_types[declared_type.name] = declared_type return declared_type
Add this type to our collection, if needed.
entailment
def get_metaschema(): # type: () -> Tuple[Names, List[Dict[Text, Any]], Loader] """Instantiate the metaschema.""" loader = ref_resolver.Loader({ "Any": "https://w3id.org/cwl/salad#Any", "ArraySchema": "https://w3id.org/cwl/salad#ArraySchema", "Array_symbol": "https://w3id.org/cwl/salad#...
Instantiate the metaschema.
entailment
def add_namespaces(metadata, namespaces): # type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None """Collect the provided namespaces, checking for conflicts.""" for key, value in metadata.items(): if key not in namespaces: namespaces[key] = value elif namespaces[key] != ...
Collect the provided namespaces, checking for conflicts.
entailment
def collect_namespaces(metadata): # type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" namespaces = {} # type: Dict[Text, Text] if "$import_metadata" in metadata: for value in metadata["$import_metadata"].values(): ...
Walk through the metadata object, collecting namespace declarations.
entailment
def load_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text] cache=None # type: Dict ): # type: (...) -> Tuple[Loader, Union[Names, SchemaParseException], Dict[Text, Any], Loader] """ Load a schema that can be used to validate documents using load_and_valida...
Load a schema that can be used to validate documents using load_and_validate. return: document_loader, avsc_names, schema_metadata, metaschema_loader
entailment
def load_and_validate(document_loader, # type: Loader avsc_names, # type: Names document, # type: Union[CommentedMap, Text] strict, # type: bool st...
Load a document and validate it with the provided schema. return data, metadata
entailment
def validate_doc(schema_names, # type: Names doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None] loader, # type: Loader strict, # type: bool strict_foreign_properties=False # type: bool ): ...
Validate a document using the provided schema.
entailment
def get_anon_name(rec): # type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" if "name" in rec: return rec["name"] anon_name = "" if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'): for sym in rec["symbols"]: anon_...
Calculate a reproducible name for anonymous types.
entailment
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True): # type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any """ Go through and replace types in the 'spec' mapping""" if isinstance(items, MutableMapping): # recursively check these fields for types to replace ...
Go through and replace types in the 'spec' mapping
entailment
def avro_name(url): # type: (AnyStr) -> AnyStr """ Turn a URL into an Avro-safe name. If the URL has no fragment, return this plain URL. Extract either the last part of the URL fragment past the slash, otherwise the whole fragment. """ frg = urllib.parse.urldefrag(url)[1] if frg != ''...
Turn a URL into an Avro-safe name. If the URL has no fragment, return this plain URL. Extract either the last part of the URL fragment past the slash, otherwise the whole fragment.
entailment
def make_valid_avro(items, # type: Avro alltypes, # type: Dict[Text, Dict[Text, Any]] found, # type: Set[Text] union=False # type: bool ): # type: (...) -> Union[Avro, Dict, Text] """Convert our schema to...
Convert our schema to be more avro like.
entailment
def deepcopy_strip(item): # type: (Any) -> Any """ Make a deep copy of list and dict objects. Intentionally do not copy attributes. This is to discard CommentedMap and CommentedSeq metadata which is very expensive with regular copy.deepcopy. """ if isinstance(item, MutableMapping): r...
Make a deep copy of list and dict objects. Intentionally do not copy attributes. This is to discard CommentedMap and CommentedSeq metadata which is very expensive with regular copy.deepcopy.
entailment
def extend_and_specialize(items, loader): # type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]] """ Apply 'extend' and 'specialize' to fully materialize derived record types. """ items = deepcopy_strip(items) types = {i["name"]: i for i in items} # type: Dict[Text, Any] results ...
Apply 'extend' and 'specialize' to fully materialize derived record types.
entailment
def make_avro_schema(i, # type: List[Any] loader # type: Loader ): # type: (...) -> Names """ All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. ...
All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output.
entailment
def shortname(inputid): # type: (Text) -> Text """Returns the last segment of the provided fragment or path.""" parsed_id = urllib.parse.urlparse(inputid) if parsed_id.fragment: return parsed_id.fragment.split(u"/")[-1] return parsed_id.path.split(u"/")[-1]
Returns the last segment of the provided fragment or path.
entailment
def print_inheritance(doc, stream): # type: (List[Dict[Text, Any]], IO) -> None """Write a Grapviz inheritance graph for the supplied document.""" stream.write("digraph {\n") for entry in doc: if entry["type"] == "record": label = name = shortname(entry["name"]) fields = ...
Write a Grapviz inheritance graph for the supplied document.
entailment
def print_fieldrefs(doc, loader, stream): # type: (List[Dict[Text, Any]], Loader, IO) -> None """Write a GraphViz graph of the relationships between the fields.""" obj = extend_and_specialize(doc, loader) primitives = set(("http://www.w3.org/2001/XMLSchema#string", "http://www.w3....
Write a GraphViz graph of the relationships between the fields.
entailment
def get_other_props(all_props, reserved_props): # type: (Dict, Tuple) -> Optional[Dict] """ Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude """ if hasattr(all_props, 'items') and callable(all_props.items): ...
Retrieve the non-reserved properties from a dictionary of properties @args reserved_props: The set of reserved properties to exclude
entailment
def make_avsc_object(json_data, names=None): # type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema """ Build Avro Schema from data parsed out of JSON string. @arg names: A Name object (tracks seen names and default space) """ if names is None: names = Names() ...
Build Avro Schema from data parsed out of JSON string. @arg names: A Name object (tracks seen names and default space)
entailment
def get_space(self): # type: () -> Optional[Text] """Back out a namespace from full name.""" if self._full is None: return None if self._full.find('.') > 0: return self._full.rsplit(".", 1)[0] else: return ""
Back out a namespace from full name.
entailment
def add_name(self, name_attr, space_attr, new_schema): # type: (Text, Optional[Text], NamedSchema) -> Name """ Add a new schema object to the name set. @arg name_attr: name value read in schema @arg space_attr: namespace value read in schema. @return: the Name tha...
Add a new schema object to the name set. @arg name_attr: name value read in schema @arg space_attr: namespace value read in schema. @return: the Name that was just added.
entailment
def make_field_objects(field_data, names): # type: (List[Dict[Text, Text]], Names) -> List[Field] """We're going to need to make message parameters too.""" field_objects = [] field_names = [] # type: List[Text] for field in field_data: if hasattr(field, 'get') and ca...
We're going to need to make message parameters too.
entailment
def search_function(root1, q, s, f, l, o='g'): """ function to get links """ global links links = search(q, o, s, f, l) root1.destroy() root1.quit()
function to get links
entailment
def task(ft): """ to create loading progress bar """ ft.pack(expand = True, fill = BOTH, side = TOP) pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate') pb_hD.pack(expand = True, fill = BOTH, side = TOP) pb_hD.start(50) ft.mainloop()
to create loading progress bar
entailment
def download_content_gui(**args): """ function to fetch links and download them """ global row if not args ['directory']: args ['directory'] = args ['query'].replace(' ', '-') root1 = Frame(root) t1 = threading.Thread(target = search_function, args = (root1, args['query'], args['website'], args['fil...
function to fetch links and download them
entailment
def main(): """ main function """ s = ttk.Style() s.theme_use('clam') ents = makeform(root) root.mainloop()
main function
entailment
def click_download(self, event): """ event for download button """ args ['parallel'] = self.p.get() args ['file_type'] = self.optionmenu.get() args ['no_redirects'] = self.t.get() args ['query'] = self.entry_query.get() args ['min_file_size'] = int( self.entry_min.get()) args ['max_file_size'] = int( ...
event for download button
entailment
def on_entry_click(self, event): """ function that gets called whenever entry is clicked """ if event.widget.config('fg') [4] == 'grey': event.widget.delete(0, "end" ) # delete all the text in the entry event.widget.insert(0, '') #Insert blank for user input event.widget.config(fg = 'black')
function that gets called whenever entry is clicked
entailment
def on_focusout(self, event, a): """ function that gets called whenever anywhere except entry is clicked """ if event.widget.get() == '': event.widget.insert(0, default_text[a]) event.widget.config(fg = 'grey')
function that gets called whenever anywhere except entry is clicked
entailment
def check_threat(self): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if self.optionmenu.get() == el: is_high_threat = True break else: if self.optionmen...
function to check input filetype against threat extensions list
entailment
def ask_dir(self): """ dialogue box for choosing directory """ args ['directory'] = askdirectory(**self.dir_opt) self.dir_text.set(args ['directory'])
dialogue box for choosing directory
entailment
def get_google_links(limit, params, headers): """ function to fetch links equal to limit every Google search result page has a start index. every page contains 10 search results. """ links = [] for start_index in range(0, limit, 10): params['start'] = start_index resp = s.get("https://www.google.com/search"...
function to fetch links equal to limit every Google search result page has a start index. every page contains 10 search results.
entailment
def get_duckduckgo_links(limit, params, headers): """ function to fetch links equal to limit duckduckgo pagination is not static, so there is a limit on maximum number of links that can be scraped """ resp = s.get('https://duckduckgo.com/html', params = params, headers = headers) links = scrape_links(resp.conte...
function to fetch links equal to limit duckduckgo pagination is not static, so there is a limit on maximum number of links that can be scraped
entailment
def scrape_links(html, engine): """ function to scrape file links from html response """ soup = BeautifulSoup(html, 'lxml') links = [] if engine == 'd': results = soup.findAll('a', {'class': 'result__a'}) for result in results: link = result.get('href')[15:] link = link.replace('/blob/', '/raw/') li...
function to scrape file links from html response
entailment
def get_url_nofollow(url): """ function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/ """ try: response = urlopen(url) code = response.getcode() return code except HTTPError as e: return...
function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/
entailment
def validate_links(links): """ function to validate urls based on http(s) prefix and return code """ valid_links = [] for link in links: if link[:7] in "http://" or link[:8] in "https://": valid_links.append(link) if not valid_links: print("No files found.") sys.exit(0) # checking valid urls for retu...
function to validate urls based on http(s) prefix and return code
entailment
def search(query, engine='g', site="", file_type = 'pdf', limit = 10): """ main function to search for links and return valid ones """ if site == "": search_query = "filetype:{0} {1}".format(file_type, query) else: search_query = "site:{0} filetype:{1} {2}".format(site,file_type, query) headers = { 'User A...
main function to search for links and return valid ones
entailment
def check_threats(**args): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if args['file_type'] == el: is_high_threat = True break else: if args['file_type'] == val: ...
function to check input filetype against threat extensions list
entailment
def validate_args(**args): """ function to check if input query is not None and set missing arguments to default value """ if not args['query']: print("\nMissing required query argument.") sys.exit() for key in DEFAULTS: if key not in args: args[key] = DEFAULTS[key] return args
function to check if input query is not None and set missing arguments to default value
entailment
def download_content(**args): """ main function to fetch links and download them """ args = validate_args(**args) if not args['directory']: args['directory'] = args['query'].replace(' ', '-') print("Downloading {0} {1} files on topic {2} from {3} and saving to directory: {4}" .format(args['limit'], args['fi...
main function to fetch links and download them
entailment
def show_filetypes(extensions): """ function to show valid file extensions """ for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in item[1]) print("{0:4}: {1}".format(val, item[0]))
function to show valid file extensions
entailment
def validate_ex(expected_schema, # type: Schema datum, # type: Any identifiers=None, # type: List[Text] strict=False, # type: bool foreign_properties=None, # type: Set...
Determine if a python datum is an instance of a schema.
entailment
def json_dump(obj, # type: Any fp, # type: IO[str] **kwargs # type: Any ): # type: (...) -> None """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' json.dump(convert_to_dict(obj), fp, **kwargs)
Force use of unicode.
entailment
def json_dumps(obj, # type: Any **kwargs # type: Any ): # type: (...) -> str """ Force use of unicode. """ if six.PY2: kwargs['encoding'] = 'utf-8' return json.dumps(convert_to_dict(obj), **kwargs)
Force use of unicode.
entailment
def codegen(lang, # type: str i, # type: List[Dict[Text, Any]] schema_metadata, # type: Dict[Text, Any] loader # type: Loader ): # type: (...) -> None """Generate classes with loaders for the given Schema Salad description.""" ...
Generate classes with loaders for the given Schema Salad description.
entailment
def find(self, name): """ Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subse...
Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subset containing the serach result.
entailment
def reinitialize(self, admin_password=None, debug=False, ConfigureIPv6=False, OSTemplateID=None): """ Reinitialize a VM. :param admin_password: Administrator password. :param debug: Flag to enable debug output. :param ConfigureIPv6: Flag to enable IPv6 on the VM. :param O...
Reinitialize a VM. :param admin_password: Administrator password. :param debug: Flag to enable debug output. :param ConfigureIPv6: Flag to enable IPv6 on the VM. :param OSTemplateID: TemplateID to reinitialize the VM with. :return: True in case of success, otherwise False ...
entailment
def login(self, username, password, load=True): """ Set the authentication data in the object, and if load is True (default is True) it also retrieve the ip list and the vm list in order to build the internal objects list. @param (str) username: username of the cloud @par...
Set the authentication data in the object, and if load is True (default is True) it also retrieve the ip list and the vm list in order to build the internal objects list. @param (str) username: username of the cloud @param (str) password: password of the cloud @param (bool) load:...
entailment
def poweroff_server(self, server=None, server_id=None): """ Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off, server_id: Int or Str representing the ID o...
Poweroff a VM. If possible to pass the VM object or simply the ID of the VM that we want to turn on. Args: server: VM Object that represent the VM to power off, server_id: Int or Str representing the ID of the VM to power off. Returns: return True if json_obj[...
entailment
def get_hypervisors(self): """ Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, otherwise False """ json_scheme = self.gen_def_json_scheme('GetHypervisors') json_obj = self.call_method_p...
Initialize the internal list containing each template available for each hypervisor. :return: [bool] True in case of success, otherwise False
entailment
def get_servers(self): """ Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects (pro or smart) as iterator. :return: bool """ json_scheme = self.gen_def_json_scheme('GetServers') json_obj = self.call_method_post(meth...
Create the list of Server object inside the Datacenter objects. Build an internal list of VM Objects (pro or smart) as iterator. :return: bool
entailment
def find_template(self, name=None, hv=None): """ Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If h...
Return a list of templates that could have one or more elements. Args: name: name of the template to find. hv: the ID of the hypervisor to search the template in Returns: A list of templates object. If hv is None will return all the templates matching the ...
entailment
def purchase_ip(self, debug=False): """ Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object """ json_scheme = self.gen_def_json_scheme('SetPurchaseIpAddress') json_obj = self...
Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object
entailment
def purchase_vlan(self, vlan_name, debug=False): """ Purchase a new VLAN. :param debug: Log the json response if True :param vlan_name: String representing the name of the vlan (virtual switch) :return: a Vlan Object representing the vlan created """ vlan_name = {...
Purchase a new VLAN. :param debug: Log the json response if True :param vlan_name: String representing the name of the vlan (virtual switch) :return: a Vlan Object representing the vlan created
entailment
def remove_vlan(self, vlan_resource_id): """ Remove a VLAN :param vlan_resource_id: :return: """ vlan_id = {'VLanResourceId': vlan_resource_id} json_scheme = self.gen_def_json_scheme('SetRemoveVLan', vlan_id) json_obj = self.call_method_post(method='SetRem...
Remove a VLAN :param vlan_resource_id: :return:
entailment
def remove_ip(self, ip_id): """ Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False """ ip_id = ' "IpAddressResourceId": %s' % ip_id json_scheme = self.gen_...
Delete an Ip from the boughs ip list @param (str) ip_id: a string representing the resource id of the IP @return: True if json method had success else False
entailment
def get_package_id(self, name): """ Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen. """ j...
Retrieve the smart package id given is English name @param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large". @return: The package id that depends on the Data center and the size choosen.
entailment
def get_ip(self): """ Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None """ json_scheme = self.gen_def_json_s...
Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None
entailment
def gen_def_json_scheme(self, req, method_fields=None): """ Generate the scheme for the json request. :param req: String representing the name of the method to call :param method_fields: A dictionary containing the method-specified fields :rtype : json object representing the met...
Generate the scheme for the json request. :param req: String representing the name of the method to call :param method_fields: A dictionary containing the method-specified fields :rtype : json object representing the method call
entailment
def _commit(self): """ :return: (dict) Response object content """ assert self.uri is not None, Exception("BadArgument: uri property cannot be None") url = '{}/{}'.format(self.uri, self.__class__.__name__) serialized_json = jsonpickle.encode(self, unpicklable=False, ) ...
:return: (dict) Response object content
entailment
def get(self): """ Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries """ request = self._call(GetSharedStorages) response = request.commit() return response['Value']
Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries
entailment
def purchase_iscsi(self, quantity, iqn, name, protocol=SharedStorageProtocolType.ISCSI): """ :type quantity: int :type iqn: list[str] :type name: str :type protocol: SharedStorageProtocols :param quantity: Amount of GB :param iqn: List of IQN represented in string...
:type quantity: int :type iqn: list[str] :type name: str :type protocol: SharedStorageProtocols :param quantity: Amount of GB :param iqn: List of IQN represented in string format :param name: Name of the resource :param protocol: Protocol to use :return:
entailment
def _get(self, *args, **kwargs): """Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.get(*args, **kwargs) r...
Wrapper around Requests for GET requests Returns: Response: A Requests Response object
entailment
def _get_xml(self, *args, **kwargs): """Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object """ req = self.session_xml.get(*args, **kwargs) return req
Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object
entailment
def _post(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.post(*args, **kwargs) ...
Wrapper around Requests for POST requests Returns: Response: A Requests Response object
entailment
def _post_xml(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session_xml.post(*args, **kwargs...
Wrapper around Requests for POST requests Returns: Response: A Requests Response object
entailment
def _put(self, *args, **kwargs): """Wrapper around Requests for PUT requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.put(*args, **kwargs) r...
Wrapper around Requests for PUT requests Returns: Response: A Requests Response object
entailment
def _delete(self, *args, **kwargs): """Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.delete(*args, **kwargs) ...
Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object
entailment
def auth_ping(self): """Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: Tru...
Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: True if the application authenticat...
entailment
def auth_user(self, username, password): """Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: ...
Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: A dict mapping of user attributes if the ...
entailment
def get_session(self, username, password, remote="127.0.0.1", proxy=None): """Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: ...
Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: The remote address of the user. This can be used to create multiple co...
entailment
def validate_session(self, token, remote="127.0.0.1", proxy=None): """Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The ...
Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The session token. remote: The remote address of the user. ...
entailment
def terminate_session(self, token): """Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed "...
Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed
entailment
def add_user(self, username, raise_on_error=False, **kwargs): """Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory ...
Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory email: mandatory first_name: optional ...
entailment
def get_user(self, username): """Retrieve information about a user Returns: dict: User information None: If no user or failure occurred """ response = self._get(self.rest_url + "/user", params={"username": username, ...
Retrieve information about a user Returns: dict: User information None: If no user or failure occurred
entailment
def set_active(self, username, active_state): """Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred """ if active_stat...
Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred
entailment
def set_user_attribute(self, username, attribute, value, raise_on_error=False): """Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: T...
Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: True on success, False on failure.
entailment
def add_user_to_group(self, username, groupname, raise_on_error=False): """Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure. """ data = { ...
Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure.
entailment
def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: ...
Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful
entailment
def change_password(self, username, newpassword, raise_on_error=False): """Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succ...
Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded False: If unsuccessful
entailment
def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/pass...
Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful
entailment
def get_nested_groups(self, username): """Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names. """ response = self...
Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names.
entailment
def get_nested_group_users(self, groupname): """Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names. """ response = sel...
Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names.
entailment
def user_exists(self, username): """Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application. """ response = self._get(self.rest_url + "/user", ...
Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application.
entailment
def get_memberships(self): """Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ response = self._get_xml(self.rest_url + "/group/membership") if not response.ok: return None ...
Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups)
entailment
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999): """Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or ...
Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or 'group' property_name: eg. 'email', 'name' search_string: the string to search for...
entailment
def versions(self) -> List(BlenderVersion): """ The versions associated with Blender """ return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)]
The versions associated with Blender
entailment