Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
337,100
def _attach_inline_policy(self, username, policy_document): response = self.client.put_user_policy( UserName=username, PolicyName="threatresponse-temporal-key-revocation", PolicyDocument=policy_document ) logger.info( .format(...
Attaches the policy to the user
337,101
def process_like(proc): newproc = copy.deepcopy(proc) newproc.creation_date = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.localtime()) return newproc
Make an exact clone of a process, including state and all subprocesses. The creation date is updated. :param proc: process :type proc: :class:`~climlab.process.process.Process` :return: new process identical to the given process :rtype: :class:`~climlab.process.process.Proces...
337,102
def eval(expr, parser=, engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False): from pandas.core.computation.expr import Expr inplace = validate_bool_kwarg(inplace, "inplace") if isinstance(expr, str): _check_expressi...
Evaluate a Python expression as a string using various backends. The following arithmetic operations are supported: ``+``, ``-``, ``*``, ``/``, ``**``, ``%``, ``//`` (python engine only) along with the following boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not). Additionally, the ``'pandas'`...
337,103
def progress(msg, *args): progress.prev_message = text
Show current progress message to stderr. This function will remember the previous message so that next time, it will clear the previous message before showing next one.
337,104
def get_single_value(value): if not all_elements_equal(value): raise ValueError() if is_scalar(value): return value return value.item(0)
Get a single value out of the given value. This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this function we return a single number from the input value. Args: value (ndarray or number): a numpy array or a single number. Returns: number: a s...
337,105
def _copy_sources_to_generated_destination(self): files = [] for key in FILES_EXTENSIONS.keys(): if type(self.project[][key]) is dict: for k,v in self.project[][key].items(): files.extend(v) elif type(self.project[][key]) is list: ...
Copies all project files to specified directory - generated dir
337,106
def fixup_namespace_packages(path_item, parent=None): _imp.acquire_lock() try: for package in _namespace_packages.get(parent, ()): subpath = _handle_ns(package, path_item) if subpath: fixup_namespace_packages(subpath, package) finally: _imp.releas...
Ensure that previously-declared namespace packages include path_item
337,107
def _heartbeat(self): if self.handler is not None: self.handler.send_pack(proto.HEARTBEAT) else: self.stop_heartbeat()
Heartbeat callback
337,108
def flow(self)->FlowField: "Access the flow-field grid after applying queued affine transforms." if self._flow is None: self._flow = _affine_grid(self.shape) if self._affine_mat is not None: self._flow = _affine_mult(self._flow,self._affine_mat) self._affine_m...
Access the flow-field grid after applying queued affine transforms.
337,109
def __snake_case(self, descriptor): newdict = {} for i, (k, v) in enumerate(descriptor.items()): newkey = "" for j, c in enumerate(k): if c.isupper(): if len(newkey) != 0: newkey += newkey +...
Utility method to convert camelcase to snake :param descriptor: The dictionary to convert
337,110
def by_command(extractor, prefix=(,), separator=, pass_args=False): if not isinstance(prefix, (tuple, list)): prefix = (prefix,) def f(msg): text = extractor(msg) for px in prefix: if text.startswith(px): chunks = text[len(px):].split(separator) ...
:param extractor: a function that takes one argument (the message) and returns a portion of message to be interpreted. To extract the text of a chat message, use ``lambda msg: msg['text']``. :param prefix: a list of special characters expected to indicate the head of a command. ...
337,111
def is_file(self): try: return S_ISREG(self.stat().st_mode) except OSError as e: if e.errno not in (ENOENT, ENOTDIR): raise return False
Whether this path is a regular file (also True for symlinks pointing to regular files).
337,112
async def play_tone(self, command): pin = int(command[0]) if command[1] == "TONE_TONE": tone_command = Constants.TONE_TONE else: tone_command = Constants.TONE_NO_TONE frequency = int(command[2]) duration = int(command[3]) await self.core.p...
This method controls a piezo device to play a tone. It is a FirmataPlus feature. Tone command is TONE_TONE to play, TONE_NO_TONE to stop playing. :param command: {"method": "play_tone", "params": [PIN, TONE_COMMAND, FREQUENCY(Hz), DURATION(MS)]} :returns:No return message.
337,113
def diff_jid(jid, config=): * pre_snapshot, post_snapshot = _get_jid_snapshots(jid, config=config) return diff(config, num_pre=pre_snapshot, num_post=post_snapshot)
Returns the changes applied by a `jid` jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.diff_jid jid=20160607130930720112
337,114
def get_all_topics(region=None, key=None, keyid=None, profile=None): cache_key = _cache_get_key() try: return __context__[cache_key] except KeyError: pass conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) __context__[cache_key] = {} topics = conn.g...
Returns a list of the all topics.. CLI example:: salt myminion boto_sns.get_all_topics
337,115
def destination(self) -> Optional[Union[str, Set[str]]]: if "destination" not in self.data.columns: return None tmp = set(self.data.destination) if len(tmp) == 1: return tmp.pop() logging.warn("Several destinations for one flight, consider splitting") ...
Returns the unique destination value(s) of the DataFrame. The destination airport is mostly represented as a ICAO or a IATA code.
337,116
def create(self): super().create() log.info(.format(name=self._name, id=self._id))
Creates this hub.
337,117
def save_tensorflow(self, inputs, path, byte_order="little_endian", data_format="nhwc"): callBigDlFunc(self.bigdl_type, "saveTF", self.value, inputs, path, byte_order, data_format)
Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names and shapes of the placeholders. BigDL model doesn't have such information. The order of the placehold...
337,118
def reqs_txt(self): role_lines = "" for role in sorted(self.report["roles"]): name = utils.normalize_role(role, self.config) galaxy_name = "{0}.{1}".format(self.config["scm_user"], name) version_path = os.path.join(self.roles_path, role, "VERSION") ...
Export a requirements file in txt format.
337,119
def mahalanobis_norm(self, dx): return sqrt(sum((self.D**-1. * np.dot(self.B.T, dx / self.sigma_vec))**2)) / self.sigma
compute the Mahalanobis norm that is induced by the adapted sample distribution, covariance matrix ``C`` times ``sigma**2``, including ``sigma_vec``. The expected Mahalanobis distance to the sample mean is about ``sqrt(dimension)``. Argument -------- A *genotype* differe...
337,120
def StartingAgeEnum(ctx): return Enum( ctx, what=-2, unset=-1, dark=0, feudal=1, castle=2, imperial=3, postimperial=4, dmpostimperial=6 )
Starting Age Enumeration.
337,121
def _check_if_both_have_same_parameters(self, other_trajectory, ignore_data, consecutive_merge): if not isinstance(other_trajectory, Trajectory): raise TypeError( % str(type(other_trajectory))) if self._store...
Checks if two trajectories live in the same space and can be merged.
337,122
def file(self, owner=None, **kwargs): return File(self.tcex, owner=owner, **kwargs)
Create the File TI object. Args: owner: **kwargs: Return:
337,123
def _get_bool_attribute(elem, name, default=False): if name not in elem.attrib: return default else: value = elem.attrib[name].strip().lower() if value in ("true", "1"): return True elif value in ("false", "0"): return False else: ...
! @brief Extract an XML attribute with a boolean value. Supports "true"/"false" or "1"/"0" as the attribute values. Leading and trailing whitespace is stripped, and the comparison is case-insensitive. @param elem ElementTree.Element object. @param name String for the attribute name. @param...
337,124
def decode_html_entities(html): if not html: return html for entity, char in six.iteritems(html_entity_map): html = html.replace(entity, char) return html
Decodes a limited set of HTML entities.
337,125
def _add_notice_to_docstring(doc, no_doc_str, notice): if not doc: lines = [no_doc_str] else: lines = _normalize_docstring(doc).splitlines() notice = [] + notice if len(lines) > 1: if lines[1].strip(): notice.append() lines[1:1] = notice ...
Adds a deprecation notice to a docstring.
337,126
def json(cls, status_code, process): def func(response): ret = None if cls.boolean(status_code)(response): ret = response.json() or {} return process(ret) return func
Callback to validate and extract a JSON object. The returned callback checks a given response for the given status_code using :function:`response_boolean`. On success the response JSON is parsed and returned. Args: status_code(int): The http status code to consider a succe...
337,127
def _transform(comps, trans): logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ mark.strip(components[1]).lower() in [, ] and trans == "o^"...
Transform the given string with transform type trans
337,128
def _unapply_interception(target, ctx=None): if ctx is None: ctx = find_ctx(elt=target) intercepted, old_ctx = get_intercepted(target) if ctx is None and old_ctx is not None: ctx = old_ctx if intercepted is None: raise JoinpointError(.format(target)) ...
Unapply interception on input target in cleaning it. :param routine target: target from where removing an interception function. is_joinpoint(target) must be True. :param ctx: target ctx.
337,129
def unmarkCollapsed( self ): if ( not self.isCollapsed() ): return self._collapsed = False self._storedSizes = None if ( self.orientation() == Qt.Vertical ): self._collapseBefore.setArrowType( Qt.UpArrow ) self._collaps...
Unmarks this splitter as being in a collapsed state, clearing any \ collapsed information.
337,130
def calc_padding(fmt, align): remain = struct.calcsize(fmt) % align if remain == 0: return "" return * (align - remain)
Calculate how many padding bytes needed for ``fmt`` to be aligned to ``align``. Args: fmt (str): :mod:`struct` format. align (int): alignment (2, 4, 8, etc.) Returns: str: padding format (e.g., various number of 'x'). >>> calc_padding('b', 2) 'x' >>> calc_padding('b',...
337,131
def bounding_box(self): cos_angle = np.cos(self.angle) sin_angle = np.sin(self.angle) tan_angle = np.tan(self.angle) t1 = np.arctan(-self.height * tan_angle / self.width) t2 = t1 + np.pi * u.rad dx1 = 0.5 * self.width * cos_angle * ...
The minimal bounding box (`~regions.BoundingBox`) enclosing the exact elliptical region.
337,132
def mayContainTextNodes(node): try: return node.mayContainTextNodes except AttributeError: pass result = True if node.nodeType != Node.ELEMENT_NODE: result = False elif node.namespaceURI != NS[]: result = True elif node.nodeName in [, ,...
Returns True if the passed-in node is probably a text element, or at least one of its descendants is probably a text element. If False is returned, it is guaranteed that the passed-in node has no business having text-based attributes. If True is returned, the passed-in node should not have its text-ba...
337,133
def dataset(self): data = tablib.Dataset() if len(list(self)) == 0: return data first = self[0] data.headers = first.keys() for row in self.all(): row = _reduce_datetimes(row.values()) data.append...
A Tablib Dataset representation of the RecordCollection.
337,134
def write(self, b): if self.closed: raise ValueError() if self.pos + len(b) > self.size: raise EOFError(.format(self.pos + len(b), self.size)) with self.lock: self.f.seek(self.start + self.pos) result = self.f.w...
Same as `file.write()` but for the slice. raises: EOFError if the new seek position is > `self.size`.
337,135
def read_stdin(): if sys.stdin.isatty() and sys.stdout.isatty(): print() return sys.stdin.read()
Read text from stdin, and print a helpful message for ttys.
337,136
def unique(iterable): yielded = set() for i in iterable: if i in yielded: continue yield i yielded.add(i)
Generator yielding each element only once. Note: May consume lots of memory depending on the given iterable.
337,137
def get_arg_descriptions_from_docstring(cls, obj): ret = OrderedDict() name = doc = obj.__doc__ or lines = [s.strip() for s in doc.split()] stanza_first_line_re = cls._get_stanza_first_line_re() for line in lines: m = stanza_first_line_re.match(line) if m and m.group(1) == : ...
Returns an ordered map of arg name -> arg description found in :param: stanzas.
337,138
def get_case24_ieee_rts(): path = os.path.dirname(pylon.__file__) path = os.path.join(path, "test", "data") path = os.path.join(path, "case24_ieee_rts", "case24_ieee_rts.pkl") case = pylon.Case.load(path) for g in case.generators: g.name return case
Returns the 24 bus IEEE Reliability Test System.
337,139
def quaternion_imag(quaternion): return np.array(quaternion[1:4], dtype=np.float64, copy=True)
Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.])
337,140
def netconf_capability_change_changed_by_server_or_user_by_user_session_id(self, **kwargs): config = ET.Element("config") netconf_capability_change = ET.SubElement(config, "netconf-capability-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications") changed_by = ET.SubEle...
Auto Generated Code
337,141
def register_plotter(identifier, module, plotter_name, plotter_cls=None, sorter=True, plot_func=True, import_plotter=None, **kwargs): if plotter_cls is None: if ((import_plotter is None and rcParams[]) or import_plotter): try: ...
Register a :class:`psyplot.plotter.Plotter` for the projects This function registers plotters for the :class:`Project` class to allow a dynamical handling of different plotter classes. Parameters ---------- %(Project._register_plotter.parameters.no_plotter_cls)s sorter: bool, optional ...
337,142
def map_values(self, func): return TDict({k: func(v) for k, v in self.items()})
:param func: :type func: T -> U :rtype: TDict[U] Usage: >>> TDict(k1=1, k2=2, k3=3).map_values(lambda x: x*2) == { ... "k1": 2, ... "k2": 4, ... "k3": 6 ... } True
337,143
def border_pixels( self, grad_sigma=0.5, grad_lower_thresh=0.1, grad_upper_thresh=1.0): boundary_im = np.ones(self.shape) for i in range(1, self.num_segments): label_border_im = self.data.copy() label_border_im[sel...
Returns the pixels on the boundary between all segments, excluding the zero segment. Parameters ---------- grad_sigma : float standard deviation used for gaussian gradient filter grad_lower_thresh : float lower threshold on gradient threshold used to determine th...
337,144
def get_port_channel_detail_output_lacp_aggregator_id(self, **kwargs): config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_detail, "output") lacp = ET.SubEl...
Auto Generated Code
337,145
def write_const_tpl(name, tpl_file, suffix, zn_array=None, shape=None, spatial_reference=None, longnames=False): if shape is None and zn_array is None: raise Exception("must pass either zn_array or shape") elif shape is None: shape = zn_array.shape parnme = [] ...
write a constant (uniform) template file Parameters ---------- name : str the base parameter name tpl_file : str the template file to write - include path zn_array : numpy.ndarray an array used to skip inactive cells Returns ------- df : pandas.DataFrame ...
337,146
def getobjectinfo(self, window_name, object_name): try: obj_info = self._get_object_map(window_name, object_name, wait_for_object=False) except atomac._a11y.ErrorInvalidUIElement: self._windows = {} ...
Get object properties. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_nam...
337,147
def secure(self): verbose() self._id = self.db.insertTarget(self.name, self.path) verbose(.format( str(self), config.CONMAN_PATH )) link(self.real_path, self.vault_path)
Creates a hard link to the target file in the vault directory and saves information about the target file in the database
337,148
def _prepare_for_training(self, records, mini_batch_size=None, job_name=None): super(AmazonAlgorithmEstimatorBase, self)._prepare_for_training(job_name=job_name) feature_dim = None if isinstance(records, list): for record in records: if record.channel == : ...
Set hyperparameters needed for training. Args: * records (:class:`~RecordSet`): The records to train this ``Estimator`` on. * mini_batch_size (int or None): The size of each mini-batch to use when training. If ``None``, a default value will be used. * job_nam...
337,149
def _find_link(inst1, inst2, rel_id, phrase): metaclass1 = get_metaclass(inst1) metaclass2 = get_metaclass(inst2) if isinstance(rel_id, int): rel_id = % rel_id for ass in metaclass1.metamodel.associations: if ass.rel_id != rel_id: continue if (ass.sou...
Find links that correspond to the given arguments.
337,150
def save_data(self, trigger_id, **data): data[] = title, content = super(ServiceTrello, self).save_data(trigger_id, **data) if len(title): t = Trello.objects.get(trigger_id=trigger_id) footer = self.set_card_footer(data, t) ...
let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save statement :rtype: boolean
337,151
def apps(): response = salt.utils.http.query( "{0}/v2/apps".format(_base_url()), decode_type=, decode=True, ) return {: [app[] for app in response[][]]}
Return a list of the currently installed app ids. CLI Example: .. code-block:: bash salt marathon-minion-id marathon.apps
337,152
def _check_for_inception(self, root_dict): for key, value in root_dict.items(): if isinstance(value, dict): root_dict[key] = Response(value) return root_dict
Used to check if there is a dict in a dict
337,153
def add_alias(self, alias): objs = object_session(self) if isinstance(alias, list): raise NotImplementedError elif isinstanceofany(alias, (str, unicode)): a = SymbolAlias(self, alias) self.aliases.append(a) objs.add(a)
Add an alias to a Symbol Parameters ---------- alias : str The alias
337,154
def set_sail(self, angle): angle = float(angle) request = self.boatd.post({: float(angle)}, ) return request.get()
Set the angle of the sail to `angle` degrees :param angle: sail angle :type angle: float between -90 and 90
337,155
def save(self, fname): out = etree.tostring(self.root, xml_declaration=True, standalone=True, pretty_print=True) with open(fname, ) as fid: fid.write(out)
Save figure to a file
337,156
def build_req_and_res(self): req = self.build_req(self, self.headers) res = self.build_res(self._handler) return req, res
Simple method which calls the request and response factories the responder was given, and returns the pair.
337,157
def genH264(infile, outfile, T): x264opts="-x264opts keyint=10:min-keyint=10:bframes=0" h264_dummystream_flavor="-pix_fmt yuv420p -vprofile main" opts="-vcodec h264 "+h264_dummystream_flavor+" "+x264opts+" -fflags +genpts -r 25 -t "+str(T) com="ffmpeg -y -loop 1 -fflags +genpts -r 25 -i "+infile+...
Generate H264 stream Input image, output video file, time in seconds Example: :: genH264("/home/sampsa/python3/tests/lprtest/RealImages/IMG_20170308_093511.jpg","testi.mkv", 10)
337,158
def _split_text(text, width, height, unicode_aware=True): tokens = text.split(" ") result = [] current_line = "" string_len = wcswidth if unicode_aware else len for token in tokens: for i, line_token in enumerate(token.split("\n")): if string_len(current_line + line_tok...
Split text to required dimensions. This will first try to split the text into multiple lines, then put a "..." on the last 3 characters of the last line if this still doesn't fit. :param text: The text to split. :param width: The maximum width for any line. :param height: The maximum height for th...
337,159
def find_output(self, ifo, time): try: lenTime = len(time) except TypeError: outFile = self.find_output_at_time(ifo,time) else: if lenTime == 2: outFile = self.find_output_in_range(ifo,time[0],time[1]...
Returns one File most appropriate at the given time/time range. Return one File that covers the given time, or is most appropriate for the supplied time range. Parameters ----------- ifo : string Name of the ifo (or ifos) that the file should be valid for. ti...
337,160
def setParameter(self, objID, param, value): self._connection._beginMessage(self._cmdSetID, tc.VAR_PARAMETER, objID, 1 + 4 + 1 + 4 + len(param) + 1 + 4 + len(value)) self._connection._string += struct.pack("!Bi", tc.TYPE_COMPOUND, 2) self._connecti...
setParameter(string, string, string) -> string Sets the value of the given parameter to value for the given objID
337,161
def clone_dataset(dataset_id,**kwargs): user_id = int(kwargs.get()) if dataset_id is None: return None dataset = db.DBSession.query(Dataset).filter( Dataset.id==dataset_id).options(joinedload_all()).first() if dataset is None: raise HydraError("Dataset %s does not ex...
Get a single dataset, by ID
337,162
def list_members_without_mfa(profile="github", ignore_cache=False): key = "github.{0}:non_mfa_users".format( _get_config_value(profile, ) ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_v...
List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. v...
337,163
def make_heartbeat(port, path, peer_uid, node_uid, app_id): packet = struct.pack("<BBH", PACKET_FORMAT_VERSION, PACKET_TYPE_HEARTBEAT, port) for string in (path, peer_uid, node_uid, app_id): string_bytes = to_bytes(string) packet += struct.pack("<H", len(string_bytes)) ...
Prepares the heart beat UDP packet Format : Little endian * Kind of beat (1 byte) * Herald HTTP server port (2 bytes) * Herald HTTP servlet path length (2 bytes) * Herald HTTP servlet path (variable, UTF-8) * Peer UID length (2 bytes) * Peer UID (variable, UTF-8) * Node UID length (2 by...
337,164
def populate_request_data(self, request_args): request_args[] = HTTPBasicAuth( self._username, self._password) return request_args
Add the authentication info to the supplied dictionary. We use the `requests.HTTPBasicAuth` class as the `auth` param. Args: `request_args`: The arguments that will be passed to the request. Returns: The updated arguments for the request.
337,165
def get_coinc_def_id(xmldoc, search, coinc_type, create_new = True, description = u""): try: coincdeftable = lsctables.CoincDefTable.get_table(xmldoc) except ValueError: if not create_new: raise coincdeftable = lsctables.New(lsctables.CoincDefTable) xmldoc.childNodes[0].appendChild(coincdeftable...
Wrapper for the get_coinc_def_id() method of the CoincDefiner table class in pycbc_glue.ligolw.lsctables. This wrapper will optionally create a new coinc_definer table in the document if one does not already exist.
337,166
def set_state(task, execution_date, upstream=False, downstream=False, future=False, past=False, state=State.SUCCESS, commit=False, session=None): assert timezone.is_localized(execution_date) assert task.dag is not None dag = task.dag latest_execution_date = dag.latest_execution_date...
Set the state of a task instance and if needed its relatives. Can set state for future tasks (calculated from execution_date) and retroactively for past tasks. Will verify integrity of past dag runs in order to create tasks that did not exist. It will not create dag runs that are missing on the schedule...
337,167
def _build_synset_lookup(imagenet_metadata_file): lines = tf.gfile.FastGFile(imagenet_metadata_file, ).readlines() synset_to_human = {} for l in lines: if l: parts = l.strip().split() assert len(parts) == 2 synset = parts[0] human = parts[1] synset_to_human[synset] = human r...
Build lookup for synset to human-readable label. Args: imagenet_metadata_file: string, path to file containing mapping from synset to human-readable label. Assumes each line of the file looks like: n02119247 black fox n02119359 silver fox n02119477 red fox, Vulpes f...
337,168
def attach_template(self, _template, _key, **unbound_var_values): if _key in unbound_var_values: raise ValueError( % _key) unbound_var_values[_key] = self return _DeferredLayer(self.bookkeeper, _template.as_layer().construct, [], ...
Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer...
337,169
def write_str2file(pathname, astr): fname = pathname fhandle = open(fname, ) fhandle.write(astr) fhandle.close()
writes a string to file
337,170
def sgn(x): x = BigFloat._implicit_convert(x) if is_nan(x): raise ValueError("Cannot take sign of a NaN.") return mpfr.mpfr_sgn(x)
Return the sign of x. Return a positive integer if x > 0, 0 if x == 0, and a negative integer if x < 0. Raise ValueError if x is a NaN. This function is equivalent to cmp(x, 0), but more efficient.
337,171
def __taint_move(self, instr): op0_taint = self.get_operand_taint(instr.operands[0]) self.set_operand_taint(instr.operands[2], op0_taint)
Taint registers move instruction.
337,172
def primes(n): if n==2: return [2] elif n<2: return [] s=list(range(3,n+1,2)) mroot = n ** 0.5 half=(n+1)//2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)//2 s[j]=0 while j<half: s[j]=0 ...
Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/
337,173
def _pipe(obj, func, *args, **kwargs): if isinstance(func, tuple): func, target = func if target in kwargs: msg = % target raise ValueError(msg) kwargs[target] = obj return func(*args, **kwargs) else: return func(obj, *args, **kwargs)
Apply a function ``func`` to object ``obj`` either by passing obj as the first argument to the function or, in the case that the func is a tuple, interpret the first element of the tuple as a function and pass the obj to that function as a keyword argument whose key is the value of the second element of...
337,174
def _getter(self, obj): result = None if self._fget_ is not None: result = self._fget_(obj) if result is None: result = getattr(obj, self._attrname(), self._default_) if isinstance(obj, Schema): obj._getvalue(self, result) ...
Called when the parent element tries to get this property value. :param obj: parent object.
337,175
def sendeof(self): n, byte = self.ptyproc.sendeof() self._log_control(byte)
This sends an EOF to the child. This sends a character which causes the pending parent output buffer to be sent to the waiting child program without waiting for end-of-line. If it is the first character of the line, the read() in the user program returns 0, which signifies end-of-file. T...
337,176
def get_part_specs_by_filter(self, db_name, tbl_name, filter, max_parts): self.send_get_part_specs_by_filter(db_name, tbl_name, filter, max_parts) return self.recv_get_part_specs_by_filter()
Parameters: - db_name - tbl_name - filter - max_parts
337,177
def load_cfg(self): if self.cfg_mode == : with open(self.cfg_file) as opened_file: return json.load(opened_file) else: with open(self.cfg_file) as ymlfile: return yaml.safe_load(ymlfile)
loads our config object accessible via self.cfg
337,178
def handle_args_and_set_context(args): parser = argparse.ArgumentParser() parser.add_argument("env", help=", ".join(EFConfig.ENV_LIST)) parser.add_argument("--sr", help="optional /path/to/service_registry_file.json", default=None) parser.add_argument("--commit", help="Make changes in AWS (dry run if omitted)...
Args: args: the command line args, probably passed from main() as sys.argv[1:] Returns: a populated EFContext object Raises: IOError: if service registry file can't be found or can't be opened RuntimeError: if repo or branch isn't as spec'd in ef_config.EF_REPO and ef_config.EF_REPO_BRANCH Calle...
337,179
def _WriteFile(output_path, name, content): path = os.path.join(output_path, name) with open(path, ) as f: f.write(content) return path
Write given content to a file in a given directory. Args: output_path: The directory to store the file in. name: The name of the file to store the content in. content: The content to write to the file.close Returns: The full path to the written file.
337,180
def get_rudder_scores(self, category): category_percentiles = self._get_term_percentiles_in_category(category) not_category_percentiles = self._get_term_percentiles_not_in_category(category) rudder_scores = self._get_rudder_scores_for_percentile_pair(category_percentiles, ...
Computes Rudder score. Parameters ---------- category : str category name to score Returns ------- np.array
337,181
def select_entry(self, core_element_id, by_cursor=True): for row_num, element_row in enumerate(self.list_store): if element_row[self.ID_STORAGE_ID] == core_element_id: if by_cursor: self.tree_view.set_cursor(row_num) else: ...
Selects the row entry belonging to the given core_element_id by cursor or tree selection
337,182
def azimuth(self, point): return geodetic.azimuth(self.longitude, self.latitude, point.longitude, point.latitude)
Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value in a range ``[0, 360)``. :rtype: float
337,183
def index_sample(self, md5, index_name): generator = self.stream_sample(md5) for row in generator: self.indexer.index_data(row, index_name)
Index a stored sample with the Indexer. Args: md5: the md5 of the sample index_name: the name of the index Returns: Nothing
337,184
def main(): args = parse_args() configure_logging(args.debug) src_path = args.src_path dest_path = args.dest_path old_str1 = + args.old_size old_str2 = + args.old_size new_str = + args.new_size logging.info(, src_path) logging.info(, dest_path) logging.info(, old_str1) ...
Read a directory containing json files for Kibana panels, beautify them and replace size value in aggregations as specified through corresponding params params.
337,185
def read_union(fo, writer_schema, reader_schema=None): index = read_long(fo) if reader_schema: if not isinstance(reader_schema, list): if match_types(writer_schema[index], reader_schema): return read_data(fo, writer_schema[index], reader_schema) els...
A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union.
337,186
def to_human_readable(self, data, label_batch_entries=True, indices=None, sep="\n"): obs = data[0] batch_size = obs.shape[1] result = [] indices = xrange(batch_size) if not indices else indices for b...
Returns a human-readable version of a one-hot encoding of words. Args: data: A tuple with (obs, target). `obs` is a numpy array with one-hot encoding of words. label_batch_entries: bool. Whether to add numerical label before each batch element in the output string. indices: Li...
337,187
def from_csv(cls, filename=None, text=None, dlm=, lexicon=None, points=False, include=None, exclude=None, remap=None, function=None, null=None, ignore...
Load from a CSV file or text.
337,188
def log(wave): r pexdoc.exh.addex( ValueError, "Math domain error", bool((min(wave._dep_vector) <= 0)) ) return _operation(wave, "log", "", np.log)
r""" Return the natural logarithm of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for peng.wave_fu...
337,189
def trigger_dag(args): log = LoggingMixin().log try: message = api_client.trigger_dag(dag_id=args.dag_id, run_id=args.run_id, conf=args.conf, execution_date=args.exec_date) ...
Creates a dag run for the specified dag :param args: :return:
337,190
def load_resource(resource_url: str, forceupdate: bool = False): log.info(f"Loading resource {resource_url}") try: fo = bel.utils.download_file(resource_url) if not fo: log.error(f"Could not download and open file {resource_url}") return "Failed to downlo...
Load BEL Resource file Forceupdate will create a new index in Elasticsearch regardless of whether an index with the resource version already exists. Args: resource_url: URL from which to download the resource to load into the BEL API forceupdate: force full update - e.g. don't leave Elasti...
337,191
def exists(self, **kwargs): requests_params requests_params = self._handle_requests_params(kwargs) self._check_load_parameters(**kwargs) kwargs[] = False session = self._meta_data[]._meta_data[] base_uri = self._meta_data[]._meta_data[] partition = kwargs.pop() ...
Check for the existence of the named object on the BIG-IP Override of resource.Resource exists() to build proper URI unique to service resources. Sends an HTTP GET to the URI of the named object and if it fails with a :exc:~requests.HTTPError` exception it checks the exception for ...
337,192
def hue(self, img1, img2): import colorsys p1 = list(img1.getdata()) p2 = list(img2.getdata()) for i in range(len(p1)): r1, g1, b1, a1 = p1[i] r1 = r1 / 255.0 g1 = g1 / 255.0 b1 = b1 / 255.0 h1,...
Applies the hue blend mode. Hues image img1 with image img2. The hue filter replaces the hues of pixels in img1 with the hues of pixels in img2. Returns a composite image with the alpha channel retained.
337,193
def add_vector(self, vector): self._num_docs+=1 max_id, veclen = self._mmw.write_vector(self._num_docs, vector) self._num_terms = max(self._num_terms, 1 + max_id) self._num_nnz += veclen
\ Writes the provided vector to the matrix. `vector` An iterable of ``(word-id, word-frequency)`` tuples
337,194
def clear_canvas(self): self.fig = None self.fmt = None self._qpix_buffer = [] self.repaint()
Clear the figure that was painted on the widget.
337,195
def get_userid_presence(self, user_id: str) -> UserPresence: return self._userid_to_presence.get(user_id, UserPresence.UNKNOWN)
Return the current presence state of ``user_id``.
337,196
def modifiers(self): if not self.get_objects_by_type(): for index in range(int(self.get_attribute())): XenaModifier(self, index=.format(self.index, index)).get() return {s.id: s for s in self.get_objects_by_type()}
:return: dictionary {index: object} of standard modifiers.
337,197
def find_associated_with_address(self, instance): objects = [] objects += list(Project.objects.filter(address=instance)) objects += list(Organization.objects.filter(address=instance)) return objects
Returns list with projects and organizations associated with given address
337,198
def minus(repo_list_a, repo_list_b): included = defaultdict(lambda: False) for repo in repo_list_b: included[repo.full_name] = True a_minus_b = list() for repo in repo_list_a: if not included[repo.full_name]: included[repo.full_name] = T...
Method to create a list of repositories such that the repository belongs to repo list a but not repo list b. In an ideal scenario we should be able to do this by set(a) - set(b) but as GithubRepositories have shown that set() on them is not reliable resort to this until it is all sorted...
337,199
def runprofile(mainfunction, output, timeout = 0, calibrate=False): if noprofiler == True: print() return False def _profile(): profile.run(mainfunction, output) print(); sys.stdout.flush(); if calibrate: print(); sys.stdout.flush(); cval = ...
Run the functions profiler and save the result If timeout is greater than 0, the profile will automatically stops after timeout seconds