text
stringlengths
78
104k
score
float64
0
0.18
def on_api_error_15(self, request): """ 15. Access denied - due to scope """ logger.error('Authorization failed. Access token will be dropped') self.access_token = self.get_access_token() return self.send(request)
0.007326
def column_describe(table_name, col_name): """ Return summary statistics of a column as JSON. Uses Pandas' "split" JSON format. """ col_desc = orca.get_table(table_name).get_column(col_name).describe() return ( col_desc.to_json(orient='split'), 200, {'Content-Type': 'app...
0.002976
def populations_diff_coeff(particles, populations): """Diffusion coefficients of the two specified populations. """ D_counts = particles.diffusion_coeff_counts if len(D_counts) == 1: pop_sizes = [pop.stop - pop.start for pop in populations] assert D_counts[0][1] >= sum(pop_sizes) ...
0.001484
def generate(variables, steps, final_outputs): """Generate all of the components of a CWL workflow from input steps. file_vs and std_vs are the list of world variables, split into those that reference files (and need declaration at each step) and those that don't and can be safely passed to each step. ...
0.005292
def _update_table_cache(self): """Clears and updates the table cache to be in sync with self""" self._table_cache.clear() for sel, tab, val in self: try: self._table_cache[tab].append((sel, val)) except KeyError: self._table_cache[tab] = [...
0.005208
def on_push(self, device): """Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time(): return last_e...
0.007979
def load_header_chain( cls, chain_path ): """ Load the header chain from disk. Each chain element will be a dictionary with: * """ header_parser = BlockHeaderSerializer() chain = [] height = 0 with open(chain_path, "rb") as f: h = SP...
0.017316
def MI_modifyInstance(self, env, modifiedInstance, previousInstance, propertyList, cimClass): # pylint: disable=invalid-name """Modify a CIM instance Implements the ...
0.007678
def _align_intervals(int_hier, lab_hier, t_min=0.0, t_max=None): '''Align a hierarchical annotation to span a fixed start and end time. Parameters ---------- int_hier : list of list of intervals lab_hier : list of list of str Hierarchical segment annotations, encoded as a list of li...
0.000899
def parseelement(elem): ''' Convert the content of an element into more ElementTree structures. We do this because sometimes we want to set xml as the content of an element. ''' xml = '<%(tag)s>%(content)s</%(tag)s>' % {'tag' : elem.tag, 'content' : elem.text} et = etree.fromstring(xml) repl...
0.014706
def start_watcher(conf, watcher_plugin_class, health_plugin_class, iterations=None, sleep_time=1): """ Start watcher loop, listening for config changes or failed hosts. Also starts the various service threads. VPC router watches for any changes in the config and updates/adds/deletes ...
0.00111
def d_x(data, axis, boundary='forward-backward'): ''' Calculates a second-order centered finite difference of data along the specified axis. Parameters ---------- data : ndarray Data on which we are taking a derivative. axis : int Index of the data array on which to take the difference. boundary : string,...
0.00048
def readAsync(self, fileName, callback, **kwargs): """ Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re...
0.001563
def _match_datetime_pattern(self, tokens): """ Match the datetime pattern at the beginning of the token list. There are several formats that this method needs to understand and distinguish between (see MongoDB's SERVER-7965): ctime-pre2.4 Wed Dec 31 19:00:00 ctime ...
0.000972
def _render_content(self, content, **settings): """ Perform widget rendering, but do not print anything. """ bar_len = int(settings[self.SETTING_BAR_WIDTH]) if not bar_len: bar_len = TERMINAL_WIDTH - 10 percent = content progress = "" progress ...
0.004405
def openXmlDocument(path=None, file_=None, data=None, url=None, mime_type=None): """**Factory function** Will guess what document type is best suited and return the appropriate document type. User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter. :param path: file path in the...
0.003514
async def run(self, *args, data): """ run the function you want """ cmd = self._get(data.text) try: if cmd is not None: command = self[cmd](*args, data=data) return await peony.utils.execute(command) except: fmt = "Error occurred ...
0.007407
def _get_script(self): """Returns fixed commands script. If `settings.repeat` is `True`, appends command with second attempt of running fuck in case fixed command fails again. """ if settings.repeat: repeat_fuck = '{} --repeat {}--force-command {}'.format( ...
0.003738
def _bse_cli_list_roles(args): '''Handles the list-roles subcommand''' all_roles = api.get_roles() if args.no_description: liststr = all_roles.keys() else: liststr = format_columns(all_roles.items()) return '\n'.join(liststr)
0.003802
def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger): ''' This function takes a series of sequences and creates a big BWT by merging the smaller ones Mostly a test function, no real purpose to the tool as of now @param seqArray - a list of '$'-terminated strings to be placed into the arr...
0.012838
def _get_front_idxs_from_id(fronts, id): """ Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front. """ if id == -1: # This is the only special case. # -1 is the index of the catch-all final column offset front. f...
0.003419
def ToCsv(self, columns_order=None, order_by=(), separator=","): """Writes the data table as a CSV string. Output is encoded in UTF-8 because the Python "csv" module can't handle Unicode properly according to its documentation. Args: columns_order: Optional. Specifies the order of columns in the...
0.006441
def required(col_name, arg, dm, df, *args): """ Col_name is required in df.columns. Return error message if not. """ if col_name in df.columns: return None else: return '"{}" column is required'.format(col_name)
0.003984
def checktype(self, elt, ps): '''See if the type of the "elt" element is what we're looking for. Return the element's type. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. ''' typeName = _find_type(elt) if typeName is N...
0.012218
def main(): """Start an interactive `MockupDB`. Use like ``python -m mockupdb``. """ from optparse import OptionParser parser = OptionParser('Start mock MongoDB server') parser.add_option('-p', '--port', dest='port', default=27017, help='port on which mock mongod listens')...
0.00114
def prox_yline(y, step): """Projection onto line in y""" if not np.isscalar(y): y= y[0] if y > -0.75: return np.array([-0.75]) else: return np.array([y])
0.010363
def make_outpoint(tx_id_le, index, tree=None): ''' byte-like, int, int -> Outpoint ''' if 'decred' in riemann.get_current_network_name(): return tx.DecredOutpoint(tx_id=tx_id_le, index=utils.i2le_padded(index, 4), tree=utils.i2le_...
0.002309
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
0.015625
def goback(self,days = 1): """ Go back days 刪除最新天數資料數據 days 代表刪除多少天數(倒退幾天) """ for i in xrange(days): self.raw_data.pop() self.data_date.pop() self.stock_range.pop() self.stock_vol.pop() self.stock_open.pop() self.stock_h.pop() self.stock_l.pop()
0.03481
def trunc(x, context=None): """ Return the next integer towards zero. If the result is not exactly representable, it will be rounded according to the current context. .. note:: This function corresponds to the MPFR function ``mpfr_rint_trunc``, not to ``mpfr_trunc``. """ re...
0.002114
def export_artifacts(self, processed_artifacts, sketch_id): """Upload provided artifacts to specified, or new if non-existent, sketch. Args: processed_artifacts: List of (timeline_name, artifact_path) tuples sketch_id: ID of sketch to append the timeline to Returns: int: ID of sketch. ...
0.005891
def dremove(self, **kwds): """Removes from the object any element that matches the given specification. """ filtered_dr = self.dfilter(**kwds) for item in filtered_dr: self.remove(item) return filtered_dr
0.007576
def save_item(self, item): """Save an object to DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`. :raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met. """ try: self.dynamodb_client.update_item...
0.009259
def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ text = link = escape(link) if is_email: link = 'mailto:%s' % link r...
0.005525
def main(newick): """Main executor of the process_newick template. Parameters ---------- newick : str path to the newick file. """ logger.info("Starting newick file processing") print(newick) tree = dendropy.Tree.get(file=open(newick, 'r'), schema="newick") tree.reroot_...
0.003822
def ssh_directory_for_unit(application_name, user=None): """Return the directory used to store ssh assets for the application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :...
0.001287
def get_command(self, ctx, cmd_name): """ gets the Click Commands underneath a service name Parameters ---------- ctx: Context context object passed in cmd_name: string the service name Returns ------- cmd: Click.Command ...
0.003465
def from_json(cls, data): """ Create STAT from json dictionary. Args: data: { 'location': {} , // ladybug location schema 'ashrae_climate_zone': str, 'koppen_climate_zone': str, 'extreme_cold_week': {}, // ladybug analy...
0.00315
def validate_day_start_ut(conn): """This validates the day_start_ut of the days table.""" G = GTFS(conn) cur = conn.execute('SELECT date, day_start_ut FROM days') for date, day_start_ut in cur: #print date, day_start_ut assert day_start_ut == G.get_day_start_ut(date)
0.006689
def transform(self): '''P⃗,Q⃗,W⃗''' i = self.inclination Ω = self.longitude_of_ascending_node ω = self.argument_of_periapsis si = sin(i) ci = cos(i) sΩ = sin(Ω) cΩ = cos(Ω) sω = sin(ω) cω = cos(ω) Q = np.array([ [-sΩ*...
0.014235
def get_filelikeobject(filename: str = None, blob: bytes = None) -> BinaryIO: """ Open a file-like object. Guard the use of this function with ``with``. Args: filename: for specifying via a filename blob: for specifying via an in-memory ``bytes`` object Retu...
0.001577
def get_attrtext(value): """attrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them...
0.001437
def contribute_to_class(self, process, fields, name): """Register this field with a specific process. :param process: Process descriptor instance :param fields: Fields registry to use :param name: Field name """ # Use order-preserving definition namespace (__dict__) to r...
0.002886
def rename(self, old_key, new_key): """ Reindexes an item from an old key to a new key. If there was no such item, does nothing. Returns 0 if successful, else -1. """ return lib.zhashx_rename(self._as_parameter_, old_key, new_key)
0.007634
def _control_sample(self, sample): ''' Control the asked sample is ok ''' if sample > float(self.SAMPLE_LAST_PIXEL): return int(self.SAMPLE_LAST_PIXEL) elif sample < float(self.SAMPLE_FIRST_PIXEL): return int(self.SAMPLE_FIRST_PIXEL) else: return sampl...
0.006231
def disassemble(self, code, lasti=-1, file=None): """Disassemble a code object.""" return self.disco(code, lasti, file)
0.014815
def common(self, other, suffix=False): ''' Return the common prefix of these two concs; that is, the largest conc which can be safely beheaded() from the front of both. The result could be emptystring. "ZYAA, ZYBB" -> "ZY" "CZ, CZ" -> "CZ" "YC, ZC" -> "" With the "suffix" flag set, works from th...
0.030783
def setDatastreamState(self, pid, dsID, dsState): '''Update datastream state. :param pid: object pid :param dsID: datastream id :param dsState: datastream state :returns: boolean success ''' # /objects/{pid}/datastreams/{dsID} ? [dsState] http_args = {'ds...
0.006969
def get_perm_name(cls, action, full=True): """ Return the name of the permission for a given model and action. By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the `perm_codename`. """ codename = "{}_{}".format(action, cls.__name__.lower...
0.004796
def total(self): """ Return the total (virtual) size of the process in bytes. If process information is not available, get the best number available, even if it is a poor approximation of reality. """ if self.system_total.available: return self.system_total.vs...
0.008299
def _get(url, params=None): """HTTP GET request.""" try: response = requests.get(url, params=params) response.raise_for_status() # If JSON fails, return raw data # (e.g. when downloading CSV job logs). try: return response.json(...
0.003591
def all_hermitian(self): """ Check if all basis operators are hermitian. """ if self._all_hermitian is None: _log.debug("Testing and caching if all basis operator are hermitian") self._all_hermitian = all((is_hermitian(op) for op in self.ops)) return self....
0.008982
def check_for_lane_permission(self): """ One or more permissions can be associated with a lane of a workflow. In a similar way, a lane can be restricted with relation to other lanes of the workflow. This method called on lane changes and checks user has required permissi...
0.003272
def revoke_user_access(self, db_names, strict=True): """ Revokes access to the databases listed in `db_names` for the user. """ return self.manager.revoke_user_access(self, db_names, strict=strict)
0.008734
def features(self): """List of features.""" r = [] for _, inter in self.props.items(): if isinstance(inter, tuple): if (inter[0] and inter[1] and inter[0].getValue() == inter[1].getValue() and inter[0].operator == "=" and inter[1].operator == ...
0.004518
def save_draft(self, target_folder=OutlookWellKnowFolderNames.DRAFTS): """ Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool """ if self.object_id: # update message. Attachments ...
0.001825
def _split_input_from_params(cls, app, namespaces, entity_kind_name, params, shard_count): """Return input reader objects. Helper for split_input.""" # pylint: disable=redefined-outer-name key_ranges = [] # KeyRanges for all namespaces for namespace in namespaces: k...
0.003398
def query_get_comment(comID): """ Get all fields of a comment :param comID: comment id :return: tuple (comID, id_bibrec, id_user, body, date_creation, star_score, nb_votes_yes, nb_votes_total, title, nb_abuse_reports, round_name, restriction) if none found return () """ query1 = """S...
0.002058
def build_filename(filename, filetype='png', resolution=300): """ Uses the input properties to create the string of the filename :param str filename: Name of the file :param str filetype: Type of file :param int resolution: DPI resolution of the output figure """ fil...
0.001695
def fetchAllUsers(self, rawResults = False) : """Returns all available users. if rawResults, the result will be a list of python dicts instead of User objects""" r = self.connection.session.get(self.URL) if r.status_code == 200 : data = r.json() if rawResults : ...
0.018868
def _extra_compile_time_classpath(self): """Compute any extra compile-time-only classpath elements.""" def extra_compile_classpath_iter(): for conf in self._confs: for jar in self.extra_compile_time_classpath_elements(): yield (conf, jar) return list(extra_compile_classpath_iter())
0.009404
def get_twitter_id(self, cache=True): """Get the twitter id for this artist if it exists Args: Kwargs: Returns: A twitter ID string Example: >>> a = artist.Artist('big boi') >>> a.get_twitter_id() u'BigBoi' >>> """ ...
0.00381
def populateFromRow(self, dataset): """ Populates the instance variables of this Dataset from the specified database row. """ self._description = dataset.description self.setAttributesJson(dataset.attributes)
0.007813
def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['os'] == 'Fedora': if __grains__['osmajorrelease'] >= 18: ...
0.001175
def start_timer(self, duration, func, *args): """ Schedules a function to be called after some period of time. * duration - time in seconds to wait before firing * func - function to be called * args - arguments to pass to the function """ t = threading.Timer(dur...
0.004016
def _fill_sample_count(self, node): """Counts and fills sample counts inside call tree.""" node['sampleCount'] += sum( self._fill_sample_count(child) for child in node['children']) return node['sampleCount']
0.00823
def _islots(self): """ Return an iterator with the inferred slots. """ if "__slots__" not in self.locals: return None for slots in self.igetattr("__slots__"): # check if __slots__ is a valid type for meth in ITER_METHODS: try: ...
0.001045
def behave(cmdline, cwd=".", **kwargs): """ Run behave as subprocess command and return process/shell instance with results (collected output, returncode). """ assert isinstance(cmdline, six.string_types) return run("behave " + cmdline, cwd=cwd, **kwargs)
0.003584
def start_multiplex_socket(self, streams, callback): """Start a multiplexed socket using a list of socket names. User stream sockets can not be included. Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker Combined stream events are wrapped as follows: {"stream"...
0.004353
def loads(s, strip_comments=False, **kw): """ Load a list of trees from a Newick formatted string. :param s: Newick formatted string. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.create`. ...
0.004141
def rating(self, value): """ Updates the Indicators rating Args: value: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) request_data = {'rating': value} return self.tc_requests.update( self.api_type, sel...
0.007653
def find_raw_batches(self, *args, **kwargs): """Query the database and retrieve batches of raw BSON. Similar to the :meth:`find` method but returns a :class:`~pymongo.cursor.RawBatchCursor`. This example demonstrates how to work with raw batches, but in practice raw batches sho...
0.001982
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs)
0.006329
def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your ...
0.002076
def mac_access_list_extended_hide_mac_acl_ext_seq_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list") access_list = ET.SubElement(mac, "access-list") exte...
0.003488
def get_int(self, key: str) -> Optional[int]: """ Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :retur...
0.008403
async def jsk_curl(self, ctx: commands.Context, url: str): """ Download and display a text file from the internet. This command is similar to jsk cat, but accepts a URL. """ # remove embed maskers if present url = url.lstrip("<").rstrip(">") async with ReplResp...
0.005299
def _with_env(self, env): """As the `with_env` class method but for recordset.""" res = self._browse(env, self._ids) return res
0.013245
def pprint_label(self): "The pretty-printed label string for the Dimension" unit = ('' if self.unit is None else type(self.unit)(self.unit_format).format(unit=self.unit)) return bytes_to_unicode(self.label) + bytes_to_unicode(unit)
0.00738
def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML doc...
0.003656
def del_netnode_plugin_name(plugin_name): """ Remove the given plugin name to the list of plugin names registered in the current IDB. Note that this implicitly uses the open IDB via the idc iterface. """ current_names = set(get_netnode_plugin_names()) if plugin_name not in current_names: ...
0.002012
def _set_igmpVlan(self, v, load=False): """ Setter method for igmpVlan, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmpVlan is considered as a private method. Backends looking to populate thi...
0.005382
def breed(self, egg_donor, sperm_donor): """Get it on.""" offspring = [] try: num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0] # 20% chance of twins for _ in range(num_children): child = God(egg_donor, sperm_donor) offspring.append(child)...
0.011342
def init(policy_file=None, rules=None, default_rule=None, use_conf=True): """Init an Enforcer class. :param policy_file: Custom policy file to use, if none is specified, `CONF.policy_file` will be used. :param rules: Default dictionary / Rules to use. It will be ...
0.00073
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
0.009479
def read_xml(cls, url, features, timestamp, game_number): """ read xml object :param url: contents url :param features: markup provider :param timestamp: game day :param game_number: game number :return: pitchpx.game.game.Game object """ soup = Mlb...
0.004484
def build_pipeline(self, collection): """ Creates aggregation pipeline for aggregation :param collection: Mongo collection for aggregation :type collection: MongoCollection :return pipeline: list of dicts """ pipeline = [] if isinstance(...
0.002146
def setup_margins(self, linenumbers=True, markers=True): """ Setup margin settings (except font, now set in editor.set_font) """ self._margin = linenumbers self._markers_margin = markers self.set_enabled(linenumbers or markers)
0.007067
def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key)
0.007905
def list_adresposities_by_nummer_and_straat(self, nummer, straat): ''' List all `adresposities` for a huisnummer and a :class:`Straat`. :param nummer: A string representing a certain huisnummer. :param straat: The :class:`Straat` for which the \ `adresposities` are wanted. O...
0.002427
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True): r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** ...
0.001543
def selectrowindex(self, window_name, object_name, row_index): """ Select row index @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full nam...
0.003512
def execute_debug(self, js): """executes javascript js in current context as opposed to the (faster) self.execute method, you can use your regular debugger to set breakpoints and inspect the generated python code """ code = translate_js(js, '') # make sure you have a temp...
0.005568
def from_line(cls, line): """ Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the openssh known_hosts file. Lines are expected to not have leading or trailing whitespace. We...
0.001621
def timesince(self, now=None): """ Shortcut for the ``django.utils.timesince.timesince`` function of the current timestamp. """ from django.utils.timesince import timesince as timesince_ return timesince_(self.timestamp, now)
0.007326
def attach_schema(self, schem): """Add a tuple schema to this object (externally imposed)""" self.tuple_schema = schema.AndSchema.make(self.tuple_schema, schem)
0.005952
def set_bank(self, bank, try_preserve_index=False): """ Set the current :class:`Bank` for the bank only if the ``bank != current_bank`` The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. ...
0.007328
def cancelSignalNotification(self, rule_id): """ Cancels a callback previously registered with notifyOnSignal """ if self._signalRules and rule_id in self._signalRules: self.objHandler.conn.delMatch(rule_id) self._signalRules.remove(rule_id)
0.006734
def find_tags(tokens, lexicon={}, model=None, morphology=None, context=None, entities=None, default=("NN", "NNP", "CD"), language="en", map=None, **kwargs): """ Returns a list of [token, tag]-items for the given list of tokens: ["The", "cat", "purs"] => [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] ...
0.003376
def apply(self, data_source): """ Called with the predict data (new information). @param data_source: Either a pandas.DataFrame or a file-like object. """ dataframe = self.__get_dataframe(data_source, use_target=False) dataframe = self.__cleaner.apply(dataframe) d...
0.005115