INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
a pylsdj. Table referencing the instrument s table or None if the instrument doesn t have a table
def table(self): """a ```pylsdj.Table``` referencing the instrument's table, or None if the instrument doesn't have a table""" if hasattr(self.data, 'table_on') and self.data.table_on: assert_index_sane(self.data.table, len(self.song.tables)) return self.song.tables[self....
import from an lsdinst struct
def import_lsdinst(self, struct_data): """import from an lsdinst struct""" self.name = struct_data['name'] self.automate = struct_data['data']['automate'] self.pan = struct_data['data']['pan'] if self.table is not None: self.table.import_lsdinst(struct_data)
Export this instrument s settings to a file.
def export_to_file(self, filename): """Export this instrument's settings to a file. :param filename: the name of the file """ instr_json = self.export_struct() with open(filename, 'w') as fp: json.dump(instr_json, fp, indent=2)
Write this sample to a WAV file.
def write_wav(self, filename): """Write this sample to a WAV file. :param filename: the file to which to write """ wave_output = None try: wave_output = wave.open(filename, 'w') wave_output.setparams(WAVE_PARAMS) frames = bytearray([x << 4 ...
Read sample data for this sample from a WAV file.
def read_wav(self, filename): """Read sample data for this sample from a WAV file. :param filename: the file from which to read """ wave_input = None try: wave_input = wave.open(filename, 'r') wave_frames = bytearray( wave_input.readframe...
find the local ip address on the given device
def get_device_address(device): """ find the local ip address on the given device """ if device is None: return None command = ['ip', 'route', 'list', 'dev', device] ip_routes = subprocess.check_output(command).strip() for line in ip_routes.split('\n'): seen = '' for a in lin...
Find the device where the default route is.
def get_default_net_device(): """ Find the device where the default route is. """ with open('/proc/net/route') as fh: for line in fh: iface, dest, _ = line.split(None, 2) if dest == '00000000': return iface return None
Adds key - value pairs to the passed dictionary so that afterwards the dictionary can be used without needing to check for KeyErrors.
def add_missing_optional_args_with_value_none(args, optional_args): ''' Adds key-value pairs to the passed dictionary, so that afterwards, the dictionary can be used without needing to check for KeyErrors. If the keys passed as a second argument are not present, they are added with ...
Checks whether all mandatory arguments are passed.
def check_presence_of_mandatory_args(args, mandatory_args): ''' Checks whether all mandatory arguments are passed. This function aims at methods with many arguments which are passed as kwargs so that the order in which the are passed does not matter. :args: The dictionary passed as arg...
Retrieves the size in bytes of this ZIP content.: return: Size of the zip content in bytes
def size(self, store_hashes=True): """ Retrieves the size in bytes of this ZIP content. :return: Size of the zip content in bytes """ if self.modified: self.__cache_content(store_hashes) return len(self.cached_content)
Monkey patch the django. db. migrations. writer. MIGRATION_TEMPLATE
def monkey_patch_migration_template(self, app, fixture_path): """ Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we don't have to do any complex regex or reflection. It's hacky... but wo...
Return true if it looks like a migration already exists.
def migration_exists(self, app, fixture_path): """ Return true if it looks like a migration already exists. """ base_name = os.path.basename(fixture_path) # Loop through all migrations for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')): ...
Create a data migration for app that uses fixture_path.
def create_migration(self, app, fixture_path): """ Create a data migration for app that uses fixture_path. """ self.monkey_patch_migration_template(app, fixture_path) out = StringIO() management.call_command('makemigrations', app.label, empty=True, stdout=out) s...
Initialize client with read access and with search function.
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config): ''' Initialize client with read access and with search function. :param handle_server_url: The URL of the Handle Server. May be None (then, the default 'https://hdl.hand...
Initialize client against an HSv8 instance with full read/ write access.
def instantiate_with_username_and_password(handle_server_url, username, password, **config): ''' Initialize client against an HSv8 instance with full read/write access. The method will throw an exception upon bad syntax or non-existing Handle. The existence or validity of the password i...
Initialize the client against an HSv8 instance with full read/ write access.
def instantiate_with_credentials(credentials, **config): ''' Initialize the client against an HSv8 instance with full read/write access. :param credentials: A credentials object, see separate class PIDClientCredentials. :param \**config: More key-value pairs may be p...
Retrieve a handle record from the Handle server as a complete nested dict ( including index ttl timestamp... ) for later use.
def retrieve_handle_record_json(self, handle): ''' Retrieve a handle record from the Handle server as a complete nested dict (including index, ttl, timestamp, ...) for later use. Note: For retrieving a simple dict with only the keys and values, please use :meth:`~b2handle.handle...
Retrieve a handle record from the Handle server as a dict. If there is several entries of the same type only the first one is returned. Values of complex types ( such as HS_ADMIN ) are transformed to strings.
def retrieve_handle_record(self, handle, handlerecord_json=None): ''' Retrieve a handle record from the Handle server as a dict. If there is several entries of the same type, only the first one is returned. Values of complex types (such as HS_ADMIN) are transformed to strings. ...
Retrieve a single value from a single Handle. If several entries with this key exist the methods returns the first one. If the handle does not exist the method will raise a HandleNotFoundException.
def get_value_from_handle(self, handle, key, handlerecord_json=None): ''' Retrieve a single value from a single Handle. If several entries with this key exist, the methods returns the first one. If the handle does not exist, the method will raise a HandleNotFoundException. :para...
Checks if there is a 10320/ LOC entry in the handle record. * Note: * In the unlikely case that there is a 10320/ LOC entry but it does not contain any locations it is treated as if there was none.
def is_10320LOC_empty(self, handle, handlerecord_json=None): ''' Checks if there is a 10320/LOC entry in the handle record. *Note:* In the unlikely case that there is a 10320/LOC entry, but it does not contain any locations, it is treated as if there was none. :param handle: The...
Register a new Handle with a unique random name ( random UUID ).
def generate_and_register_handle(self, prefix, location, checksum=None, additional_URLs=None, **extratypes): ''' Register a new Handle with a unique random name (random UUID). :param prefix: The prefix of the handle to be registered. The method will generate a suffix. :param...
Modify entries ( key - value - pairs ) in a handle record. If the key does not exist yet it is created.
def modify_handle_value(self, handle, ttl=None, add_if_not_exist=True, **kvpairs): ''' Modify entries (key-value-pairs) in a handle record. If the key does not exist yet, it is created. *Note:* We assume that a key exists only once. In case a key exists several time, an exceptio...
Delete a key - value pair from a handle record. If the key exists more than once all key - value pairs with this key are deleted.
def delete_handle_value(self, handle, key): ''' Delete a key-value pair from a handle record. If the key exists more than once, all key-value pairs with this key are deleted. :param handle: Handle from whose record the entry should be deleted. :param key: Key to be deleted. Also...
Delete the handle and its handle record. If the Handle is not found an Exception is raised.
def delete_handle(self, handle, *other): '''Delete the handle and its handle record. If the Handle is not found, an Exception is raised. :param handle: Handle to be deleted. :param other: Deprecated. This only exists to catch wrong method usage by users who are used to delete handle...
Exchange an URL in the 10320/ LOC entry against another keeping the same id and other attributes.
def exchange_additional_URL(self, handle, old, new): ''' Exchange an URL in the 10320/LOC entry against another, keeping the same id and other attributes. :param handle: The handle to modify. :param old: The URL to replace. :param new: The URL to set as new URL. ...
Add a URL entry to the handle record s 10320/ LOC entry. If 10320/ LOC does not exist yet it is created. If the 10320/ LOC entry already contains the URL it is not added a second time.
def add_additional_URL(self, handle, *urls, **attributes): ''' Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC does not exist yet, it is created. If the 10320/LOC entry already contains the URL, it is not added a second time. :param handle: The handle to add...
Remove a URL from the handle record s 10320/ LOC entry.
def remove_additional_URL(self, handle, *urls): ''' Remove a URL from the handle record's 10320/LOC entry. :param handle: The handle to modify. :param urls: The URL(s) to be removed. Several URLs may be specified. :raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException...
Registers a new Handle with given name. If the handle already exists and overwrite is not set to True the method will throw an exception.
def register_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes): ''' Registers a new Handle with given name. If the handle already exists and overwrite is not set to True, the method will throw an exception. :param handle: The full...
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as - is. The servlet is supposed to be case - insensitive but if it isn t the wrong case will cause a: exc: ~b2handle. handleexceptions. ReverseLookupException.
def search_handle(self, URL=None, prefix=None, **key_value_pairs): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, th...
Generate a unique random Handle name ( random UUID ). The Handle is not registered. If a prefix is specified the PID name has the syntax <prefix >/ <generatedname > otherwise it just returns the generated random name ( suffix for the Handle ).
def generate_PID_name(self, prefix=None): ''' Generate a unique random Handle name (random UUID). The Handle is not registered. If a prefix is specified, the PID name has the syntax <prefix>/<generatedname>, otherwise it just returns the generated random name (suffix for the Hand...
Finds the Handle entry indices of all entries that have a specific type.
def get_handlerecord_indices_for_key(self, key, list_of_entries): ''' Finds the Handle entry indices of all entries that have a specific type. *Important:* It finds the Handle System indices! These are not the python indices of the list, so they can not be used for itera...
Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record using the requests module.
def __send_handle_delete_request(self, handle, indices=None, op=None): ''' Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :p...
Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record using the requests module.
def __send_handle_put_request(self, handle, list_of_entries, indices=None, overwrite=False, op=None): ''' Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record, using the requests module. :param hand...
Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record using the requests module.
def __send_handle_get_request(self, handle, indices=None): ''' Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Opt...
Returns the handle record if it is None or if its handle is not the same as the specified handle.
def __get_handle_record_if_necessary(self, handle, handlerecord_json): ''' Returns the handle record if it is None or if its handle is not the same as the specified handle. ''' if handlerecord_json is None: handlerecord_json = self.retrieve_handle_record_json(han...
Find an index not yet used in the handle record and not reserved for any ( other ) special type.
def __make_another_index(self, list_of_entries, url=False, hs_admin=False): ''' Find an index not yet used in the handle record and not reserved for any (other) special type. :param: list_of_entries: List of all entries to find which indices are used already. :pa...
Create an entry of any type except HS_ADMIN.
def __create_entry(self, entrytype, data, index, ttl=None): ''' Create an entry of any type except HS_ADMIN. :param entrytype: THe type of entry to create, e.g. 'URL' or 'checksum' or ... Note: For entries of type 'HS_ADMIN', please use __create_admin_entry(). For type '...
Create an entry of type HS_ADMIN.
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None): ''' Create an entry of type "HS_ADMIN". :param username: The username, i.e. a handle with an index (index:prefix/suffix). The value referenced by the index contains authentcation informati...
Finds the indices of all entries that have a specific type. Important: This method finds the python indices of the list of entries! These are not the Handle System index values!
def __get_python_indices_for_key(self, key, list_of_entries): ''' Finds the indices of all entries that have a specific type. Important: This method finds the python indices of the list of entries! These are not the Handle System index values! :param key: The key (Handle...
Exchange every occurrence of oldurl against newurl in a 10320/ LOC entry. This does not change the ids or other xml attributes of the <location > element.
def __exchange_URL_in_13020loc(self, oldurl, newurl, list_of_entries, handle): ''' Exchange every occurrence of oldurl against newurl in a 10320/LOC entry. This does not change the ids or other xml attributes of the <location> element. :param oldurl: The URL that will be...
Remove an URL from the handle record s 10320/ LOC entry. If it exists several times in the entry all occurences are removed. If the URL is not present nothing happens. If after removing there is no more URLs in the entry the entry is removed.
def __remove_URL_from_10320LOC(self, url, list_of_entries, handle): ''' Remove an URL from the handle record's "10320/LOC" entry. If it exists several times in the entry, all occurences are removed. If the URL is not present, nothing happens. If after removing, there is no more U...
Add a url to the handle record s 10320/ LOC entry. If no 10320/ LOC entry exists a new one is created ( using the default chooseby attribute if configured ). If the URL is already present it is not added again but the attributes ( e. g. weight ) are updated/ added. If the existing 10320/ LOC entry is mal - formed an ex...
def __add_URL_to_10320LOC(self, url, list_of_entries, handle=None, weight=None, http_role=None, **kvpairs): ''' Add a url to the handle record's "10320/LOC" entry. If no 10320/LOC entry exists, a new one is created (using the default "chooseby" attribute, if configured). ...
Adds or updates attributes of a <location > element. Existing attributes are not removed!
def __set_or_adapt_10320LOC_attributes(self, locelement, weight=None, http_role=None, **kvpairs): ''' Adds or updates attributes of a <location> element. Existing attributes are not removed! :param locelement: A location element as xml snippet (xml.etree.ElementTree.Elem...
authorization url request weibo authorization url: return: code string 用于第二步调用oauth2/ access_token接口,获取授权后的access token。 state string 如果传递参数,会回传该参数
def authorize_url(self): """ authorization url request weibo authorization url :return: code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。 state string 如果传递参数,会回传该参数 """ if self.oauth2_params and self.oauth2_params.get("display") == ...
: param method: str http method [ GET POST PUT ]: param suffix: the url suffix: param data:: return:
def request(self, method, suffix, data): """ :param method: str, http method ["GET","POST","PUT"] :param suffix: the url suffix :param data: :return: """ url = self.site_url + suffix response = self.session.request(method, url, data=data) if respo...
verify the fist authorization response url code
def auth_access(self, auth_code): """ verify the fist authorization response url code response data 返回值字段 字段类型 字段说明 access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据, 第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值...
授权回收接口,帮助开发者主动取消用户的授权。
def revoke_auth_access(self, access_token): """ 授权回收接口,帮助开发者主动取消用户的授权。 应用下线时,清空所有用户的授权 应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权 开发者调试应用,需要反复调试授权功能 应用内实现类似登出微博帐号的功能 并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间 :param access_token: :return...
Creates and sets the authentication string for ( write - ) accessing the Handle Server. No return the string is set as an attribute to the client instance.
def __set_basic_auth_string(self, username, password): ''' Creates and sets the authentication string for (write-)accessing the Handle Server. No return, the string is set as an attribute to the client instance. :param username: Username handle with index: index:prefix/s...
Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record using the requests module.
def send_handle_get_request(self, handle, indices=None): ''' Send a HTTP GET request to the handle server to read either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optio...
Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record using the requests module.
def send_handle_put_request(self, **args): ''' Send a HTTP PUT request to the handle server to write either an entire handle or to some specified values to an handle record, using the requests module. :param handle: The handle. :param list_of_entries: A list of h...
Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record using the requests module.
def send_handle_delete_request(self, **args): ''' Send a HTTP DELETE request to the handle server to delete either an entire handle or to some specified values from a handle record, using the requests module. :param handle: The handle. :param indices: Optional. A...
Check if the username handles exists.
def check_if_username_exists(self, username): ''' Check if the username handles exists. :param username: The username, in the form index:prefix/suffix :raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException` :raises: :exc:`~b2handle.handleexceptions.GenericHandleError`...
Create HTTP headers for different HTTP requests. Content - type and Accept are application/ json as the library is interacting with a REST API.
def __get_headers(self, action): ''' Create HTTP headers for different HTTP requests. Content-type and Accept are 'application/json', as the library is interacting with a REST API. :param action: Action for which to create the header ('GET', 'PUT', 'DELETE', ...
Create the URL for a HTTP request ( URL + query string ) to request a specific handle from the Handle Server.
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None): ''' Create the URL for a HTTP request (URL + query string) to request a specific handle from the Handle Server. :param handle: The handle to access. :param indices: Optional. A list of integers or s...
Record a single hit on a given metric.
def publish_metric(self, metric_name, metric_value, epoch_seconds=None): '''Record a single hit on a given metric. Args: metric_name: The name of the metric to record with Carbon. metric_value: The value to record with Carbon. epoch_seconds: Optionally specify the ti...
Record hits to a metric at a specified interval.
def register_repeating_metric(self, metric_name, frequency, getter): '''Record hits to a metric at a specified interval. Args: metric_name: The name of the metric to record with Carbon. frequency: The frequency with which to poll the getter and record the value with Carbon. ...
Setup integration
def setup(console=False, port=None, menu=True): """Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Arguments: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to conn...
Try showing the most desirable GUI
def show(): """Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the user. """ parent = None current = QtWidgets.QApplication.activeWindow() while current: parent = current cur...
Remove Nuke margins when docked UI.. _More info: https:// gist. github. com/ maty974/ 4739917
def _nuke_set_zero_margins(widget_object): """Remove Nuke margins when docked UI .. _More info: https://gist.github.com/maty974/4739917 """ parentApp = QtWidgets.QApplication.allWidgets() parentWidgetList = [] for parent in parentApp: for child in parent.children(): i...
Expecting a window to parent into a Nuke panel that is dockable.
def dock(window): """ Expecting a window to parent into a Nuke panel, that is dockable. """ # Deleting existing dock # There is a bug where existing docks are kept in-memory when closed via UI if self._dock: print("Deleting existing dock...") parent = self._dock dialog = None ...
Returns index and handle separately in a tuple.
def remove_index_from_handle(handle_with_index): ''' Returns index and handle separately, in a tuple. :handle_with_index: The handle string with an index (e.g. 500:prefix/suffix) :return: index and handle as a tuple. ''' split = handle_with_index.split(':') if len(split) == 2: ...
Checks the syntax of a handle without an index ( are prefix and suffix there are there too many slashes? ).
def check_handle_syntax(string): ''' Checks the syntax of a handle without an index (are prefix and suffix there, are there too many slashes?). :string: The handle without index, as string prefix/suffix. :raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError` :return: True....
Creates an authentication string from the username and password.
def create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') user...
Creates a string containing all relevant information about a request made to the Handle System for logging purposes.
def make_request_log_message(**args): ''' Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the requ...
Returns an etree. XMLRoot object loaded from the url: param str url: URL for the resource to load as an XML
def request_xml(url, auth=None): ''' Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML ''' try: r = requests.get(url, auth=auth, verify=False) return r.text.encode('utf-8') except BaseException: logger.error("Skippi...
Returns the appropriate catalog URL by replacing html with xml in some cases: param str url: URL to the catalog
def _get_catalog_url(self, url): ''' Returns the appropriate catalog URL by replacing html with xml in some cases :param str url: URL to the catalog ''' u = urlparse.urlsplit(url) name, ext = os.path.splitext(u.path) if ext == ".html": u = urlp...
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog: param str url: URL for the current catalog: param lxml. etree. Eleemnt tree: Current XML Tree
def _yield_leaves(self, url, tree): ''' Yields a URL corresponding to a leaf dataset for each dataset described by the catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' for leaf in tree.findall('.//{%s}dataset[@urlPat...
Returns a list of catalog reference URLs for the current catalog: param str url: URL for the current catalog: param lxml. etree. Eleemnt tree: Current XML Tree
def _compile_references(self, url, tree): ''' Returns a list of catalog reference URLs for the current catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' references = [] for ref in tree.findall('.//{%s}catalogR...
Performs a multiprocess depth - first - search of the catalog references and yields a URL for each leaf dataset found: param str url: URL for the current catalog: param requests. auth. AuthBase auth: requets auth object to use
def _run(self, url, auth): ''' Performs a multiprocess depth-first-search of the catalog references and yields a URL for each leaf dataset found :param str url: URL for the current catalog :param requests.auth.AuthBase auth: requets auth object to use ''' if url i...
Recursive function to perform the DFS and yield the leaf datasets: param str url: URL for the current catalog: param str xml_content: XML Body returned from HTTP Request
def _build_catalog(self, url, xml_content): ''' Recursive function to perform the DFS and yield the leaf datasets :param str url: URL for the current catalog :param str xml_content: XML Body returned from HTTP Request ''' try: tree = etree.XML(xml_content) ...
Find a loader for module or package fqname.
def find_module(fdr, fqname, path = None): '''Find a loader for module or package `fqname`. This method will be called with the fully qualified name of the module. If the finder is installed on `sys.meta_path`, it will receive a second argument, which is `None` for a top-level module, ...
Load fqname from under ldr. fspath.
def load_module(ldr, fqname): '''Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added t...
Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe and exit if the pipe becomes unreadable. Returns pipe or NULL if there was an error.
def zthread_fork(ctx, func, *args, **kwargs): """ Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe, and exit if the pipe becomes unreadable. Returns pipe, or NULL if there was an error. """ a = ctx.socket(zmq.PAIR) a.setsoc...
Prevent accidental assignment of existing members
def _remap(object, name, value, safe=True): """Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that ...
Try loading each binding in turn
def init(): """Try loading each binding in turn Please note: the entire Qt module is replaced with this code: sys.modules["Qt"] = binding() This means no functions or variables can be called after this has executed. For debugging and testing, this module may be accessed through `Qt.__...
Log the instantiation of an object to the given logger.
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False): ''' Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments pa...
convert dict value if value is bool type False - > false True - > true
def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.it...
error code response: { request:/ statuses/ home_timeline. json error_code: 20502 error: Need you follow uid. }: param response:: return:
def _handler_response(self, response, data=None): """ error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: """ if response.s...
request weibo api: param suffix: str: param params: dict url query parameters: return:
def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base + suffix params = filter_params(params) response = self.session.get(url=url, params=params) ...
: return:
def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, data=data)
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as - is. The servlet is supposed to be case - insensitive but if it isn t the wrong case will cause a: exc: ~b2handle. handleexceptions. ReverseLookupException.
def search_handle(self, **args): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b...
Create the part of the solr request that comes after the question mark e. g. ?URL = * dkrz * &CHECKSUM = * abc *. If allowed search keys are configured only these are used. If no allowed search keys are specified all key - value pairs are passed on to the reverse lookup servlet.
def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are ...
Creates and sets the authentication string for accessing the reverse lookup servlet. No return the string is set as an attribute to the client instance.
def __set_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Pa...
Create a new instance of a PIDClientCredentials with information read from a local JSON file.
def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json ...
Load fixtures using a data migration.
def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=F...
Get all non - zero bits
def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
Returns a hexadecimal string
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
Construct BitMap from hex string
def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
Construct BitMap from string
def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("I...
Get version information or return default if unable to do so.
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case It returns a string.
def get_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE cert...
Setup filter ( only called when filter is actually used ).
def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bund...
Initialize filter just before it will be used.
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
Determine which option name to use.
def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.ind...
Input filtering.
def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
Wrap translation in Angular module.
def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) ...
Process individual translation file.
def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gett...
Check the combination username/ password that is valid on the database.
def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, models.USERS.c.email == username ) user = self.identity_fro...
Query the Github API to retrieve the needed infos.
def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sani...
Cache the return value in the correct cache directory. Set method to false for static methods.
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): ...