Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
386,200
def debug(self, message, *args, **kwargs): self._log(logging.DEBUG, message, *args, **kwargs)
Debug level to use and abuse when coding
386,201
def _set_fcoe_max_enode(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={: []}, int_size=32), restriction_dict={: [u]}), is_leaf=True, yang_name="fcoe-max-enode", rest_...
Setter method for fcoe_max_enode, mapped from YANG variable /rbridge_id/fcoe_config/fcoe_max_enode (fcoe-max-enodes-per-rbridge-type) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_max_enode is considered as a private method. Backends looking to populate this variable ...
386,202
def generate_html_documentation(self): methods = {} for method_name in self.system_listMethods(): if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: method_info = [None, None] ...
generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring...
386,203
def _parse_migrate_output(self, output): failed = None succeeded = [] for line in output.split(): line = _remove_escape_characters(line).strip() line_match = self.migration_regex.match(line) if line_match: m...
Args: output: str, output of "manage.py migrate" Returns (succeeded: list(tuple), failed: tuple or None) Both tuples are of the form (app, migration)
386,204
def get_directory(db, user_id, api_dirname, content): db_dirname = from_api_dirname(api_dirname) if not _dir_exists(db, user_id, db_dirname): raise NoSuchDirectory(api_dirname) if content: files = files_in_directory( db, user_id, db_dirname, )...
Return the names of all files/directories that are direct children of api_dirname. If content is False, return a bare model containing just a database-style name.
386,205
def _zforce(self,R,z,phi=0,t=0): r= numpy.sqrt(R**2.+z**2.) out= self._scf.zforce(R,z,phi=phi,use_physical=False) for a,s,ds,H,dH in zip(self._Sigma_amp,self._Sigma,self._dSigmadR, self._Hz,self._dHzdz): out-= 4.*numpy.pi*a*(ds(r)*H(z)*z/r+s(r)*d...
NAME: _zforce PURPOSE: evaluate the vertical force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: vertical force at (R,z, phi) HISTORY: 2...
386,206
def __filterItems(self, terms, autoExpand=True, caseSensitive=False, parent=None, level=0): if key in generic: generic_foun...
Filters the items in this tree based on the inputed keywords. :param terms | {<int> column: [<str> term, ..], ..} autoExpand | <bool> caseSensitive | <bool> parent | <QtGui.QTreeWidgetItem> || None ...
386,207
def organismsKEGG(): organisms=urlopen("http://rest.kegg.jp/list/organism").read() organisms=organisms.split("\n") organisms=[ s.split("\t") for s in organisms ] organisms=pd.DataFrame(organisms) return organisms
Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row.
386,208
def sequential_connect(self): try: mappings = sequential_bind(self.mapping_no + 1, self.interface) con = self.server_connect(mappings[0]["sock"]) except Exception as e: log.debug(e) log.debug("this err") return None ...
Sequential connect is designed to return a connection to the Rendezvous Server but it does so in a way that the local port ranges (both for the server and used for subsequent hole punching) are allocated sequentially and predictably. This is because Delta+1 type NATs only preserve th...
386,209
def request(self, url, *, method=, headers=None, data=None, result_callback=None): url = self._make_full_url(url) self._log.debug(, method, url) return self._request(url, method=method, headers=headers, data=data, result_callback=result_cal...
Perform request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: request data. :param object -> object result_callback: result callback. :rtype: dict :raise: APIError
386,210
def _list_itemstrs(list_, **kwargs): items = list(list_) kwargs[] = True _tups = [repr2(item, **kwargs) for item in items] itemstrs = [t[0] for t in _tups] max_height = max([t[1][] for t in _tups]) if _tups else 0 _leaf_info = { : max_height + 1, } sort = kwargs.get(, None)...
Create a string representation for each item in a list.
386,211
def design_expparams_field(self, guess, field, cost_scale_k=1.0, disp=False, maxiter=None, maxfun=None, store_guess=False, grad_h=None, cost_mult=False ): r up = self._updater m = up.model ...
r""" Designs a new experiment by varying a single field of a shape ``(1,)`` record array and minimizing the objective function .. math:: O(\vec{e}) = r(\vec{e}) + k \$(\vec{e}), where :math:`r` is the Bayes risk as calculated by the updater, and wher...
386,212
def remove(self, child): for i in range(len(self)): if self[i] == child: del self[i]
Remove a child element.
386,213
def netconf_state_schemas_schema_identifier(self, **kwargs): config = ET.Element("config") netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring") schemas = ET.SubElement(netconf_state, "schemas") schema = ET.SubElement...
Auto Generated Code
386,214
def get_interface_detail_output_interface_ip_mtu(self, **kwargs): config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") interface = ET.SubElement(output...
Auto Generated Code
386,215
def _layer_norm_new_params(input_shape, rng, epsilon=1e-6): del rng, epsilon features = input_shape[-1] scale = np.ones(features) bias = np.zeros(features) return (scale, bias)
Helper: create layer norm parameters.
386,216
def get_permissions(self): user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role return user_role.get_permissions()
Permissions of the user. Returns: List of Permission objects.
386,217
def feed_fetch_force(request, id, redirect_to): feed = Feed.objects.get(id=id) feed.fetch(force=True) msg = _("Fetched tweets for %s" % feed.name) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
Forcibly fetch tweets for the feed
386,218
def repeat_str(state): if state == const.REPEAT_STATE_OFF: return if state == const.REPEAT_STATE_TRACK: return if state == const.REPEAT_STATE_ALL: return return
Convert internal API repeat state to string.
386,219
def is_threat(self, result=None, harmless_age=None, threat_score=None, threat_type=None): harmless_age = harmless_age if harmless_age is not None else settings.CACHED_HTTPBL_HARMLESS_AGE threat_score = threat_score if threat_score is not None else settings.CACHED_HTTPBL_THREAT_SCORE th...
Check if IP is a threat :param result: httpBL results; if None, then results from last check_ip() used (optional) :param harmless_age: harmless age for check if httpBL age is older (optional) :param threat_score: threat score for check if httpBL threat is lower (optional) :param threat_...
386,220
def quit(self, message=None): if message is None: message = if self.connected: self.send(, params=[message])
Quit from the server.
386,221
def start_dashboard(self): stdout_file, stderr_file = self.new_log_files("dashboard", True) self._webui_url, process_info = ray.services.start_dashboard( self.redis_address, self._temp_dir, stdout_file=stdout_file, stderr_file=stderr_file, ...
Start the dashboard.
386,222
def extract(self, package_name): for cmd in [, ]: if not Cmd.which(cmd): message = .format(cmd) raise InstallError(message) pattern = .format(package_name, self.arch) rpm_files = Cmd.find(, pattern) if not rpm_files: raise...
Extract given package.
386,223
def audio_inputs(self): return self.client.get_ports(is_audio=True, is_physical=True, is_input=True)
:return: A list of audio input :class:`Ports`.
386,224
def _GenerateDescription(self): manifest = { "description": self.description, "processed_files": len(self.processed_files), "archived_files": len(self.archived_files), "ignored_files": len(self.ignored_files), "failed_files": len(self.failed_files) } if self.ign...
Generates description into a MANIFEST file in the archive.
386,225
def gen_xlsx_table_info(): XLSX_FILE = if os.path.exists(XLSX_FILE): pass else: return RAW_LIST = [, , , , , , , , , , , , , , , , , , , , , , , , , ] FILTER_COLUMNS = RAW_LIST + ["A" + x for x in RAW_LIST] + \ ["B" + x for x in RAW_LIST]...
向表中插入数据
386,226
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP...
Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param outstanding_certs: Certificates that belongs to me that the IdP may have used to encry...
386,227
def field_to_dict(fields): field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], deepcopy(EMPTY_DICT) ).u...
Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } ...
386,228
def ReadDataFile(self): if os.path.isfile(self.filename[0:-4] + ): filename = self.filename[0:-4] + elif os.path.isfile(self.filename[0:-4] + ): filename = self.filename[0:-4] + else: print "Data file File not found." retur...
Reads the contents of the Comtrade .dat file and store them in a private variable. For accessing a specific channel data, see methods getAnalogData and getDigitalData.
386,229
def AgregarFusion(self, nro_ing_brutos, nro_actividad, **kwargs): "Datos de comprador o vendedor según liquidación a ajustar (fusión.)" self.ajuste[][] = {: nro_ing_brutos, : nro_actividad, } return Tru...
Datos de comprador o vendedor según liquidación a ajustar (fusión.)
386,230
def rget(self, key, replica_index=None, quiet=None): if replica_index is not None: return _Base._rgetix(self, key, replica=replica_index, quiet=quiet) else: return _Base._rget(self, key, quiet=quiet)
Get an item from a replica node :param string key: The key to fetch :param int replica_index: The replica index to fetch. If this is ``None`` then this method will return once any replica responds. Use :attr:`configured_replica_count` to figure out the upper bound fo...
386,231
def plot_site(fignum, SiteRec, data, key): print() print() print(SiteRec[], SiteRec[], SiteRec[], SiteRec[], SiteRec[], SiteRec[], SiteRec[], SiteRec[], SiteRec[]) print() for i in range(len(data)): print( % (data[i][ + key + ], data[i][key + ], data[i] ...
deprecated (used in ipmag)
386,232
def _generate_struct_class(self, ns, data_type): self.emit(self._class_declaration_for_type(ns, data_type)) with self.indent(): if data_type.has_documented_type_or_fields(): self.emit() self.emit() self._generate_struct_class_slots(d...
Defines a Python class that represents a struct in Stone.
386,233
def to_datetime(dt, tzinfo=None, format=None): if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if isinstance(dt, (str, unicode)): if not format: formats = DEFAULT_DATETIME_INPUT_FORMATS else: formats = list(format) d = None...
Convert a date or time to datetime with tzinfo
386,234
def mutual_information( self, M_c, X_L_list, X_D_list, Q, seed, n_samples=1000): get_next_seed = make_get_next_seed(seed) return iu.mutual_information( M_c, X_L_list, X_D_list, Q, get_next_seed, n_samples)
Estimate mutual information for each pair of columns on Q given the set of samples. :param Q: List of tuples where each tuple contains the two column indexes to compare :type Q: list of two-tuples of ints :param n_samples: the number of simple predictive samples to use ...
386,235
def interrupt(self): if(self.device.read(9) & 0x01): self.handle_request() self.device.clear_IR()
Invoked on a write operation into the IR of the RendererDevice.
386,236
def pop(self, key, *args): try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError(.format(key))
Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].
386,237
def calculate_lyapunov(self): if self._calculate_megno==0: raise RuntimeError("Lyapunov Characteristic Number cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation.") clibrebound.reb_tools_calculate_lyapunov.restype = ...
Return the current Lyapunov Characteristic Number (LCN). Note that you need to call init_megno() before the start of the simulation. To get a timescale (the Lyapunov timescale), take the inverse of this quantity.
386,238
def _get_nsamps_samples_n(res): try: samples_n = res.samples_n nsamps = len(samples_n) except: niter = res.niter nlive = res.nlive nsamps = len(res.logvol) if nsamps == niter: samples_n = np.ones(niter, dtype=) * nlive el...
Helper function for calculating the number of samples Parameters ---------- res : :class:`~dynesty.results.Results` instance The :class:`~dynesty.results.Results` instance taken from a previous nested sampling run. Returns ------- nsamps: int The total number of samples...
386,239
def is_gene_list(bed_file): with utils.open_gzipsafe(bed_file) as in_handle: for line in in_handle: if not line.startswith(" if len(line.split()) == 1: return True else: return False
Check if the file is only a list of genes, not a BED
386,240
def is_decorated_with_property(node): if not node.decorators: return False for decorator in node.decorators.nodes: if not isinstance(decorator, astroid.Name): continue try: if _is_property_decorator(decorator): return True except ast...
Check if the function is decorated as a property. :param node: The node to check. :type node: astroid.nodes.FunctionDef :returns: True if the function is a property, False otherwise. :rtype: bool
386,241
def cpustats(): * def linux_cpustats(): ret = {} try: with salt.utils.files.fopen(, ) as fp_: stats = salt.utils.stringutils.to_unicode(fp_.read()) except IOError: pass else: for line in stats.splitlines(): ...
Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats
386,242
def zDDEInit(self): self.pyver = _get_python_version() if _PyZDDE.liveCh==0: try: _PyZDDE.server = _dde.CreateServer() _PyZDDE.server.Create("ZCLIENT") except Exception as err: _sys.stderr.write("{}: DDE server ...
Initiates link with OpticStudio DDE server
386,243
def get(self, key): o = self.data[key]() if o is None: del self.data[key] raise CacheFault( "FinalizingCache has %r but its value is no more." % (key,)...
Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subclass) if the given key is present in the cache, but the value it points to is gone.
386,244
def dict_to_env(d, pathsep=os.pathsep): out_env = {} for k, v in d.iteritems(): if isinstance(v, list): out_env[k] = pathsep.join(v) elif isinstance(v, string_types): out_env[k] = v else: raise TypeError(.format(type(v))) return out_env
Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep)
386,245
def grid(script, size=1.0, x_segments=1, y_segments=1, center=False, color=None): size = util.make_list(size, 2) filter_xml = .join([ , , .format(size[0]), , , , , .format(size[1]), , , , , .for...
2D square/plane/grid created on XY plane x_segments # Number of segments in the X direction. y_segments # Number of segments in the Y direction. center="false" # If true square will be centered on origin; otherwise it is place in the positive XY quadrant.
386,246
def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False): abf.setsweep(sweep) if m1 is None: m1=0 else: m1=m1*abf.pointsPerSec if m2 is None: m2=-1 else: m2=m2*abf.pointsPerSec Yorig=abf.sweepY[int(m1):int(m2)] X=np.arange(len(Yorig))/abf.pointsPerSec Ylpf=linear_gaussian(Yo...
m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs]
386,247
def record(self): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() return b + struct.pack(, RRRERecord.length(), SU_ENTRY_VERSION)
Generate a string representing the Rock Ridge Relocated Directory record. Parameters: None. Returns: String containing the Rock Ridge record.
386,248
def FaultFromException(ex, inheader, tb=None, actor=None): tracetext = None if tb: try: lines = .join([ % (name, line, func) for name, line, func, text in traceback.extract_tb(tb)]) except: pass else: tracetext = lines ...
Return a Fault object created from a Python exception. <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Processing Failure</faultstring> <detail> <ZSI:FaultDetail> <ZSI:string></ZSI:string> <ZSI:trace></ZSI:trace> </ZSI:FaultDetail> </...
386,249
def getoutputerror(cmd): out_err = process_handler(cmd, lambda p: p.communicate()) if out_err is None: return , out, err = out_err return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err)
Return (standard output, standard error) of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str stderr : str
386,250
def setMotorShutdown(self, value, device=DEFAULT_DEVICE_ID, message=True): return self._setMotorShutdown(value, device, message)
Set the motor shutdown on error status stored on the hardware device. :Parameters: value : `int` An integer indicating the effect on the motors when an error occurs. A `1` will cause the cause the motors to stop on an error and a `0` will ignore errors keeping the ...
386,251
def xpathNextChild(self, cur): if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextChild(self._o, cur__o) if ret is None:raise xpathError() __tmp = xmlNode(_obj=ret) return __tmp
Traversal function for the "child" direction The child axis contains the children of the context node in document order.
386,252
def to_json(value, pretty=False): options = { : False, : BasicJSONEncoder, } if pretty: options[] = 2 options[] = (, ) return json.dumps(value, **options)
Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str
386,253
def t_text(self, t): r t.lexer.text_start = t.lexer.lexpos - len() t.lexer.begin()
r':\s*<text>
386,254
def count(self, request, *args, **kwargs): self.queryset = self.filter_queryset(self.get_queryset()) return response.Response({: self.queryset.count()}, status=status.HTTP_200_OK)
To get a count of events - run **GET** against */api/events/count/* as authenticated user. Endpoint support same filters as events list. Response example: .. code-block:: javascript {"count": 12321}
386,255
def conn_gcp(cred, crid): gcp_auth_type = cred.get(, "S") if gcp_auth_type == "A": gcp_crd_ia = CONFIG_DIR + ".gcp_libcloud_a_auth." + cred[] gcp_crd = {: cred[], : cred[], : cred[], : "IA", : gcp_crd_ia} else...
Establish connection to GCP.
386,256
def create_symlinks(d): data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in data["pages"][work]: work = data["page...
Create new symbolic links in output directory.
386,257
def list_slot_differences_slot( self, resource_group_name, name, slot, target_slot, preserve_vnet, custom_headers=None, raw=False, **operation_config): slot_swap_entity = models.CsmSlotEntity(target_slot=target_slot, preserve_vnet=preserve_vnet) def internal_paging(next_link=None, ...
Get the difference in configuration settings between two web app slots. Get the difference in configuration settings between two web app slots. :param resource_group_name: Name of the resource group to which the resource belongs. :type resource_group_name: str :param name: Nam...
386,258
def _suppress_distutils_logs(): f = distutils.log.Log._log def _log(log, level, msg, args): if level >= distutils.log.ERROR: f(log, level, msg, args) distutils.log.Log._log = _log yield distutils.log.Log._log = f
Hack to hide noise generated by `setup.py develop`. There isn't a good way to suppress them now, so let's monky-patch. See https://bugs.python.org/issue25392.
386,259
def close(self): if self.session is not None: self.session.cookies.clear() self.session.close() self.session = None
Close the current session, if still open.
386,260
def disable_ipython(self): from IPython.core.getipython import get_ipython self.ipython_enabled = False ip = get_ipython() formatter = ip.display_formatter.formatters[] formatter.type_printers.pop(Visualization, None) formatter.type_printers.pop(VisualizationLoc...
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
386,261
def api(self): api = getattr(self, , None) if api is None: self._api = mailjet.Api() return self._api
Get or create an Api() instance using django settings.
386,262
def estimate_from_ssr(histograms, readout_povm, channel_ops, settings): nqc = len(channel_ops[0].dims[0]) pauli_basis = grove.tomography.operator_utils.PAULI_BASIS ** nqc pi_basis = readout_povm.pi_basis if not histograms.shape[1] == pi_basis.dim: raise ValueError...
Estimate a density matrix from single shot histograms obtained by measuring bitstrings in the Z-eigenbasis after application of given channel operators. :param numpy.ndarray histograms: The single shot histograms, `shape=(n_channels, dim)`. :param DiagognalPOVM readout_povm: The POVM correspond...
386,263
def get_resource_area(self, area_id, enterprise_name=None, organization_name=None): route_values = {} if area_id is not None: route_values[] = self._serialize.url(, area_id, ) query_parameters = {} if enterprise_name is not None: query_parameters[] = self...
GetResourceArea. [Preview API] :param str area_id: :param str enterprise_name: :param str organization_name: :rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>`
386,264
def _setBitOn(x, bitNum): _checkInt(x, minvalue=0, description=) _checkInt(bitNum, minvalue=0, description=) return x | (1 << bitNum)
Set bit 'bitNum' to True. Args: * x (int): The value before. * bitNum (int): The bit number that should be set to True. Returns: The value after setting the bit. This is an integer. For example: For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (...
386,265
def post(self): self.write(resultdict) self.finish()
This handles POST requests. Saves the changes made by the user on the frontend back to the current checkplot-list.json file.
386,266
def handle_webhook_event(self, environ, url, params): for handler in self.events["webhook"]: urlpattern = handler.event.args["urlpattern"] if not urlpattern or match(urlpattern, url): response = handler(self, environ, url, params) if response: ...
Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response.
386,267
def _prepare_executor(self, data, executor): logger.debug(__("Preparing executor for Data with id {}", data.id))
Copy executor sources into the destination directory. :param data: The :class:`~resolwe.flow.models.Data` object being prepared for. :param executor: The fully qualified name of the executor that is to be used for this data object. :return: Tuple containing the relative ...
386,268
def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]: identifiers = set() composite_axes = [] if in expression: if not in expression: raise EinopsError() if str.count(expression, ) != 1 or str.count(expression, ) != 3: raise EinopsError...
Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups
386,269
def apply_mutation(module_path, operator, occurrence): module_ast = get_ast(module_path, python_version=operator.python_version) original_code = module_ast.get_code() visitor = MutationVisitor(occurrence, operator) mutated_ast = visitor.walk(module_ast) mutated_code = None if visitor.mutat...
Apply a specific mutation to a file on disk. Args: module_path: The path to the module to mutate. operator: The `operator` instance to use. occurrence: The occurrence of the operator to apply. Returns: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was no ...
386,270
def parse_rcfile(rcfile): def parse_bool(value): value = value.lower() if value in [, ]: return True elif value in [, ]: return False else: raise ValueError(t parse {}sizecommenttemplatereverseoppositeposition fi...
Parses rcfile Invalid lines are ignored with a warning
386,271
def dropped(self, param, event): if event.source() == self or isinstance(param, AddLabel): index = self.indexAt(event.pos()) self.model().insertRows(index.row(),1) if event.source() == self: self.model().setData(index, param) else: ...
Adds the dropped parameter *param* into the protocol list. Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>`
386,272
def call(self, command, *args): command = self._normalize_command_name(command) args = self._normalize_command_args(command, *args) redis_function = getattr(self, command) value = redis_function(*args) return self._normalize_command_response(command, value)
Sends call to the function, whose name is specified by command. Used by Script invocations and normalizes calls using standard Redis arguments to use the expected redis-py arguments.
386,273
def get_assessment_offered_query_session_for_bank(self, bank_id): if not self.supports_assessment_offered_query(): raise errors.Unimplemented() return sessions.AssessmentOfferedQuerySession(bank_id, runtime=self._runtime)
Gets the ``OsidSession`` associated with the assessment offered query service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentOfferedQuerySession) - an ``AssessmentOfferedQuerySession`` raise: NotFound - ``bank_id`` no...
386,274
def get_vocab(self, vocab_name, **kwargs): vocab_dict = self.__get_vocab_dict__(vocab_name, **kwargs) filepaths = list(set([os.path.join(self.cache_dir, vocab_dict[]), os.path.join(self.vocab_dir, ...
Returns data stream of an rdf vocabulary args: vocab_name: the name or uri of the vocab to return
386,275
def produce(self, **kwargs): produce_args = self._produce_params.copy() produce_args.update(kwargs) if self._class: return getattr(self.instance, self.produce_method)(**produce_args) produce_args.update(self._hyperparameters) return self.primitive(**produce_...
Call the primitive function, or the predict method of the primitive. The given keyword arguments will be passed directly to the primitive, if it is a simple function, or to the `produce` method of the primitive instance specified in the JSON annotation, if it is a class. If any of the ...
386,276
def parse_sdk_name(name): if all(part.isdigit() for part in name.split(, 2)): return DOWNLOAD_URL % name url = urlparse.urlparse(name) if url.scheme: return name return os.path.abspath(name)
Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path.
386,277
def set_properties(self, properties, recursive=True): if not properties: return return self._accessor.set_properties(self, properties, recursive)
Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values for a key. recursive - on folders property attachment is rec...
386,278
def galleries(self): api_version = self._get_api_version() if api_version == : from .v2018_06_01.operations import GalleriesOperations as OperationClass elif api_version == : from .v2019_03_01.operations import GalleriesOperations as OperationClass else: ...
Instance depends on the API version: * 2018-06-01: :class:`GalleriesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleriesOperations>` * 2019-03-01: :class:`GalleriesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleriesOperations>`
386,279
def qteBindKeyWidget(self, keysequence, macroName: str, widgetObj: QtGui.QWidget): keysequence = QtmacsKeysequence(keysequence) if not hasattr(widgetObj, ): msg = msg += raise QtmacsOtherError(ms...
Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used to individualise the key bindings inside every applet instance and every widget inside that instance. Even mult...
386,280
def randomColor( self ): r = random.randint(120, 180) g = random.randint(120, 180) b = random.randint(120, 180) return QColor(r, g, b)
Generates a random color. :return <QColor>
386,281
def log_likelihood(self,x, K_extra=1): x = np.asarray(x) ks = self._get_occupied() K = len(ks) K_total = K + K_extra obs_distns = [] for k in range(K): o = copy.deepcopy(self.obs_distn) o.resample(data=self._get_data_withlabel(k)...
Estimate the log likelihood with samples from the model. Draw k_extra components which were not populated by the current model in order to create a truncated approximate mixture model.
386,282
def DbUnExportServer(self, argin): self._log.debug("In DbUnExportServer()") self.db.unexport_server(argin)
Mark all devices belonging to a specified device server process as non exported :param argin: Device server name (executable/instance) :type: tango.DevString :return: :rtype: tango.DevVoid
386,283
def convolve_spatial3(im, psfs, mode="constant", grid_dim=None, sub_blocks=None, pad_factor=2, plan=None, return_plan=False, verbose=False): ndim = im.ndim ...
GPU accelerated spatial varying convolution of an 3d image with a (Gz, Gy, Gx) grid of psfs assumed to be equally spaced within the image the input image im is subdivided into (Gz, Gy,Gx) blocks, each block is convolved with the corresponding psf and linearly interpolated to give the final result ...
386,284
def slice_bounds_by_doubling(x_initial, target_log_prob, log_slice_heights, max_doublings, step_size, seed=None, name=None): with tf.compat.v...
Returns the bounds of the slice at each stage of doubling procedure. Precomputes the x coordinates of the left (L) and right (R) endpoints of the interval `I` produced in the "doubling" algorithm [Neal 2003][1] P713. Note that we simultaneously compute all possible doubling values for each chain, for the reaso...
386,285
def pretty_repr(instance): instance_type = type(instance) if not is_registered( instance_type, check_superclasses=True, check_deferred=True, register_deferred=True ): warnings.warn( "pretty_repr is assigned as the __repr__ method of " ". ...
A function assignable to the ``__repr__`` dunder method, so that the ``prettyprinter`` definition for the type is used to provide repr output. Usage: .. code:: python from prettyprinter import pretty_repr class MyClass: __repr__ = pretty_repr
386,286
def _dpi(self, resolution_tag): ifd_entries = self._ifd_entries if resolution_tag not in ifd_entries: return 72 resolution_unit = ( ifd_entries[TIFF_TAG.RESOLUTION_UNIT] if TIFF_TAG.RESOLUTION_UNIT in ifd_entries else 2 ) i...
Return the dpi value calculated for *resolution_tag*, which can be either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The calculation is based on the values of both that tag and the TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries| instance.
386,287
def get_purchase(self, purchase_id, purchase_key=): data = {: purchase_id, : purchase_key} return self.api_get(, data)
Retrieve information about a purchase using the system's unique ID or a client's ID @param id_: a string that represents a unique_id or an extid. @param key: a string that is either 'sid' or 'extid'.
386,288
def setup_logger(debug, color): if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger = logging.getLogger() stream = Handler(log_level, debug, color) logger.addHandler(stream) logger.setLevel(log_level)
Configure the logger.
386,289
def from_graph(cls, graph, linear_energy_ranges, quadratic_energy_ranges): get_env().enable_infix_notation = True theta = cls.empty(dimod.SPIN) theta.add_offset(Symbol(, REAL)) def Linear(v): bias = Symbol(.format(v), REAL) min_, max_ =...
Create Theta from a graph and energy ranges. Args: graph (:obj:`networkx.Graph`): Provides the structure for Theta. linear_energy_ranges (dict): A dict of the form {v: (min, max), ...} where min and max are the range of values allowed to ...
386,290
def save(self): if self.compression and hasattr(self.path_or_buf, ): msg = ("compression has no effect when passing file-like " "object as input.") warnings.warn(msg, RuntimeWarning, stacklevel=2) is_zip = isinstance(self.path_or_buf...
Create the writer & save
386,291
def access_token(): client = Client.query.filter_by( client_id=request.form.get() ).first() if not client: abort(404) if not client.is_confidential and \ == request.form.get(): error = InvalidClientError() response = jsonify(dict(error.twotuples)) ...
Token view handles exchange/refresh access tokens.
386,292
def camelcase_underscore(name): s1 = re.sub(, r, name) return re.sub(, r, s1).lower()
Convert camelcase names to underscore
386,293
def pull(i): o=i.get(,) xrecache=False pp=[] px=i.get(,) t=i.get(,) url=i.get(,) stable=i.get(,) version=i.get(,) if stable==: version= branch=i.get(,) checkout=i.get(,) ip=i.get(,) cr=i.get(,[]) tt= if i.get(,)==: tt= if px!=: pp.appe...
Input: { (path) - repo UOA (where to create entry) (type) - type (url) - URL or (data_uoa) - repo UOA (clone) - if 'yes', clone repo instead of update (current_repos) - if resolving dependencies on ...
386,294
def register_action(self, name, **kwargs): settings = foundations.data_structures.Structure(**{"parent": None, "text": None, "icon": None, ...
Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: Action. :rtype: QAction
386,295
def _retrieveRegions(self): self.sensors = [] self.coarseSensors = [] self.locationInputs = [] self.L4Columns = [] self.L2Columns = [] self.L5Columns = [] self.L6Columns = [] for i in xrange(self.numColumns): self.sensors.append( self.network.regions["sensorInput_" + ...
Retrieve and store Python region instances for each column
386,296
def load_all(self, group): for ep in iter_entry_points(group=group): plugin = ep.load() plugin(self.__config)
Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the everest configurator as single argument.
386,297
def salvar(self, destino=None, prefix=, suffix=): if destino: if os.path.exists(destino): raise IOError((errno.EEXIST, , destino,)) destino = os.path.abspath(destino) fd = os.open(destino, os.O_EXCL|os.O_CREAT|os.O_WRONLY) else: fd...
Salva o arquivo de log decodificado. :param str destino: (Opcional) Caminho completo para o arquivo onde os dados dos logs deverão ser salvos. Se não informado, será criado um arquivo temporário via :func:`tempfile.mkstemp`. :param str prefix: (Opcional) Prefixo para o nome do ...
386,298
def port_str_arrange(ports): b_tcp = ports.find("T") b_udp = ports.find("U") if (b_udp != -1 and b_tcp != -1) and b_udp < b_tcp: return ports[b_tcp:] + ports[b_udp:b_tcp] return ports
Gives a str in the format (always tcp listed first). T:<tcp ports/portrange comma separated>U:<udp ports comma separated>
386,299
def to_phase(self, time, component=None, t0=, **kwargs): if kwargs.get(, False): raise ValueError("support for phshift was removed as of 2.1. Please pass t0 instead.") ephem = self.get_ephemeris(component=component, t0=t0, **kwargs) if isinstance(time, list): ...
Get the phase(s) of a time(s) for a given ephemeris :parameter time: time to convert to phases (should be in same system as t0s) :type time: float, list, or array :parameter t0: qualifier of the parameter to be used for t0 :type t0: str :parameter str component: comp...