text
stringlengths
78
104k
score
float64
0
0.18
def import_cvxpy(): """ Try importing the qutip module, log an error if unsuccessful. :return: The cvxpy module if successful or None :rtype: Optional[module] """ global _CVXPY_ERROR_LOGGED try: import cvxpy except ImportError: # pragma no coverage cvxpy = None ...
0.00409
def is_SYMBOL(token, *symbols): """ Returns True if ALL of the given argument are AST nodes of the given token (e.g. 'BINARY') """ from symbols.symbol_ import Symbol assert all(isinstance(x, Symbol) for x in symbols) for sym in symbols: if sym.token != token: return False ...
0.003003
def hostname(self): """Get the hostname that this connection is associated with""" from six.moves.urllib.parse import urlparse return urlparse(self._base_url).netloc.split(':', 1)[0]
0.009709
def unwrap(self) -> T: """ Returns the success value in the :class:`Result`. Returns: The success value in the :class:`Result`. Raises: ``ValueError`` with the message provided by the error value if the :class:`Result` is a :meth:`Result.Err` value....
0.003155
def debug_text_world(self, text: str, pos: Union[Unit, Point2, Point3], color=None, size: int = 8): """ Draws a text at Point3 position. Don't forget to add 'await self._client.send_debug'. To grab a unit's 3d position, use unit.position3d Usually the Z value of a Point3 is between 8 and 14 (exc...
0.010453
def chgrp(path, group): ''' Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility fea...
0.000756
def initialize(self): """Instantiates the cache area to be ready for updates""" if self.collname not in self.current_kv_names(): r = self.request('post', self.url+"storage/collections/config", headers={'content-type': 'application/jso...
0.007752
def compose(*funcs): """compose a list of functions""" return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)
0.008
def _autodetect_num_gpus(): """Attempt to detect the number of GPUs on this machine. TODO(rkn): This currently assumes Nvidia GPUs and Linux. Returns: The number of GPUs if any were detected, otherwise 0. """ proc_gpus_path = "/proc/driver/nvidia/gpus" if os.path.isdir(proc_gpus_path):...
0.002632
def _setup_output_metrics(self, engine): """Helper method to setup metrics to log """ metrics = {} if self.metric_names is not None: for name in self.metric_names: if name not in engine.state.metrics: warnings.warn("Provided metric name '{}...
0.004635
def clear_file_cache(filename=None): """Clear the file cache. If no filename is given clear it entirely. if a filename is given, clear just that filename.""" global file_cache, file2file_remap, file2file_remap_lines if filename is not None: if filename in file_cache: del file_cache[f...
0.002141
def _get_timestamp(self): """Get modification timestamp from rec file.""" filename_date = _find_date(os.path.basename(self._path)) if filename_date: return filename_date
0.009756
def _all_datatable_data(self): """ Returns ------- A list of tuples representing rows from all columns of the datatable, sorted accordingly. """ dtbl = self.datatable objs = object_session(self) imcols = [dtbl.c.indx, dtbl.c.final, dtbl.c....
0.006452
def handle_exception(self, e, request=None): """ Handle code exception. :return response: Http response """ if isinstance(e, HttpError): response = SerializedHttpResponse(e.content, status=e.status) return self.emit( response, request=request, em...
0.002384
def get_gpbar(ebar, gbar, v, C, scale_high): r"""Function to numerically determine the hypercharge gauge coupling in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients.""" if C['phiWB'] == 0: # this is the trivial case gpbar = ebar * gbar / sqrt(gbar**2 - ebar**2) else: # if epsilon !...
0.002608
def complete(self, text, line=None, cursor_pos=None): """Return the completed text and a list of completions. Parameters ---------- text : string A string of text to be completed on. It can be given as empty and instead a line/position pair are given. In ...
0.001296
def clean(self, tool): """ Clean a project """ tools = self._validate_tools(tool) if tools == -1: return -1 for current_tool in tools: # We get the export dict formed, then use it for cleaning self._fill_export_dict(current_tool) path = s...
0.003891
def minimize_best_n(Members): ''' Orders population members from lowest fitness to highest fitness Args: Members (list): list of PyGenetics Member objects Returns: lsit: ordered lsit of Members, from highest fitness to lowest fitness ''' return(list(reversed(sorted( Me...
0.002667
def sort_basis(basis, use_copy=True): """ Sorts all the information in a basis set into a standard order If use_copy is True, the input basis set is not modified. """ if use_copy: basis = copy.deepcopy(basis) for k, el in basis['elements'].items(): if 'electron_shells' in el: ...
0.001828
def set_password(name, password): ''' Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext pa...
0.00101
def fit_sparse_one_step(model_matrix, response, model, model_coefficients_start, tolerance, l1_regularizer, l2_regularizer=None, maximum_full_sweeps=Non...
0.001818
async def deleteallreactions(self, ctx): """Removes a reaction""" data = self.config.get(ctx.message.server.id, {}) if data: await self.config.put(ctx.message.server.id, {}) await self.bot.responses.success(message="All reactions have been deleted.") else: ...
0.01005
def path_parts(path): """Split path into container, object. :param path: Path to resource (including container). :type path: `string` :return: Container, storage object tuple. :rtype: `tuple` of `string`, `string` """ path = path if path is not None else '' container_path = object_pat...
0.001923
def figure(key=None, fig=None, **kwargs): """Creates figures and switches between figures. If a ``bqplot.Figure`` object is provided via the fig optional argument, this figure becomes the current context figure. Otherwise: - If no key is provided, a new empty context figure is created. - If a...
0.000434
def read_data(self, **kwargs): """ get the data from the service as the pocket service does not have any date in its API linked to the note, add the triggered date to the dict data thus the service will be triggered when data will be found ...
0.002999
def transform(self, X): """Select categorical features and transform them using OneHotEncoder. Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ...
0.005981
def put_attachment(self, id, filename, file, content_type, include_online=False): """Upload an attachment to the Xero object (from file object).""" return self.put_attachment_data(id, filename, file.read(), content_type, include_online=include_online)
0.014981
def star(self, **args): ''' star any gist by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user...
0.038585
def upsert(self, insert_index, val, fn=None): """Inserts or updates an existing index within the vector. Args: - insert_index (int): The index at which the element should be inserted. - val (int|float): The value to be inserted into the vector. - fn (...
0.003119
def system_monitor_SFM_threshold_down_threshold(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") SFM = ET.SubElement(system_monitor, "SFM") ...
0.005137
def check_trademark_symbol(text): """Use the trademark symbol instead of (TM).""" err = "typography.symbols.trademark" msg = u"(TM) is a goofy alphabetic approximation, use the symbol ™." regex = "\(TM\)" return existence_check( text, [regex], err, msg, max_errors=3, require_padding=False)
0.009404
def parse_dos_time(stamp): """Parse standard 32-bit DOS timestamp. """ sec, stamp = stamp & 0x1F, stamp >> 5 mn, stamp = stamp & 0x3F, stamp >> 6 hr, stamp = stamp & 0x1F, stamp >> 5 day, stamp = stamp & 0x1F, stamp >> 5 mon, stamp = stamp & 0x0F, stamp >> 4 yr = (stamp & 0x7F) + 1980 ...
0.002762
def bind(self, study, **kwargs): # @UnusedVariable """ Returns a copy of the AcquiredSpec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__) """ if self.d...
0.002252
def ParseReportDescriptor(rd, desc): """Parse the binary report descriptor. Parse the binary report descriptor into a DeviceDescriptor object. Args: rd: The binary report descriptor desc: The DeviceDescriptor object to update with the results from parsing the descriptor. Returns: None "...
0.008646
def on(self, image): """ Project polygons from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the polygons are to be projected. May also simply be that new image's shape tuple. Returns -...
0.002849
def _exit(self, status_code): """Properly kill Python process including zombie threads.""" # If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func =...
0.004926
def PushTask(self, task): """Pushes a task onto the heap. Args: task (Task): task. Raises: ValueError: if the size of the storage file is not set in the task. """ storage_file_size = getattr(task, 'storage_file_size', None) if not storage_file_size: raise ValueError('Task sto...
0.006231
def pandoc_version(): """Pandoc's version number""" version = pandoc(u'--version').splitlines()[0].split()[1] if parse_version(version) < parse_version('2.7.2'): raise PandocError('Please install pandoc>=2.7.2 (found version {})'.format(version)) return version
0.006993
def _read_para_cert(self, code, cbit, clen, *, desc, length, version): """Read HIP CERT parameter. Structure of HIP CERT parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
0.000883
def eigenvector_sensitivity(T, k, j, right=True): r"""Sensitivity matrix of a selected eigenvector element. Parameters ---------- T : (M, M) ndarray Transition matrix (stochastic matrix). k : int Eigenvector index j : int Element index right : bool If True co...
0.003695
def calculate(self, T, method): r'''Method to calculate surface tension of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at whi...
0.001815
def clean_recipe_build(self, args): """Deletes the build files of the given recipe. This is intended for debug purposes. You may experience strange behaviour or problems with some recipes if their build has made unexpected state changes. If this happens, run clean_builds, or att...
0.003247
def execute_cast_timestamp_to_timestamp(op, data, type, **kwargs): """Cast timestamps to other timestamps including timezone if necessary""" input_timezone = data.tz target_timezone = type.timezone if input_timezone == target_timezone: return data if input_timezone is None or target_timezo...
0.002353
def clicks_platforms(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the browser platforms used to open your emails. This is only recorded when Link Tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/clicks/platforms", tag=tag, f...
0.008523
def start(instance_id, call=None): ''' Start an instance. CLI Examples: .. code-block:: bash salt-cloud -a start i-2f733r5n ''' if call != 'action': raise SaltCloudSystemExit( 'The stop action must be called with -a or --action.' ) log.info('Starting i...
0.001792
def is_unicode_string(string): """ Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool """ if string is None: ...
0.002364
def load_waveforms_from_file(path_to_waveforms): """ Waveforms must be: - in a .csv or .dat file - each row is a waveform, values comma separated - each waveform is preprocessed -- aligned to core bounce -- all have same sampling frequencies -- all have same number of time s...
0.004098
def text_input(*args, **kwargs): ''' Get multi-line text input as a strong from a textarea form element. ''' text_input = wtforms.TextAreaField(*args, **kwargs) text_input.input_type = 'text' return text_input
0.004292
def get_file(self, index, doc_type, id=None): """ Return the filename and memory data stream """ data = self.get(index, doc_type, id) return data['_name'], base64.standard_b64decode(data['content'])
0.008403
def lt(self, value): """Construct a less than (``<``) filter. :param value: Filter value :return: :class:`filters.Field <filters.Field>` object :rtype: filters.Field """ self.op = '<' self.negate_op = '>=' self.value = self._value(value) return se...
0.006211
def set_role(username, role): ''' Assign role to username .. code-block:: bash salt '*' onyx.cmd set_role username=daniel role=vdc-admin ''' try: sendline('config terminal') role_line = 'username {0} role {1}'.format(username, role) ret = sendline(role_line) ...
0.001887
def _has_level_handler(logger): """Check if there is a handler in the logging chain that will handle the given logger's effective level. """ level = logger.getEffectiveLevel() current = logger while current: if any(handler.level <= level for handler in current.handlers): ret...
0.002309
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) if isinstance(x, dict): return {k: nested_map(x[k], f) for k in x} retu...
0.018349
def plot_vec(axis, step, var): """Plot vector field. Args: axis (:class:`matplotlib.axes.Axes`): the axis handler of an existing matplotlib figure where the vector field should be plotted. step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData insta...
0.00104
def list_campaigns(self, **kwargs): """List all update campaigns. :param int limit: number of campaigns to retrieve :param str order: sort direction of campaigns when ordered by creation time (desc|asc) :param str after: get campaigns after given campaign ID :param dict filters:...
0.005642
def rm_files(path, extension): """ Remove all files in the given directory with the given extension :param str path: Directory :param str extension: File type to remove :return none: """ files = list_files(extension, path) for file in files: if file.endswith(extension): ...
0.002703
def update_fields(self, updates): """ Update the value for a field(s) in the listitem :param update: A dict of {'field name': newvalue} """ for field in updates: if self._valid_field(field): self._track_changes.add(field) else: ...
0.006711
def cols_(self) -> pd.DataFrame: """ Returns a dataframe with columns info :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.cols_()`` """ try: s = self.df.iloc[0] df = pd.DataFrame(s) df = df.rename(columns={0: ...
0.003247
def build_composite( self, format_string, param_dict=None, composites=None, attr_getter=None ): """ .. note:: deprecated in 3.3 use safe_format(). Build a composite output using a format string. Takes a format_string and treats it the same way as ``safe_format()...
0.004098
def isDriver(self): """ Determines if the current L{PE} instance is a driver (.sys) file. @rtype: bool @return: C{True} if the current L{PE} instance is a driver. Otherwise, returns C{False}. """ modules = [] imports = self.ntHeaders.optionalHeader.dataDi...
0.011327
def score(self, X, y, sample_weight=None): """Returns the mean accuracy on the given test data and labels. NOTE: In the condition of sklearn.svm.SVC with precomputed kernel when the kernel matrix is computed portion by portion, the function will ignore the first input argument X. ...
0.001228
def prep_system(run_info_yaml, bcbio_system=None): """Prepare system configuration information from an input configuration file. This does the work of parsing the system input file and setting up directories for use in 'organize'. """ work_dir = os.getcwd() config, config_file = config_utils.lo...
0.008977
def business_hours_schedule_holiday_delete(self, schedule_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/schedules#delete-a-holiday" api_path = "/api/v2/business_hours/schedules/{schedule_id}/holidays/{id}.json" api_path = api_path.format(schedule_id=schedule_id, id=id) ...
0.010582
def salience(self, salience): """Activation salience value.""" lib.EnvSetActivationSalience(self._env, self._act, salience)
0.014388
def import_milestone(self, name, estimated_start, estimated_finish, **attrs): """ Import a Milestone and returns a :class:`Milestone` object. :param name: name of the :class:`Milestone` :param estimated_start: estimated start time of the ...
0.004412
def conf_sets(self): '''The dictionary of configuration sets in this component, if any.''' with self._mutex: if not self._conf_sets: self._parse_configuration() return self._conf_sets
0.008511
def open(self, url): """ Open a document at the specified url. @param url: A document URL. @type url: str @return: A file pointer to the document. @rtype: StringIO """ protocol, location = self.split(url) if protocol == self.protocol: r...
0.005222
def _lift(self, data, bytes_offset=None, max_bytes=None, max_inst=None, opt_level=1, traceflags=None, allow_arch_optimizations=None, strict_block_end=None, skip_stmts=False, collec...
0.009611
def select_by_visible_text(self, text): """ Performs search of selected item from Web List @params text - string visible text """ xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text)) opts = self.find_elements_by_xpath(xpath) matched = F...
0.004243
def _setup(self, lines): '''setup required adding content from the host to the rootfs, so we try to capture with with ADD. ''' bot.warning('SETUP is error prone, please check output.') for line in lines: # For all lines, replace rootfs with actual root / ...
0.003425
def read(self, sig) -> Value: """ Read value from signal or interface """ try: v = sig._val except AttributeError: v = sig._sigInside._val return v.clone()
0.008772
def val(self): """ The ``<c:val>`` XML for this series, as an oxml element. """ xml = self._val_tmpl.format(**{ 'nsdecls': ' %s' % nsdecls('c'), 'values_ref': self._series.values_ref, 'number_format': self._series.number_format, 'v...
0.004535
def cat_pts(self): """ Return a sequence representing the `c:pt` elements under the `c:cat` element of the first series in this xChart element. A category having no value will have no corresponding `c:pt` element; |None| will appear in that position in such cases. Items appear in...
0.002628
def xlsw_write_row(ws, row_idx, row, fmt=None): """ ws: row_idx: row number row: a list, data to write fmt: format for cell """ for col_idx in range(len(row)): ws.write(row_idx, col_idx, row[col_idx], fmt) row_idx += 1 return row_idx
0.00361
def result_report_parameters(self): """Report metric parameters Returns ------- str result report in string format """ output = self.ui.data(field='Tags', value=len(self.tag_label_list)) + '\n' output += self.ui.data(field='Evaluated units', value=i...
0.010667
def fetch_items(self): """ Fetch items Performs a query to retrieve items based on current query and pagination settings. """ offset = self.per_page * (self.page - 1) items = self._query.limit(self.per_page).offset(offset).all() return items
0.006557
def queryBuilderWidget( self ): """ Returns the query builder widget instance that this widget is \ associated with. :return <XQueryBuilderWidget> """ from projexui.widgets.xquerybuilderwidget import XQueryBuilderWidget builder = self.parent(...
0.019231
def inner(self, x1, x2): """Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float or complex The inner...
0.002407
def match_abstract_str(cls): """ For a given abstract or match rule meta-class returns a nice string representation for the body. """ def r(s): if s.root: if s in visited or s.rule_name in ALL_TYPE_NAMES or \ (hasattr(s, '_tx_class') and s...
0.000583
def click_at_coordinates(self, x, y): """ Click at (x,y) coordinates. """ self.device.click(int(x), int(y))
0.014388
def set_decade_lims(axis=None,direction=None): r''' Set limits the the floor/ceil values in terms of decades. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. **direction** ([``None``] | ``'x'`` | ``'y'``) Limit the application to a certain direction (default: b...
0.024185
def multi_index(idx, dim): """ Single to multi-index using graded reverse lexicographical notation. Parameters ---------- idx : int Index in interger notation dim : int The number of dimensions in the multi-index notation Returns ------- out : tuple Multi-in...
0.000972
def send(self, from_pid, to_pid, method, body=None): """Send a message method from one pid to another with an optional body. Note: It is more idiomatic to send directly from a bound process rather than calling send on the context. If the destination pid is on the same context, the Context may skip the...
0.006322
def _generate_perfect_bst(height): """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_...
0.002625
def fade_out(self, duration=3, group=0): """Turns off the light by gradually fading it out. The optional `duration` parameter allows for control of the fade out duration (in seconds)""" self.on(group) super(WhiteLight, self).fade_out(duration, group=group) self.off(group)
0.00625
def get_nodes(self): """ Returns the View nodes. :return: View nodes. :rtype: list """ return [node for node in foundations.walkers.nodes_walker(self.model().root_node)]
0.013699
def pad_with_zeros(logits, labels): """Pad labels on the length dimension to match logits length.""" with tf.name_scope("pad_with_zeros", values=[logits, labels]): logits, labels = pad_to_same_length(logits, labels) if len(labels.shape) == 3: # 2-d labels. logits, labels = pad_to_same_length(logits, ...
0.01108
def locator(self, value): """Update the locator, and trigger a latitude and longitude update. Args: value (str): New Maidenhead locator string """ self._locator = value self._latitude, self._longitude = utils.from_grid_locator(value)
0.006993
def squid_to_guid(squid): ''' Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID ''' squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = ...
0.002625
def phaseq(et, target, illmn, obsrvr, abcorr): """ Compute the apparent phase angle for a target, observer, illuminator set of ephemeris objects. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/phaseq_c.html :param et: Ephemeris seconds past J2000 TDB. :type et: float :param target...
0.001151
async def get_participant(self, p_id: int, force_update=False) -> Participant: """ get a participant by its id |methcoro| Args: p_id: participant id force_update (dfault=False): True to force an update to the Challonge API Returns: Participant: None...
0.005042
def limit(self, n, skip=None): """ Limit the result set. However when the query set already has limit field before, this would raise an exception :Parameters: - n : The maximum number of rows returned - skip: how many rows to skip :Return: a new QuerySet object so...
0.004983
def get_instance(self, payload): """ Build an instance of TaskInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task.TaskInstance :rtype: twilio.rest.taskrouter.v1.workspace.task.TaskInstance """ return Tas...
0.007463
def market(self, accountID, **kwargs): """ Shortcut to create a Market Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a MarketOrderRequest Returns: v20.response.Response containing the results from submit...
0.004274
def create(provider, names, opts=None, **kwargs): ''' Create an instance using Salt Cloud CLI Example: .. code-block:: bash salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True ''' c...
0.004228
def mirror_to_local_no_recursion(self, path_from, path_to, log_files=False): """Mirror a directory without descending into directories. Return a list of subdirectory names (do not include full path). We will unlink existing files without determining if the...
0.008039
def wrap(self, word, width, hyphen='-'): """ Return the longest possible first part and the last part of the hyphenated word. The first part has the hyphen already attached. Returns None, if there is no hyphenation point before width, or if the word could not be hyphenated. ...
0.004264
def is_all_field_none(self): """ :rtype: bool """ if self._BunqMeTab is not None: return False if self._BunqMeTabResultResponse is not None: return False if self._BunqMeFundraiserResult is not None: return False if self._Car...
0.000919
def put_overlay(self, overlay_name, overlay): """Store the overlay.""" logger.debug("Putting overlay: {}".format(overlay_name)) key = self.get_overlay_key(overlay_name) text = json.dumps(overlay, indent=2) self.put_text(key, text)
0.007407
def _handle_tag_scriptlimits(self): """Handle the ScriptLimits tag.""" obj = _make_object("ScriptLimits") obj.MaxRecursionDepth = unpack_ui16(self._src) obj.ScriptTimeoutSeconds = unpack_ui16(self._src) return obj
0.007905