Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
2,200
def cells_rt_meta(workbook, sheet, row, col): logger_excel.info("enter cells_rt_meta") col_loop = 0 cell_data = [] temp_sheet = workbook.sheet_by_name(sheet) while col_loop < temp_sheet.ncols: col += 1 col_loop += 1 try: if temp_sheet.cell_value(row, col) != ...
Traverse all cells in a row. If you find new data in a cell, add it to the list. :param obj workbook: :param str sheet: :param int row: :param int col: :return list: Cell data for a specific row
2,201
def render_html(self, obj, context=None): provided_context = context or Context() context = RequestContext(mock_request()) context.update(provided_context) context.push() context[self._meta.context_varname] = obj rendered = render_to_string(self....
Generate the 'html' attribute of an oembed resource using a template. Sort of a corollary to the parser's render_oembed method. By default, the current mapping will be passed in as the context. OEmbed templates are stored in: oembed/provider/[app_label]_[model].html ...
2,202
def lreshape(data, groups, dropna=True, label=None): if isinstance(groups, dict): keys = list(groups.keys()) values = list(groups.values()) else: keys, values = zip(*groups) all_cols = list(set.union(*[set(x) for x in values])) id_cols = list(data.columns.difference(all_col...
Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... ...
2,203
def face_function(script, function=): filter_xml = .join([ , , .format(str(function).replace(, ).replace(, )), , , , ]) util.write_filter(script, filter_xml) return None
Boolean function using muparser lib to perform face selection over current mesh. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, <, >, = It's possible to use per-face variables like...
2,204
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method=, **kwargs): r fun_inverse.fun = cost_fun.fun = fun if fun is not None else getattr(fun_inverse, , lambda x: x) fun_inverse.target = cost_fun.target = y or 0 fun_inverse.verbose = verbose = cost_fun.verbose = kwargs.pop( , getat...
r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate an inverse for y (float): desired output of fun x0 (float): initial guess at input to ...
2,205
def create_ar (archive, compression, cmd, verbosity, interactive, filenames): opts = if verbosity > 1: opts += cmdlist = [cmd, opts, archive] cmdlist.extend(filenames) return cmdlist
Create a AR archive.
2,206
def available_composite_ids(self, available_datasets=None): if available_datasets is None: available_datasets = self.available_dataset_ids(composites=False) else: if not all(isinstance(ds_id, DatasetID) for ds_id in available_datasets): raise ValueError( ...
Get names of compositors that can be generated from the available datasets. Returns: generator of available compositor's names
2,207
def _hijack_gtk(self): def dummy(*args, **kw): pass orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit
Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop ...
2,208
def _detect_sse41(self): "Does this compiler support SSE4.1 intrinsics?" self._print_support_start() result = self.hasfunction( , include=, extra_postargs=[]) self._print_support_end(, result) return result
Does this compiler support SSE4.1 intrinsics?
2,209
def newton(self): dae = self.system.dae while True: inc = self.calc_inc() dae.x += inc[:dae.n] dae.y += inc[dae.n:dae.n + dae.m] self.niter += 1 max_mis = max(abs(inc)) self.iter_mis.append(max_mis) self._it...
Newton power flow routine Returns ------- (bool, int) success flag, number of iterations
2,210
def type_converter(text): if text.isdigit(): return int(text), int try: return float(text), float except ValueError: return text, STRING_TYPE
I convert strings into integers, floats, and strings!
2,211
def jsonresolver_loader(url_map): def endpoint(doi_code): pid_value = "10.13039/{0}".format(doi_code) _, record = Resolver(pid_type=, object_type=, getter=Record.get_record).resolve(pid_value) return record pattern = url_map.add(Rule(pattern, endpo...
Jsonresolver hook for funders resolving.
2,212
def b_pathInTree(self, astr_path): if astr_path == : return True, [] al_path = astr_path.split() if astr_path != and al_path[-1] == : al_path = al_path[0:-2] if not len(al_path[0]): al...
Converts a string <astr_path> specifier to a list-based *absolute* lookup, i.e. "/node1/node2/node3" is converted to ['/' 'node1' 'node2' 'node3']. The method also understands a paths that start with: '..' or combination of '../../..' and is also aware that the root ...
2,213
def get_model_indexes(model, add_reserver_flag=True): import uliweb.orm as orm from sqlalchemy.engine.reflection import Inspector indexes = [] engine = model.get_engine().engine insp = Inspector.from_engine(engine) for index in insp.get_indexes(model.tablename): d = {} d[] ...
Creating indexes suit for model_config.
2,214
def parse_mini(memory_decriptor, buff): mms = MinidumpMemorySegment() mms.start_virtual_address = memory_decriptor.StartOfMemoryRange mms.size = memory_decriptor.Memory.DataSize mms.start_file_address = memory_decriptor.Memory.Rva mms.end_virtual_address = mms.start_virtual_address + mms.size return mms
memory_descriptor: MINIDUMP_MEMORY_DESCRIPTOR buff: file_handle
2,215
def obfn_dfd(self): r Ef = self.eval_Rf(self.Xf) E = sl.irfftn(Ef, self.cri.Nv, self.cri.axisN) return (np.linalg.norm(self.W * E)**2) / 2.0
r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m \mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`
2,216
def create_argparser(): parser = argparse.ArgumentParser() arg_defaults = { "daemon": False, "loop": False, "listpresets": False, "config": None, "debug": False, "sleeptime": 300, "version": False, "verbose_count": 0 } parser.add...
Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values.
2,217
def get_block_info(self): if not self.finished: raise Exception("Not finished downloading") ret = [] for (block_hash, block_data) in self.block_info.items(): ret.append( (block_data[], block_data[]) ) return ret
Get the retrieved block information. Return [(height, [txs])] on success, ordered on height Raise if not finished downloading
2,218
def request_forward_agent(self, handler): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException() m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string() m.add_boolean(False) ...
Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param function handler: a required handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ok) :raises: SS...
2,219
def guest_delete_disks(self, userid, disk_vdev_list): action = "delete disks from guest " % (str(disk_vdev_list), userid) with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.delete_disks(userid, disk_vdev_list)
Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102']
2,220
def _extensions(self, line): line = line.strip() if not line.startswith("//") and "." in line: line = line.encode("idna").decode("utf-8") if line.startswith("*."): line ...
Extract the extension from the given line. :param line: The line from the official public suffix repository. :type line: str
2,221
def _set_request_referer_metric(self, request): if in request.META and request.META[]: monitoring.set_custom_metric(, request.META[])
Add metric 'request_referer' for http referer.
2,222
def get_effect_class(self, effect_name: str, package_name: str = None) -> Type[]: return self._project.get_effect_class(effect_name, package_name=package_name)
Get an effect class by the class name Args: effect_name (str): Name of the effect class Keyword Args: package_name (str): The package the effect belongs to. This is optional and only needed when effect class names are not unique. Returns...
2,223
def open_required(func): def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return wrapper
Use this decorator to raise an error if the project is not opened
2,224
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names): print() if names == : tf_name = + random_string(4) elif names == : tf_name = w_name else: tf_name = w_name + str(random.random()) output_size = params[] align_corners = para...
Convert upsample_bilinear2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short n...
2,225
def hoverEnterEvent(self, event): self._hovered = True if self.toolTip(): QToolTip.showText(QCursor.pos(), self.toolTip()) return True return self.style() == XNodeHotspot.Style.Icon
Processes when this hotspot is entered. :param event | <QHoverEvent> :return <bool> | processed
2,226
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs): return cls._basis_spline_factory(coef, degree, knots, 1, ext)
Given some coefficients, return a the derivative of a B-spline.
2,227
def voltage_delta_vde(v_nom, s_max, r, x, cos_phi): delta_v = (s_max * ( r * cos_phi + x * math.sin(math.acos(cos_phi)))) / v_nom ** 2 return delta_v
Estimate voltrage drop/increase The VDE [#]_ proposes a simplified method to estimate voltage drop or increase in radial grids. Parameters ---------- v_nom : int Nominal voltage s_max : float Apparent power r : float Short-circuit resistance from node to HV/MV subst...
2,228
def open(filename, mode="r", iline = 189, xline = 193, strict = True, ignore_geometry = False, endian = ): if in mode: problem = solution = raise ValueError(.join((pro...
Open a segy file. Opens a segy file and tries to figure out its sorting, inline numbers, crossline numbers, and offsets, and enables reading and writing to this file in a simple manner. For reading, the access mode `r` is preferred. All write operations will raise an exception. For writing, the mo...
2,229
def _unmount_devicemapper(self, cid): mountpoint = self.mountpoint Mount.unmount_path(mountpoint) cinfo = self.client.inspect_container(cid) dev_name = cinfo[][][] Mount.remove_thin_device(dev_name) self._cleanup_container(cinfo)
Devicemapper unmount backend.
2,230
def text_ui(self): self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
Start Text UI main loop
2,231
def _get_name(self, name): team_name = name.text() abbr = self._parse_abbreviation(name) non_di = False if not abbr: abbr = team_name non_di = True return team_name, abbr, non_di
Find a team's name and abbreviation. Given the team's HTML name tag, determine their name, abbreviation, and whether or not they compete in Division-I. Parameters ---------- name : PyQuery object A PyQuery object of a team's HTML name tag in the boxscore. R...
2,232
def save_code(self, title, addr, _bytes): self.standard_bytes_header(title, addr, len(_bytes)) _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] self.standard_block(_bytes)
Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes
2,233
def nvmlDeviceGetCurrPcieLinkWidth(handle): r fn = _nvmlGetFunctionPointer("nvmlDeviceGetCurrPcieLinkWidth") width = c_uint() ret = fn(handle, byref(width)) _nvmlCheckReturn(ret) return bytes_to_str(width.value)
r""" /** * Retrieves the current PCIe link width * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param currLinkWidth Reference in which to return the current PCIe link gen...
2,234
def image(self, well_row, well_column, field_row, field_column): return next((i for i in self.images if attribute(i, ) == well_column and attribute(i, ) == well_row and attribute(i, ) == field_column and attrib...
Get path of specified image. Parameters ---------- well_row : int Starts at 0. Same as --U in files. well_column : int Starts at 0. Same as --V in files. field_row : int Starts at 0. Same as --Y in files. field_column : int ...
2,235
def modified_Wilson_Vc(zs, Vcs, Aijs): r if not none_and_length_check([zs, Vcs]): raise Exception() C = -2500 Vcm = sum(zs[i]*Vcs[i] for i in range(len(zs))) for i in range(len(zs)): Vcm += C*zs[i]*log(zs[i] + sum(zs[j]*Aijs[i][j] for j in range(len(zs))))/1E6 return Vcm
r'''Calculates critical volume of a mixture according to mixing rules in [1]_ with parameters. Equation .. math:: V_{cm} = \sum_i x_i V_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)V_{ref} For a binary mxiture, this simplifies to: .. math:: V_{cm} = x_1 V_{c1} + x_2 V_{c...
2,236
def __startOpenThread(self): print try: if self.hasActiveDatasetToCommit: if self.__sendCommand()[0] != : raise Exception() else: self.hasActiveDatasetToCommit = False if self.isPowerD...
start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack
2,237
def _close_stdout_stderr_streams(self): if self._stdout_tee.tee_file is not None: self._stdout_tee.tee_file.close() if self._stderr_tee.tee_file is not None: self._stderr_tee.tee_file.close() self._stdout_tee.close_join() ...
Close output-capturing stuff. This also flushes anything left in the buffers.
2,238
def expected_log_joint_probability(self): from pyslds.util import expected_hmm_logprob elp = expected_hmm_logprob( self.pi_0, self.trans_matrix, (self.expected_states, self.expected_transcounts, self._normalizer)) elp += np.sum(self.ex...
Compute E_{q(z) q(x)} [log p(z) + log p(x | z) + log p(y | x, z)]
2,239
def _run_configure_script(self, script): _, tmpFile = tempfile.mkstemp() with open(tmpFile, ) as f: f.write(script) try: ssh = self._get_ssh_client( self.host, "ubuntu", self.private_key_path, ...
Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
2,240
def run(suite, stream, args, testing=False): if not issubclass(GreenStream, type(stream)): stream = GreenStream(stream, disable_windows=args.disable_windows, disable_unidecode=args.disable_unidecode) result = GreenTestResult(args, stream) if not msg: ...
Run the given test case or test suite with the specified arguments. Any args.stream passed in will be wrapped in a GreenStream
2,241
def data(self, data, part=False, dataset=): imgs = self.imgtype.convert(data) for channel, data in zip(self.imgtype.channels, imgs): key = dataset + channel data = self.scanner(data, part) if isinstance(self.parser, LevelParser): ...
Parameters ---------- data : `PIL.Image` Image to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: '').
2,242
def get_object(self, subject=None, predicate=None): results = self.rdf.objects(subject, predicate) as_list = list(results) if not as_list: return None return as_list[0]
Eliminates some of the glue code for searching RDF. Pass in a URIRef object (generated by the `uri` function above or a BNode object (returned by this function) for either of the parameters.
2,243
def gcs_get_url(url, altexts=None, client=None, service_account_json=None, raiseonfail=False): bucket_item = url.replace(,) bucket_item = bucket_item.split() bucket = bucket_item[0] filekey = .join(bucket_item[1:]) return gcs_get_...
This gets a single file from a Google Cloud Storage bucket. This uses the gs:// URL instead of a bucket name and key. Parameters ---------- url : str GCS URL to download. This should begin with 'gs://'. altexts : None or list of str If not None, this is a list of alternate extens...
2,244
def prime(self): for d in self.definitions.values(): self.defined[d.name] = d.default return self
Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties}
2,245
def _verify_inputs(inputs, channel_index, data_format): input_shape = tuple(inputs.get_shape().as_list()) if len(input_shape) != len(data_format): raise base.IncompatibleShapeError(( "Input Tensor must have rank {} corresponding to " "data_format {}, but instead was {} of rank {}.").format...
Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If the shape of `inputs` doesn't match `data_format`. ba...
2,246
async def get_protocol_version(self): value = await self.core.get_protocol_version() if value: reply = json.dumps({"method": "protocol_version_reply", "params": value}) else: reply = json.dumps({"method": "protocol_version_reply", "params": "Unknown"}) aw...
This method retrieves the Firmata protocol version. JSON command: {"method": "get_protocol_version", "params": ["null"]} :returns: {"method": "protocol_version_reply", "params": [PROTOCOL_VERSION]}
2,247
def fixed_inputs(model, non_fixed_inputs, fix_routine=, as_list=True, X_all=False): from ...inference.latent_function_inference.posterior import VariationalPosterior f_inputs = [] if hasattr(model, ) and model.has_uncertain_inputs(): X = model.X.mean.values.copy() elif isinstance(model.X, V...
Convenience function for returning back fixed_inputs where the other inputs are fixed using fix_routine :param model: model :type model: Model :param non_fixed_inputs: dimensions of non fixed inputs :type non_fixed_inputs: list :param fix_routine: fixing routine to use, 'mean', 'median', 'zero' ...
2,248
def refreshButtons(self): last = self._last first = self._first joiner = self._containerWidget.currentJoiner() if first: self.uiJoinSBTN.setActionTexts([, ]) elif joiner == QueryCompound.Op.And: self.uiJoinSBTN...
Refreshes the buttons for building this sql query.
2,249
def display(self): w, h = self.session.window_size() return Display(w*self.scale, h*self.scale)
Get screen width and height
2,250
def expQt(self, t): eLambdaT = np.diag(self._exp_lt(t)) Qs = self.v.dot(eLambdaT.dot(self.v_inv)) return np.maximum(0,Qs)
Parameters ---------- t : float Time to propagate Returns -------- expQt : numpy.array Matrix exponential of exo(Qt)
2,251
def codigo_ibge_uf(sigla): idx = [s for s, i, n, r in UNIDADES_FEDERACAO].index(sigla) return UNIDADES_FEDERACAO[idx][_UF_CODIGO_IBGE]
Retorna o código do IBGE para a UF informada.
2,252
def ColorLuminance(color): r = int(color[0:2], 16) g = int(color[2:4], 16) b = int(color[4:6], 16) return (299*r + 587*g + 114*b) / 1000.0
Compute the brightness of an sRGB color using the formula from http://www.w3.org/TR/2000/WD-AERT-20000426#color-contrast. Args: color: a string of 6 hex digits in the format verified by IsValidHexColor(). Returns: A floating-point number between 0.0 (black) and 255.0 (white).
2,253
def entity_to_protobuf(entity): entity_pb = entity_pb2.Entity() if entity.key is not None: key_pb = entity.key.to_protobuf() entity_pb.key.CopyFrom(key_pb) for name, value in entity.items(): value_is_list = isinstance(value, list) value_pb = _new_value_pb(entity_pb, na...
Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity.
2,254
def connect(self, factory): try: factory = self._factories[factory] except KeyError: raise NoSuchFactory() remote = self.getProtocol() addr = remote.transport.getPeer() proto = factory.buildProtocol(addr) if proto is None: rai...
Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will then store the protocol under a...
2,255
def error_redirect(self, errormsg=, errorlog=): from django.shortcuts import redirect self.lti_errormsg = errormsg self.lti_errorlog = errorlog return redirect(self.build_return_url())
Shortcut for redirecting Django view to LTI Consumer with errors
2,256
def add_eval(self, agent, e, fr=None): self._evals[agent.name] = e self._framings[agent.name] = fr
Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation.
2,257
def XYZ_to_galcenrect(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True): if _extra_rot: X,Y,Z= nu.dot(galcen_extra_rot,nu.array([X,Y,Z])) dgc= nu.sqrt(Xsun**2.+Zsun**2.) costheta, sintheta= Xsun/dgc, Zsun/dgc return nu.dot(nu.array([[costheta,0.,-sintheta], [0.,1.,0.], ...
NAME: XYZ_to_galcenrect PURPOSE: transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates INPUT: X - X Y - Y Z - Z Xsun - cylindrical distance to the GC Zsun - Sun's height above the midplane _extra_rot= (True) if True...
2,258
def value_splitter(self, reference, prop, value, mode): items = [] if mode == : try: items = json.loads(value) except json.JSONDecodeError as e: print(value) msg = ("Reference raised JSON decoder error when " ...
Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property name used when raising possible error. value (string): Property v...
2,259
def t_string_NGRAPH(t): r"\\[ .:]" global __STRING P = {: 0, ".: ": 1, : 4, : 5} __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
r"\\[ '.:][ '.:]
2,260
def writeImageToFile(self, filename, _format="PNG"): filename = self.device.substituteDeviceTemplate(filename) if not os.path.isabs(filename): raise ValueError("writeImageToFile expects an absolute path (fielname=)" % filename) if os.path.isdir(filename): filena...
Write the View image to the specified filename in the specified format. @type filename: str @param filename: Absolute path and optional filename receiving the image. If this points to a directory, then the filename is determined by this View unique ID and ...
2,261
def _num_players(self): self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == : self._player_num += 1 elif player.type == : self._computer_num += 1
Compute number of players, both human and computer.
2,262
def _iter_path_collection(paths, path_transforms, offsets, styles): N = max(len(paths), len(offsets)) if not path_transforms: path_transforms = [np.eye(3)] edgecolor = styles[] if np.size(edgecolor) == 0: edgecolor = [] facecolor = styles[] ...
Build an iterator over the elements of the path collection
2,263
def ecn(ns=None, cn=None, di=None): return CONN.EnumerateClassNames(ns, ClassName=cn, DeepInheritance=di)
This function is a wrapper for :meth:`~pywbem.WBEMConnection.EnumerateClassNames`. Enumerate the names of subclasses of a class, or of the top-level classes in a namespace. Parameters: ns (:term:`string`): Name of the CIM namespace to be used (case independent). If `None`, ...
2,264
def index(self, index, doc_type, body, id=None, **query_params): self._es_parser.is_not_empty_params(index, doc_type, body) method = HttpMethod.POST if id in NULL_VALUES else HttpMethod.PUT path = self._es_parser.make_path(index, doc_type, id) result = yield self._perform_reque...
Adds or updates a typed JSON document in a specific index, making it searchable. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :param index: The name of the index :param doc_type: The type of the document :param body: The document :param id...
2,265
def encrypted_gradient(self, sum_to=None): gradient = self.compute_gradient() encrypted_gradient = encrypt_vector(self.pubkey, gradient) if sum_to is not None: return sum_encrypted_vectors(sum_to, encrypted_gradient) else: return encrypted_gradient
Compute and encrypt gradient. When `sum_to` is given, sum the encrypted gradient to it, assumed to be another vector of the same size
2,266
def validate(self, ip, **kwargs): if ip is None: return False ip = stringify(ip) if self.IPV4_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET, ip) return True except AttributeError: t...
Check to see if this is a valid ip address.
2,267
def decorate_with_checker(func: CallableT) -> CallableT: assert not hasattr(func, "__preconditions__"), \ "Expected func to have no list of preconditions (there should be only a single contract checker per function)." assert not hasattr(func, "__postconditions__"), \ "Expected func to have...
Decorate the function with a checker that verifies the preconditions and postconditions.
2,268
def changeSubMenu(self,submenu): if submenu not in self.submenus: raise ValueError("Submenu %s does not exist!"%submenu) elif submenu == self.activeSubMenu: return old = self.activeSubMenu self.activeSubMenu = submenu if old is not None: ...
Changes the submenu that is displayed. :raises ValueError: if the name was not previously registered
2,269
def add_model_name_to_payload(cls, payload): if not cls.MODEL_NAME in payload: payload = {cls.MODEL_NAME: payload} return payload
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoi...
2,270
def add(path=None, force=False, quiet=False): option = if force else return run( % (option, path) or , quiet=quiet)
Add that path to git's staging area (default current dir) so that it will be included in next commit
2,271
def algorithm(G, method_name, **kwargs): warnings.warn("To be removed in 0.8. Use GraphCollection.analyze instead.", DeprecationWarning) return G.analyze(method_name, **kwargs)
Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the :class:`.GraphCollection` ``G``. For options, see the `list of algorithms <http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_ in the NetworkX documentation. Not all of these ...
2,272
def expect(self, searcher, timeout=3): timeout = float(timeout) end = time.time() + timeout match = searcher.search(self._history[self._start:]) while not match: incoming = self._stream_adapter.poll(end - time.time()) self.input_callback(inco...
Wait for input matching *searcher* Waits for input matching *searcher* for up to *timeout* seconds. If a match is found, the match result is returned (the specific type of returned result depends on the :class:`Searcher` type). If no match is found within *timeout* seconds, raise an :cl...
2,273
def build_structure(self, check_name, groups, source_name, limit=1): aggregates = {} aggregates[] = 0 aggregates[] = 0 high_priorities = [] medium_priorities = [] low_priorities = [] all_priorities = [] aggregates[] = 0 aggregates[] = 0 ...
Compiles the checks, results and scores into an aggregate structure which looks like: { "scored_points": 396, "low_count": 0, "possible_points": 400, "testname": "gliderdac", "medium_count": 2, "source_name": ".//rutgers/ru...
2,274
def delete_collection_namespaced_replica_set(self, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_collection_namespaced_replica_set_with_http_info(namespace, **kwargs) else: (data) = self.delete_collection_namespaced_replica_set_wit...
delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_replica_set(namesp...
2,275
def make_bcbiornaseq_object(data): if "bcbiornaseq" not in dd.get_tools_on(data): return data upload_dir = tz.get_in(("upload", "dir"), data) report_dir = os.path.join(upload_dir, "bcbioRNASeq") safe_makedir(report_dir) organism = dd.get_bcbiornaseq(data).get("organism", None) group...
load the initial bcb.rda object using bcbioRNASeq
2,276
def rollback(self, label=None, plane=): begin = time.time() rb_label = self._chain.target_device.rollback(label=label, plane=plane) elapsed = time.time() - begin if label: self.emit_message("Configuration rollback last {:.0f}s. Label: {}".format(elapsed, rb_label), ...
Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or None
2,277
def resource_redirect(id): resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
Redirect to the latest version of a resource given its identifier.
2,278
def submission_storage_path(instance, filename): string = .join([, instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)]) string += +datetime.datetime.now().strftime("%I:%M%p-%m-%d-%Y") string += filename return st...
Function DocString
2,279
def items(self): for values_str in self._v2b_dict: element_value = self._v2b_dict[values_str] yield element_value, values_str
Generator that iterates through the items of the value mapping. The items are the array entries of the `Values` and `ValueMap` qualifiers, and they are iterated in the order specified in the arrays. If the `ValueMap` qualifier is not specified, the default of consecutive integers startin...
2,280
def save(self, logmessage=None): if self.as_of_date is not None: raise RuntimeError() save_opts = {} if self.info_modified: if self.label: save_opts[] = self.label if self.mimetype: save_opts[] = self.mimetype ...
Save datastream content and any changed datastream profile information to Fedora. :rtype: boolean for success
2,281
def member_add(self, cluster_id, params): cluster = self._storage[cluster_id] result = cluster.member_add(params.get(, None), params.get(, {})) self._storage[cluster_id] = cluster return result
add new member into configuration
2,282
def find_field(self, field=None, alias=None): if alias: field = alias field = FieldFactory(field, table=self, alias=alias) identifier = field.get_identifier() for field in self.fields: if field.get_identifier() == identifier: return field ...
Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: :class:`Field <querybuilder.fields.Field>` or None
2,283
def _array_slice(array, index): if isinstance(index, slice): start = index.start stop = index.stop if (start is not None and start < 0) or ( stop is not None and stop < 0 ): raise ValueError() step = index.step if step is not None and st...
Slice or index `array` at `index`. Parameters ---------- index : int or ibis.expr.types.IntegerValue or slice Returns ------- sliced_array : ibis.expr.types.ValueExpr If `index` is an ``int`` or :class:`~ibis.expr.types.IntegerValue` then the return type is the element type of ...
2,284
def cxxRecordDecl(*args): kinds = [ CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, ] inner = [ PredMatcher(is_kind(k)) for k in kinds ] return allOf(anyOf(*inner), *args)
Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X
2,285
def get(package_name, pypi_server="https://pypi.python.org/pypi/"): if not pypi_server.endswith("/"): pypi_server = pypi_server + "/" response = requests.get("{0}{1}/json".format(pypi_server, package_name)) if response.status_code >= 300: ...
Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> package = yarg.get('yarg') <Package yarg>
2,286
def handle_sap(q): question_votes = votes = Answer.objects.filter(question=q) users = q.get_users_voted() num_users_votes = {u.id: votes.filter(user=u).count() for u in users} user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users} choices = [] for c in q.choice_set.all().order_by("num")...
Clear vote
2,287
def get_available_ip6(self, id_network6): if not is_valid_int_param(id_network6): raise InvalidParameterError( u) url = + str(id_network6) + "/" code, xml = self.submit(None, , url) return self.response(code, xml)
Get a available IP in Network ipv6 :param id_network6: Network ipv6 identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip6': {'ip6': < available_ip6 >}} :raise IpNotAvailableError: Network dont have available IP. ...
2,288
def hasx(self, name, *args): return lib.zargs_hasx(self._as_parameter_, name, *args)
Returns true if named parameter(s) was specified on command line
2,289
def Put(self, key, obj): node = self._hash.pop(key, None) if node: self._age.Unlink(node) node = Node(key=key, data=obj) self._hash[key] = node self._age.AppendNode(node) self.Expire() return key
Add the object to the cache.
2,290
def create_socketpair(size=None): parentfp, childfp = socket.socketpair() parentfp.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size or mitogen.core.CHUNK_SIZE) childfp.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, ...
Create a :func:`socket.socketpair` to use for use as a child process's UNIX stdio channels. As socket pairs are bidirectional, they are economical on file descriptor usage as the same descriptor can be used for ``stdin`` and ``stdout``. As they are sockets their buffers are tunable, allowing large buffe...
2,291
def by_name(cls, session, name, **kwargs): classifier = cls.first(session, where=(cls.name == name,)) if not kwargs.get(, False): return classifier if not classifier: splitted_names = [n.strip() for n in name.split(u)] classifiers = [u.join(splitted...
Get a classifier from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the classifier :type name: `unicode :return: classifier instance :rtype: :class:`pyshop.models.Classifier`
2,292
def get_point( self, x: float = 0, y: float = 0, z: float = 0, w: float = 0 ) -> float: return float(lib.NoiseGetSample(self._tdl_noise_c, (x, y, z, w)))
Return the noise value at the (x, y, z, w) point. Args: x (float): The position on the 1st axis. y (float): The position on the 2nd axis. z (float): The position on the 3rd axis. w (float): The position on the 4th axis.
2,293
def _ReadIntegerDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): definition_object = self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.IntegerDefinition, definition_name, self._SUPP...
Reads an integer data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data ty...
2,294
def transformer_tall_pretrain_lm(): hparams = transformer_tall() hparams.learning_rate_constant = 2e-4 hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay") hparams.optimizer = "adam_w" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon...
Hparams for transformer on LM pretraining (with 64k vocab).
2,295
def set_topic_attributes(TopicArn, AttributeName, AttributeValue, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.set_topic_attributes(TopicArn=TopicArn, AttributeName=AttributeName, ...
Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue
2,296
def get_title(self): try: return extract_literal(self.meta_kwargs[]) except KeyError: slot = self.get_slot() if slot is not None: return slot.replace(, ).title() return None
Return the string literal that is used in the template. The title is used in the admin screens.
2,297
def counter(self, ch, part=None): return Counter(self(self._key(ch), part=part))
Return a counter on the channel ch. ch: string or integer. The channel index number or channel name. part: int or None The 0-based enumeration of a True part to return. This has an effect whether or not the mask or filter is turned on. Raise IndexError i...
2,298
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb): u if enable: SSL_CTX_set_info_callback(self._ctx, func) else: SSL_CTX_set_info_callback(self._ctx, 0)
u''' Enable or disable SSL logging :param True | False enable: Enable or disable SSL logging :param func: Callback function for logging
2,299
def create_sslcert(self, name, common_name, pri, ca): req = {} req.update({"name": name}) req.update({"common_name": common_name}) req.update({"pri": pri}) req.update({"ca": ca}) body = json.dumps(req) url = .format(self.server) return self.__pos...
修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11 Args: name: 证书名称 common_name: 相关域名 pri: 证书私钥 ca: 证书内容 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回dict{certID:...