Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
900
def set_attrs(obj, attrs): o = setattr if hasattr(obj, ): o = type(obj).__setitem__ [o(obj, k, v) for k, v in attrs.iteritems()]
Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict
901
def complete(self, match, subject_graph): size = len(match) if match.forward[size-1] in subject_graph.neighbors[match.forward[size-2]]: order = list(range(0, size, 2)) + list(range(1, size-1, 2))[::-1] ok = True for i in range(len(order)...
Check the completeness of a ring match
902
async def eap_options(request: web.Request) -> web.Response: return web.json_response(EAP_CONFIG_SHAPE, status=200)
Get request returns the available configuration options for WPA-EAP. Because the options for connecting to WPA-EAP secured networks are quite complex, to avoid duplicating logic this endpoint returns a json object describing the structure of arguments and options for the eap_config arg to /wifi/configu...
903
def description(pokemon): r = requests.get( + (pokemon.descriptions.values()[0])) desc = eval(r.text)[].replace(, ) return desc
Return a description of the given Pokemon.
904
def versionok_for_gui(): if sys.hexversion < 0x02060000: return False if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000: return False if sys.platform.startswith("java") or sys.platform.startswith(): return False return True
Return True if running Python is suitable for GUI Event Integration and deeper IPython integration
905
def transform(self, X, y=None): check_is_fitted(self, "categories_") X = self._check_array(X).copy() categories = self.categories_ for k, dtype in categories.items(): if _HAS_CTD: if not isinstance(dtype, pd.api.types.CategoricalDtype): ...
Transform the columns in ``X`` according to ``self.categories_``. Parameters ---------- X : pandas.DataFrame or dask.DataFrame y : ignored Returns ------- X_trn : pandas.DataFrame or dask.DataFrame Same type as the input. The columns in ``self.catego...
906
def subtract_months(self, months: int) -> datetime: self.value = self.value - relativedelta(months=months) return self.value
Subtracts a number of months from the current value
907
def take_at_least_n_seconds(time_s): timeout = PolledTimeout(time_s) yield while not timeout.has_expired(): time.sleep(timeout.remaining)
A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting. Args: time_s: The number of seconds...
908
def encrypt(self, s, mac_bytes=10): if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: ...
Encrypt `s' for this pubkey.
909
def enable(self, cmd="enable", pattern=r" output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) output += self.read_until_prompt_or_pattern( pattern=pattern, re_flags=re_flags ) if not self.check_...
Enable mode on MRV uses no password.
910
def update_repodata(self, channels=None): norm_channels = self.conda_get_condarc_channels(channels=channels, normalize=True) repodata_urls = self._set_repo_urls_from_channels(norm_channels) self._check_repos(repodata_urls)
Update repodata from channels or use condarc channels if None.
911
def gifs_trending_get(self, api_key, **kwargs): kwargs[] = True if kwargs.get(): return self.gifs_trending_get_with_http_info(api_key, **kwargs) else: (data) = self.gifs_trending_get_with_http_info(api_key, **kwargs) return data
Trending GIFs Endpoint Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team. The data returned mirrors the GIFs showcased on the <a href = \"http://www.giphy.com\">GIPHY homepage</a>. Returns 25 results by default. This method makes a synchronous HTTP request by default. To mak...
912
def get_package_info(self, name): if self._disable_cache: return self._get_package_info(name) return self._cache.store("packages").remember_forever( name, lambda: self._get_package_info(name) )
Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server.
913
def t_offset(self, s): r pos = self.pos self.add_token(, s) self.pos = pos + len(s)
r'[+]\d+
914
def move(self, auth, resource, destinationresource, options={"aliases": True}, defer=False): return self._call(, auth, [resource, destinationresource, options], defer)
Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being moved to.
915
def in_nested_list(nested_list, obj): for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: return True return False
return true if the object is an element of <nested_list> or of a nested list
916
def dump(self, validate=True): if validate: self.validate() return bencode(self.convert())
Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes`
917
def parse(response): if response.status_code == 400: try: msg = json.loads(response.content)[] except (KeyError, ValueError): msg = raise ApiError(msg) return response
check for errors
918
def stop_request(self, stop_now=False): logger.debug("Sending stop request to %s, stop now: %s", self.name, stop_now) res = self.con.get(, {: if stop_now else }) return res
Send a stop request to the daemon :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: the daemon response (True)
919
def install_var(instance, clear_target, clear_all): _check_root() log("Checking frontend library and cache directories", emitter=) uid = pwd.getpwnam("hfos").pw_uid gid = grp.getgrnam("hfos").gr_gid join = os.path.join log("Cleaning up: " + item, lvl=warn) ...
Install required folders in /var
920
def train(self, s, path="spelling.txt"): model = {} for w in re.findall("[a-z]+", s.lower()): model[w] = w in model and model[w] + 1 or 1 model = ("%s %s" % (k, v) for k, v in sorted(model.items())) model = "\n".join(model) f = open(path, "w") f.write...
Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor.
921
def unique_append(self, value): if value not in self: try: super(self.__class__, self).append(Uri(value)) except AttributeError as err: if isinstance(value, MODULE.rdfclass.RdfClassBase): super(self.__class__, self).append(value) else: ...
function for only appending unique items to a list. #! consider the possibility of item using this to a set
922
def _command(self, sock_info, command, slave_ok=False, read_preference=None, codec_options=None, check=True, allowable_errors=None, read_concern=None, write_concern=None, collation=None, session=None, ...
Internal command helper. :Parameters: - `sock_info` - A SocketInfo instance. - `command` - The command itself, as a SON instance. - `slave_ok`: whether to set the SlaveOkay wire protocol bit. - `codec_options` (optional) - An instance of :class:`~bson.codec_o...
923
def usePointsForInterpolation(self,cNrm,mNrm,interpolator): s consumption-saving problem, with a consumption function, marginal value function, and minimum m. ' cFuncNowUnc = interpolator(mNrm,cNrm) cFuncNow = LowerEnvelope(cFuncNowUnc,self.cFuncNowCnst) ...
Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- cNrm : np.array (Normalized) consumption points for interpolation. mNrm : np.array (Normalized) corresponding market resourc...
924
def _validate_authority_uri_abs_path(host, path): if len(host) > 0 and len(path) > 0 and not path.startswith("/"): raise ValueError( "Path in a URL with authority " "should start with a slash () if set" )
Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not.
925
def _run_command(argv): command_name, argv = _get_command_and_argv(argv) _LOGGER.info(, settings.command, command_name, argv) subcommand = _get_subcommand(command_name) func = call.get_callable(subcommand) doc = usage.format_usage(subcommand.__doc__) args = _get_parsed...
Run the command with the given CLI options and exit. Command functions are expected to have a __doc__ string that is parseable by docopt. Args: argv: The list of command line arguments supplied for a command. The first argument is expected to be the name of the command to be run. ...
926
def post(self, text=None, attachments=None, source_guid=None): return self.messages.create(text=text, attachments=attachments, source_guid=source_guid)
Post a direct message to the user. :param str text: the message content :param attachments: message attachments :param str source_guid: a client-side unique ID for the message :return: the message sent :rtype: :class:`~groupy.api.messages.DirectMessage`
927
def _mmComputeSequenceRepresentationData(self): if not self._sequenceRepresentationDataStale: return unionSDRTrace = self.mmGetTraceUnionSDR() sequenceLabelsTrace = self.mmGetTraceSequenceLabels() resetsTrace = self.mmGetTraceResets() n = len(unionSDRTrace.data) overlapMatrix = nump...
Calculates values for the overlap distance matrix, stability within a sequence, and distinctness between sequences. These values are cached so that they do need to be recomputed for calls to each of several accessor methods that use these values.
928
def predefinedEntity(name): ret = libxml2mod.xmlGetPredefinedEntity(name) if ret is None:raise treeError() return xmlEntity(_obj=ret)
Check whether this name is an predefined entity.
929
def get_work_items_batch(self, work_item_get_request, project=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) content = self._serialize.body(work_item_get_request, ) response = self._send(http_method=, ...
GetWorkItemsBatch. Gets work items for a list of work item ids (Maximum 200) :param :class:`<WorkItemBatchGetRequest> <azure.devops.v5_0.work_item_tracking.models.WorkItemBatchGetRequest>` work_item_get_request: :param str project: Project ID or project name :rtype: [WorkItem]
930
def _finish(self, update_ops, name_scope): iter_ = self._get_iter_variable() beta1_power, beta2_power = self._get_beta_accumulators() with tf.control_dependencies(update_ops): with tf.colocate_with(iter_): def update_beta_op(): update_beta1 = beta1_power.assign( b...
Updates beta_power variables every n batches and incrs counter.
931
def grant_client(self, client_id, read=True, write=True): scopes = [] authorities = [] if write: for zone in self.service.settings.data[][]: scopes.append(zone) authorities.append(zone) if read: for zone in self.service.s...
Grant the given client id all the scopes and authorities needed to work with the timeseries service.
932
def get_data_excel_xml(file_name, file_contents=None, on_demand=False): if file_contents: xml_file = BytesIO(file_contents) else: xml_file = file_name book = xmlparse.ParseExcelXMLFile(xml_file) row_builder = lambda s, r: list(s.row_values(r)) return [XMLSheetYielder(book, ...
Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. If left as None, then file_name is directly loaded. ...
933
def event_notify(self, event): if event.name not in self.available_events: return message = json.dumps({ : , : event.as_event_description(), }) for subscriber in self.available_events[event.name][]: try: subscribe...
Notify all subscribers of an event. event -- the event that occurred
934
def has_event(self, event, cameo_code): if self.has_cameo_code(cameo_code): entry = self.mapping.get(cameo_code) if entry: return entry[self.event_name[event]] return False
Test whether there is an "event2" or "event3" entry for the given cameo code Args: event: cameo_code: Returns:
935
def add_call(self, func): self.trace.append("{} ({}:{})".format( object_name(func), inspect.getsourcefile(func), inspect.getsourcelines(func)[1])) return self
Add a call to the trace.
936
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
Return the total apparent size, including children.
937
def to_dict(self): obj = { : self.identifier, : self.name, : self.description, : self.data_type.to_dict() } if not self.default is None: obj[] = self.default return obj
Convert attribute definition into a dictionary. Returns ------- dict Json-like dictionary representation of the attribute definition
938
async def _buffer_body(self, reader): remaining = int(self.headers.get(, 0)) if remaining > 0: try: self.data = await reader.readexactly(remaining) except asyncio.IncompleteReadError: raise EOFError()
Buffers the body of the request
939
def _get_default_arg(args, defaults, arg_index): if not defaults: return DefaultArgSpec(False, None) args_with_no_defaults = len(args) - len(defaults) if arg_index < args_with_no_defaults: return DefaultArgSpec(False, None) else: value = defaults[arg_index - args_with_no_d...
Method that determines if an argument has default value or not, and if yes what is the default value for the argument :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg'] :param defaults: array of default values, eg: (42, 'something') :param arg_index: index of the argument in ...
940
def draw_simple_elevation(world, sea_level, target): e = world.layers[].data c = numpy.empty(e.shape, dtype=numpy.float) has_ocean = not (sea_level is None or world.layers[].data is None or not world.layers[].data.any()) mask_land = numpy.ma.array(e, mask=world.layers[].data if has_ocean else Fa...
This function can be used on a generic canvas (either an image to save on disk or a canvas part of a GUI)
941
def _index_param_value(num_samples, v, indices): if not _is_arraylike(v) or _num_samples(v) != num_samples: return v if sp.issparse(v): v = v.tocsr() return safe_indexing(v, indices)
Private helper function for parameter value indexing. This determines whether a fit parameter `v` to a SearchCV.fit should be indexed along with `X` and `y`. Note that this differs from the scikit-learn version. They pass `X` and compute num_samples. We pass `num_samples` instead.
942
async def request(self, command, payload, retry=3): if self._token is None: _LOGGER.error("No token") return None _LOGGER.debug(command, payload) nonce = .join(random.choice(string.ascii_uppercase + string.digits) for _ in range(16)) url = API...
Request data.
943
def update_firmware(filename, host=None, admin_username=None, admin_password=None): if os.path.exists(filename): return _update_firmware(.format(filename), host=None, admin_userna...
Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command on your FX2 (using username and password stored in the pillar data) .. code-block:: bash racadm update –f firmware.exe -u user –p pass
944
def format(sql, args=None): resolved_vars = {} code = [] SqlStatement._find_recursive_dependencies(sql, args, code=code, resolved_vars=resolved_vars) parts = [] for (escape, placeholder, _, literal) in SqlStatement._get_tokens(sql): ...
Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictionary of values to use in variable ex...
945
def _by_columns(self, columns): return columns if self.isstr(columns) else self._backtick_columns(columns)
Allow select.group and select.order accepting string and list
946
def read_pipe(pipe_out): out = b while more_data(pipe_out): out += os.read(pipe_out, 1024) return out.decode()
Read data on a pipe Used to capture stdout data produced by libiperf :param pipe_out: The os pipe_out :rtype: unicode string
947
def _bounds_dist(self, p): prob = self.problem lb_dist = (p - prob.variable_bounds[0, ]).min() ub_dist = (prob.variable_bounds[1, ] - p).min() if prob.bounds.shape[0] > 0: const = prob.inequalities.dot(p) const_lb_dist = (const - prob.bounds[0, ]).min()...
Get the lower and upper bound distances. Negative is bad.
948
def update_received_packet(self, received_pkt_size_bytes): self.update_count(self.RECEIVED_PKT_COUNT) self.update_count(self.RECEIVED_PKT_SIZE, incr_by=received_pkt_size_bytes)
Update received packet metrics
949
def get(self, id, **options): if not self._item_path: raise AttributeError( % self._item_name) target = self._item_path % id json_data = self._redmine.get(target, **options) data = self._redmine.unwrap_json(self._item_type, json_data) data[] = target ...
Get a single item with the given ID
950
def _dy_shapelets(self, shapelets, beta): num_n = len(shapelets) dy = np.zeros((num_n+1, num_n+1)) for n1 in range(num_n): for n2 in range(num_n): amp = shapelets[n1][n2] dy[n1][n2+1] -= np.sqrt((n2+1)/2.) * amp if n2 > 0: ...
computes the derivative d/dx of the shapelet coeffs :param shapelets: :param beta: :return:
951
def disable_share(cookie, tokens, shareid_list): url = .join([ const.PAN_URL, , , tokens[], ]) data = + encoder.encode_uri(json.dumps(shareid_list)) req = net.urlopen(url, headers={ : cookie.header_output(), : const.CONTENT_FORM_UTF8, }, data=data.en...
取消分享. shareid_list 是一个list, 每一项都是一个shareid
952
def getAceTypeBit(self, t): try: return self.validAceTypes[t][] except KeyError: raise CommandExecutionError(( ).format(t, .join(self.validAceTypes)))
returns the acetype bit of a text value
953
def logs(self, pod=None): if pod is None: return {pod.status.pod_ip: self.logs(pod) for pod in self.pods()} return self.core_api.read_namespaced_pod_log(pod.metadata.name, pod.metadata.namespace)
Logs from a worker pod You can get this pod object from the ``pods`` method. If no pod is specified all pod logs will be returned. On large clusters this could end up being rather large. Parameters ---------- pod: kubernetes.client.V1Pod The pod from which ...
954
def latitude(self): sd = dm_to_sd(self.lat) if self.lat_dir == : return +sd elif self.lat_dir == : return -sd else: return 0.
Latitude in signed degrees (python float)
955
def __calculate_bu_dfs_recursively(u, b, dfs_data): first_time = True for v in dfs_data[][u]: if a(v, dfs_data) == u: if first_time: b[v] = b[u] else: b[v] = D(u, dfs_data) __calculate_bu_dfs_recursively(v, b, dfs_data) fir...
Calculates the b(u) lookup table with a recursive DFS.
956
def _get_unitary(self): unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits]) unitary = np.stack((unitary.real, unitary.imag), axis=-1) unitary[abs(unitary) < self._chop_threshold] = 0.0 return unitary
Return the current unitary in JSON Result spec format
957
def estimate_K_knee(self, th=.015, maxK=12): if self.X.shape[0] < maxK: maxK = self.X.shape[0] if maxK < 2: maxK = 2 K = np.arange(1, maxK) bics = [] for k in K: means, labels = self.run_kmeans(self.X, k) bic = sel...
Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.
958
def validate_query(self, using=None, **kwargs): return self._get_connection(using).indices.validate_query(index=self._name, **kwargs)
Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged.
959
def jprecess(ra, dec, mu_radec=None, parallax=None, rad_vel=None, epoch=None): if isinstance(ra, ndarray): ra = array(ra) dec = array(dec) else: ra = array([ra0]) dec = array([dec0]) n = ra.size if rad_vel is None: rad_vel = zeros(n,dtype=float) else: if no...
NAME: JPRECESS PURPOSE: Precess astronomical coordinates from B1950 to J2000 EXPLANATION: Calculate the mean place of a star at J2000.0 on the FK5 system from the mean place at B1950.0 on the FK4 system. Use BPRECESS for the reverse direction J2000 ==> B1950 ...
960
def equals(val1, val2): if len(val1) != len(val2): return False result = 0 for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0
Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths.
961
def _remove_code(site): def handle_error(function, path, excinfo): click.secho(.format(em=excinfo.message, p=path), err=True, fg=) if os.path.exists(site.root): shutil.rmtree(site.root, onerror=handle_error)
Delete project files @type site: Site
962
def _create_ucsm_host_to_service_profile_mapping(self): ucsm_ips = [ip for ip, ucsm in CONF.ml2_cisco_ucsm.ucsms.items() if not ucsm.ucsm_host_list] for ucsm_ip in ucsm_ips: with self.ucsm_connect_disconnect(ucsm_ip) as handle: try: ...
Reads list of Service profiles and finds associated Server.
963
def calculate_lvgd_stats(nw): proj = partial( pyproj.transform, pyproj.Proj(init=), pyproj.Proj(init=)) nw.control_circuit_breakers(mode=) lv_dist_idx = 0 lv_dist_dict = {} lv_gen_idx = 0 lv_gen_dict = {} lv_load_idx...
LV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- lvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the LVGD
964
def update(self, name, **kwargs): self.allowed(, kwargs, [, , , , , ]) kwargs = self.unused(kwargs) return self.http_post( % name, params=kwargs)
Create a new node
965
def refetch_for_update(obj): return obj.__class__.objects.select_for_update().get(id=obj.id)
Queries the database for the same object that is passed in, refetching its contents and runs ``select_for_update()`` to lock the corresponding row until the next commit. :param obj: Object to refetch :returns: Refreshed version of the object
966
def sendToTradepile(self, item_id, safe=True): if safe and len( self.tradepile()) >= self.tradepile_size:
Send to tradepile (alias for __sendToPile__). :params item_id: Item id. :params safe: (optional) False to disable tradepile free space check.
967
def _convert_value(self, item): if item.ctype == 3: try: return datetime.datetime(*xlrd.xldate_as_tuple(item.value, self._book.datemode)) except ValueError: ...
Handle different value types for XLS. Item is a cell object.
968
def command_max_run_time(self, event=None): try: max_run_time = self.max_run_time_var.get() except ValueError: max_run_time = self.runtime_cfg.max_run_time self.runtime_cfg.max_run_time = max_run_time self.max_run_time_var.set(self.runtime_cfg.max_run_ti...
CPU burst max running time - self.runtime_cfg.max_run_time
969
def add_require(self, require): for p in self.requires: if p.value == require.value: return self.requires.append(require)
Add a require object if it does not already exist
970
def stop(self): super(AggregateDependency, self).stop() if self.services: return [ (service, reference) for reference, service in self.services.items() ] return None
Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None
971
def _build_pools(self): if self.level >= Topic: self.topics_pool = set(self.topic() for i in range(self.pool_size)) if self.level >= Fact: self.facts_pool = set(self.fact() for i in range(self.pool_size)) if self.level >= Theory: ...
Slow method, retrieve all the terms from the database. :return:
972
def notify(self, correlation_id, args): for listener in self._listeners: try: listener.on_event(correlation_id, self, args) except Exception as ex: raise InvocationException( correlation_id, "EXEC_FAILED", ...
Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with.
973
def get_pk(obj): if inspect.isclass(obj): pk_list = sqlalchemy.inspect(obj).primary_key else: pk_list = obj.__mapper__.primary_key return pk_list
Return primary key name by model class or instance. :Parameters: - `obj`: SQLAlchemy model instance or class. :Examples: >>> from sqlalchemy import Column, Integer >>> from sqlalchemy.ext.declarative import declarative_base >>> Base = declarative_base() >>> class User(Base): ... ...
974
def copy(self, cursor, f): logger.info("Inserting file: %s", f) cursor.execute( % (self.table, f, self._credentials(), self.jsonpath, self.copy_json_options, self.copy_options))
Defines copying JSON from s3 into redshift.
975
def getVerifiers(self): contacts = list() for verifier in self.getVerifiersIDs(): user = api.get_user(verifier) contact = api.get_user_contact(user, ["LabContact"]) if contact: contacts.append(contact) return contacts
Returns the list of lab contacts that have verified at least one analysis from this Analysis Request
976
def from_json(data): memfiles = InMemoryFiles() memfiles.files = json.loads(data) return memfiles
Convert JSON into a in memory file storage. Args: data (str): valid JSON with path and filenames and the base64 encoding of the file content. Returns: InMemoryFiles: in memory file storage
977
def create_file_service(self): try: from azure.storage.file.fileservice import FileService return FileService(self.account_name, self.account_key, sas_token=self.sas_token, endpoint_suffix=self.endpoint_suffix) ...
Creates a FileService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.file.fileservice.FileService`
978
def add(self, elem): if isinstance(elem, self._allowedTypes): self._collection.add(elem) self._collectedTypes.add(type(elem).__name__) else: raise CollectionTypeError("{} can only contain , is not allowed.".format(type(self).__name__, self._allowedTypes, ele...
Adds _elem_ to the collection. # Parameters _elem_ : `object` > The object to be added
979
def _symbols(): global _SYMBOLS if _SYMBOLS is None: tmp = [(s, ) for s in _data()[].keys()] tmp += [(s, ) for s in _data()[].keys()] tmp += [(s.name, ) for s in _data()[].values()] _SYMBOLS = sorted( tmp, key=lambda s: (len(s[0]), ord(s[0][0])), ...
(Lazy)load list of all supported symbols (sorted) Look into `_data()` for all currency symbols, then sort by length and unicode-ord (A-Z is not as relevant as ֏). Returns: List[unicode]: Sorted list of possible currency symbols.
980
def joint_img(self, num_iid, pic_path, session, id=None, position=None, is_major=None): request = TOPRequest() request[] = num_iid request[] = pic_path if id!=None: request[] = id if position!=None: request[] = position if is_major!=None: ...
taobao.item.joint.img 商品关联子图 - 关联一张商品图片到num_iid指定的商品中 - 传入的num_iid所对应的商品必须属于当前会话的用户 - 商品图片关联在卖家身份和图片来源上的限制,卖家要是B卖家或订购了多图服务才能关联图片,并且图片要来自于卖家自己的图片空间才行 - 商品图片数量有限制。不管是上传的图片还是关联的图片,他们的总数不能超过一定限额
981
def create_notes_folder(self, title, parentid=""): if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req(, post_data={ ...
Create new folder :param title: The title of the folder to create :param parentid: The UUID of the parent folder
982
def required(wrapping_functions, patterns_rslt): ^staff/staff^mypage/mypage if not hasattr(wrapping_functions, ): wrapping_functions = (wrapping_functions,) return [ _wrap_instance__resolve(wrapping_functions, instance) for instance in patterns_rslt ]
USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ) staff_patterns = required( staff_member_requi...
983
def _exec_request(self, service, method=None, path_args=None, data=None, params=None): if path_args is None: path_args = [] req = { : method or , : .join(str(a).strip() for a in [ cfg.CONF.tvdb.service_url, service] + pa...
Execute request.
984
def put(self, deviceId): device = request.get_json() logger.debug("Received /devices/" + deviceId + " - " + str(device)) self._deviceController.accept(deviceId, device) return None, 200
Puts a new device into the device store :param deviceId: :return:
985
def predict(self, log2_bayes_factors, reset_index=False): if reset_index: x = log2_bayes_factors.reset_index(level=0, drop=True) else: x = log2_bayes_factors if isinstance(x, pd.DataFrame): not_na = (x.notnull() > 0).any() not_na_columns =...
Guess the most likely modality for each event For each event that has at least one non-NA value, if no modalilites have logsumexp'd logliks greater than the log Bayes factor threshold, then they are assigned the 'multimodal' modality, because we cannot reject the null hypothesis that th...
986
def _wrap_tracebackexception_format(redact: Callable[[str], str]): original_format = getattr(TracebackException, , None) if original_format is None: original_format = TracebackException.format setattr(TracebackException, , original_format) @wraps(original_format) def tracebackexcep...
Monkey-patch TracebackException.format to redact printed lines. Only the last call will be effective. Consecutive calls will overwrite the previous monkey patches.
987
def _param_deprecation_warning(schema, deprecated, context): for i in deprecated: if i in schema: msg = msg = msg.format(ctx = context, word = i) warnings.warn(msg, Warning)
Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency
988
def xpath(request): ident_hash = request.params.get() xpath_string = request.params.get() if not ident_hash or not xpath_string: exc = httpexceptions.HTTPBadRequest exc.explanation = raise exc try: uuid, version = split_ident_hash(ident_hash) except IdentHashS...
View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.
989
def telnet_sa_telnet_server_shutdown(self, **kwargs): config = ET.Element("config") telnet_sa = ET.SubElement(config, "telnet-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") telnet = ET.SubElement(telnet_sa, "telnet") server = ET.SubElement(telnet, "server") shut...
Auto Generated Code
990
def _get_bases(cls, ab): start_bases, end_bases = [], [] for base in (, , ): if ab.find(, start=base): start_bases.append(base[0:1]) else: start_bases.append() if ab.find(, end=base): end_bases.append(base[0:1])...
Start Bases & End Bases :param ab: at bat object(type:Beautifulsoup) :param attribute_name: attribute name :return: start base, end base
991
def create_app(): app = App.create_app(__name__) app.configure() return app
Create the standard app for ``fleaker_config`` and register the two routes required.
992
def reply_sticker( self, sticker: str, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", "pyrogram.ReplyKeyboardMarkup", "pyrogram.ReplyKeyboard...
Bound method *reply_sticker* of :obj:`Message <pyrogram.Message>`. Use as a shortcut for: .. code-block:: python client.send_sticker( chat_id=message.chat.id, sticker=sticker ) Example: .. code-block:: python ...
993
def exists_or_mkdir(path, verbose=True): if not os.path.exists(path): if verbose: logging.info("[*] creates %s ..." % path) os.makedirs(path) return False else: if verbose: logging.info("[!] %s exists ..." % path) return True
Check a folder by given name, if not exist, create the folder and return False, if directory exists, return True. Parameters ---------- path : str A folder path. verbose : boolean If True (default), prints results. Returns -------- boolean True if folder already...
994
def trace_min_buffer_capacity(self): cmd = enums.JLinkTraceCommand.GET_MIN_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException() return data.value
Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer.
995
def can_import(self, file_uris, current_doc=None): if len(file_uris) <= 0: return False for file_uri in file_uris: file_uri = self.fs.safe(file_uri) if not self.check_file_type(file_uri): return False return True
Check that the specified file looks like an image supported by PIL
996
def add_note(note, **kwargs): note_i = Note() note_i.ref_key = note.ref_key note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value note_i.created_by = kwargs.get() db.DBSession.add(note_i) db.DBSession.flush() return note_i
Add a new note
997
def _wait(self, generator, method, timeout=None, *args, **kwargs): if self.debug: print("waiting for %s to pause" % generator) original_timeout = timeout while timeout is None or timeout > 0: last_time = time.time() if self._lock.acquire(False): ...
Wait until generator is paused before running 'method'.
998
def __run_git(cmd, path=None): exe = [__get_git_bin()] + cmd try: proc = subprocess.Popen(exe, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except subprocess.CalledProcessError: return None, None except ValueError: return None, None except OSError: r...
internal run git command :param cmd: git parameters as array :param path: path where command will be executed :return: tuple (<line>, <returncode>)
999
def bulk_modify(self, *filters_or_records, **kwargs): values = kwargs.pop(, None) if kwargs: raise ValueError(.format(kwargs)) if not values: raise ValueError() if not isinstance(values, dict): raise ValueError("values parameter must be dic...
Shortcut to bulk modify records .. versionadded:: 2.17.0 Args: *filters_or_records (tuple) or (Record): Either a list of Records, or a list of filters. Keyword Args: values (dict): Dictionary of one or more 'field_name': 'new_value' pairs to update ...