text
stringlengths
78
104k
score
float64
0
0.18
def get_network_addresses(self): """For each network configured, return corresponding address and hostnamr or vip (if available). Returns a list of tuples of the form: [(address_in_net_a, hostname_in_net_a), (address_in_net_b, hostname_in_net_b), ...] ...
0.001267
def get_real_stored_key(self, session_key): """Return the real key name in redis storage @return string """ prefix = settings.SESSION_REDIS_PREFIX if not prefix: return session_key return ':'.join([prefix, session_key])
0.007168
def resolve_label_components(self, module = None, function = None, offset = None): """ Resolve the memory address of the given module, function and/or offset. @note: If multiple modules with the same n...
0.003196
def generate_if_then_else(self): """ Implementation of if-then-else. .. code-block:: python { 'if': { 'exclusiveMaximum': 0, }, 'then': { 'minimum': -10, }, 'else...
0.001438
def to_segmentlistdict(self): """ Return a segmentlistdict object describing the instruments and times spanned by the entries in this Cache. The return value is coalesced. """ d = segments.segmentlistdict() for entry in self: d |= entry.segmentlistdict return d
0.039146
def expand_envvars(env): ''' Expand all environment variables in an environment dict :param env: Environment dict ''' out_env = {} for k, v in env.iteritems(): out_env[k] = Template(v).safe_substitute(env) # Expand twice to make sure we expand everything we possibly can for k...
0.002375
def parse(cls, j): """ :param dict j: JSON response from TryHaskell. :rtype: TryHaskell.Result """ error = j.get('error') if error: return cls._bad_result(error) success = j.get('success') if success: try: return cls...
0.002869
def plot_dropout_rate_heterogeneity( model, suptitle="Heterogeneity in Dropout Probability", xlabel="Dropout Probability p", ylabel="Density", suptitle_fontsize=14, **kwargs ): """ Plot the estimated gamma distribution of p. p - (customers' probability of dropping out immediately af...
0.001522
def candle_lighting(self): """Return the time for candle lighting, or None if not applicable.""" today = HDate(gdate=self.date, diaspora=self.location.diaspora) tomorrow = HDate(gdate=self.date + dt.timedelta(days=1), diaspora=self.location.diaspora) # If today...
0.00225
def setCollapsed(self, state): """ Sets whether or not this toolbar is in a collapsed state. :return <bool> changed """ if state == self._collapsed: return False self._collapsed = state self.refreshButton() if not...
0.014388
def as_dash_app(self): ''' Return a DjangoDash instance of the dash application ''' dateless_dash_app = getattr(self, '_stateless_dash_app_instance', None) if not dateless_dash_app: dateless_dash_app = get_stateless_by_name(self.app_name) setattr(self, '_s...
0.005
async def parse_user_results(soup): """ Parse a page of user results :param soup: Bs4 Class object :return: A list of dictionaries containing a name and join date """ soup = list(soup.find_all('table', class_='stripe')[0].children)[1:] users = [] for item in soup: t_u = {'name':...
0.001965
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order...
0.020921
def list_stack(profile=None): ''' Return a list of available stack (heat stack-list) profile Profile to use CLI Example: .. code-block:: bash salt '*' heat.list_stack profile=openstack1 ''' ret = {} h_client = _auth(profile) for stack in h_client.stacks.list(): ...
0.001344
def opendocs(where='index', how='default'): ''' Rebuild documentation and opens it in your browser. Use the first argument to specify how it should be opened: `d` or `default`: Open in new tab or new window, using the default method of your browser. `t` or `tab`: Open documentatio...
0.001164
def __is_control_flow(self): """ Private method to tell if the instruction pointed to by the program counter is a control flow instruction. Currently only works for x86 and amd64 architectures. """ jump_instructions = ( 'jmp', 'jecxz', 'jcxz', 'ja...
0.005376
def process_objects(kls): """ Applies default Meta properties. """ # first add a Meta object if not exists if 'Meta' not in kls.__dict__: kls.Meta = type('Meta', (object,), {}) if 'unique_together' not in kls.Meta.__dict__: kls.Meta.unique_together...
0.003306
def end(self): """Close the V interface. Args:: No argument Returns:: None C library equivalent : Vend """ # Note: Vend is just a macro; use 'Vfinish' instead # Note also the the same C function is ...
0.004032
def bucket(self, bucket_name, user_project=None): """Factory constructor for bucket object. .. note:: This will not make an HTTP request; it simply instantiates a bucket object owned by this client. :type bucket_name: str :param bucket_name: The name of the bucket t...
0.002841
def clear(self): """ Remove all cache entries. """ db = sqlite3.connect(self.path) c = db.cursor() c.execute("DELETE FROM dirhashcache") db.commit() db.close()
0.008969
def sum(self, values, axis=0, dtype=None): """compute the sum over each group Parameters ---------- values : array_like, [keys, ...] values to sum per group axis : int, optional alternative reduction axis for values dtype : output dtype R...
0.0033
def _add_namespaces(self): """ Add namespaces to NIDM document. """ self.doc.add_namespace(NIDM) self.doc.add_namespace(NIIRI) self.doc.add_namespace(CRYPTO) self.doc.add_namespace(DCT) self.doc.add_namespace(DC) self.doc.add_namespace(NFO) ...
0.004762
def is_valid(arxiv_id): """ Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690...
0.002628
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t): pt = zeros((range_x, range_y, 3)) "omp parallel for private(i,j,k,tmp)" for i in xrange(range_x): for j in xrange(range_y): pt[i,j,0], pt[i,j,1] = (xmin+step*i)*180/math.pi, (ymin+step*j)*180/math.pi for k in...
0.033784
def transform_metadata(blob): """ Transforms metadata types about channels / users / bots / etc. into a dict rather than a list in order to enable faster lookup. """ o = {} for e in blob: i = e[u'id'] o[i] = e return o
0.043478
def detach(self, attachments): """Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will simply not be created on the server the item i...
0.006674
def search(self, paths_rows=None, lat=None, lon=None, address=None, start_date=None, end_date=None, cloud_min=None, cloud_max=None, limit=1, geojson=False): """ The main method of Search class. It searches Development Seed's Landsat API. :param paths_rows: A string in...
0.002669
def validate_cmd_response_nonce(got, used): """ Check that the returned nonce matches nonce used in request. A request nonce of 000000000000 means the HSM should generate a nonce internally though, so if 'used' is all zeros we actually check that 'got' does NOT match 'used'. """ if used == '000...
0.009554
def format_version(version, build_number=None, build_tag=BUILD_TAG): """ Format a version string for use in packaging. >>> format_version([0,3,5]) '0.3.5' >>> format_version([8, 8, 9], 23676) '8.8.9-jenkins-23676' >>> format_version([8, 8, 9], 23676, 'koekjes') '8.8.9-koekjes-23676'...
0.007533
def get_unique_scan_parameter_combinations(meta_data_array, scan_parameters=None, scan_parameter_columns_only=False): '''Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters. If selected columns only is true, the ...
0.006042
def api_version_elb_backend(*args, **kwargs): """ ELB and ELBV2 (Classic and Application load balancers) use the same hostname and url space. To differentiate them we must read the `Version` parameter out of the url-encoded request body. TODO: There has _got_ to be a better way to do this. Please he...
0.001009
def update_priority(self, tree_idx_list, priority_list): """ Update priorities of the elements in the tree """ for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees): segment_tree.update(tree_idx, priority)
0.010989
def query_framebuffer(self, screen_id): """Queries the graphics updates targets for a screen. in screen_id of type int return framebuffer of type :class:`IFramebuffer` """ if not isinstance(screen_id, baseinteger): raise TypeError("screen_id can only be an instance...
0.007859
def log_value(self, name, value, step=None): """Log new value for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (float): this is a real number to be logged as a scalar. ...
0.002039
def get_credentials(options, environment): """ Get credentials or prompt for them from options """ if options['--username'] or options['--auth']: if not options['--username']: options['<username>'] = lib.prompt("Please enter the username for %s..." % environment) if not options['--pa...
0.006508
def set_environment(self, environment): """Set the environment for all nodes.""" todo = deque([self]) while todo: node = todo.popleft() node.environment = environment todo.extend(node.iter_child_nodes()) return self
0.007067
def delete_sql(table, filter): ''' >>> delete_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('DELETE FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) ''' keys, values = _split_dict(filter) where = _pairs(keys) sql = 'DELETE FROM {} WHERE {}'.format(table, where) return sql, values
0.003289
def swagger_ui_script_template(request, **kwargs): """ :param request: :return: Generates the <script> code that bootstraps Swagger UI, it will be injected into index template """ swagger_spec_url = request.route_url('cornice_swagger.open_api_path') template = pkg_resources.resource_str...
0.001942
def get(self, hook_id): """Get a webhook.""" path = '/'.join(['notification', 'webhook', hook_id]) return self.rachio.get(path)
0.013245
def record_to_objects(self): """Create config records to match the file metadata""" from ..util import AttrDict fr = self.record contents = fr.unpacked_contents if not contents: return ad = AttrDict(contents) # Get time that filessystem was synch...
0.007937
def _set_m2ms(self, old_m2ms): """ Creates the same m2m relationships that the old object had. """ for k, v in old_m2ms.items(): if v: setattr(self, k, v)
0.008969
def _set_avg_session_metrics(session_group): """Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values across the sessions in t...
0.009302
def tuple_type_compare(types0, types1): """doufo.tuple_type_compare: compare two types if `types0` is 'bigger' than `types1`, return negative (<0); otherwise, return positive (>0). Here 'bigger' is defined by whether they are 'parent and child', or ituitively bigger Args: ...
0.012469
def _shellcomplete(cli, prog_name, complete_var=None): """Internal handler for the bash completion support. Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line complete_var : str The environ...
0.002362
def accept_key(pki_dir, pub, id_): ''' If the master config was available then we will have a pki_dir key in the opts directory, this method places the pub key in the accepted keys dir and removes it from the unaccepted keys dir if that is the case. ''' for key_dir in 'minions', 'minions_pre', '...
0.001214
def get_declared_items(self): """ Override to do it manually """ for k, v in super(AndroidListView, self).get_declared_items(): if k == 'layout': yield k, v break
0.012552
def incrby(self, key, increment): """Increments the number stored at key by increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer...
0.002153
def _parse_contract(self, player_info): """ Parse the player's contract. Depending on the player's contract status, a contract table is located at the bottom of the stats page and includes player wages by season. If found, create a dictionary housing the wages by season. ...
0.001696
def get_state(self): """ Return the sampler and step methods current state in order to restart sampling at a later time. """ self.step_methods = set() for s in self.stochastics: self.step_methods |= set(self.step_method_dict[s]) state = Sampler.get_s...
0.003738
def execute_catch(c, sql, vars=None): """Run a query, but ignore any errors. For error recovery paths where the error handler should not raise another.""" try: c.execute(sql, vars) except Exception as err: cmd = sql.split(' ', 1)[0] log.error("Error executing %s: %s", cmd, err)
0.006369
def safe_decode(text, incoming=None, errors='strict'): """Decodes incoming text/bytes string using `incoming` if they're not already unicode. This function was copied from novaclient.openstack.strutils :param incoming: Text's current encoding :param errors: Errors handling policy. See here for ...
0.000657
def start(self): """Start the sensor. """ if rospy.get_name() == '/unnamed': raise ValueError('Weight sensor must be run inside a ros node!') self._weight_subscriber = rospy.Subscriber('weight_sensor/weights', Float32MultiArray, self._weights_callback) self._running =...
0.009231
def parse_frame(self, buf: bytes) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]: """Return the next frame from the socket.""" frames = [] if self._tail: buf, self....
0.000623
def plot(self, **kwargs): """Plot xvg file data. The first column of the data is always taken as the abscissa X. Additional columns are plotted as ordinates Y1, Y2, ... In the special case that there is only a single column then this column is plotted against the index, i.e. (N...
0.004155
def set_theme(self, theme_name): """ Set new theme to use. Uses a direct tk call to allow usage of the themes supplied with this package. :param theme_name: name of theme to activate """ package = theme_name if theme_name not in self.PACKAGES else self.PACKAGES[theme_nam...
0.006682
def _agent_is_gene(agent, specific_only): """Returns whether an agent is for a gene. Parameters ---------- agent: Agent The agent to evaluate specific_only : Optional[bool] If True, only elementary genes/proteins evaluate as genes and families will be filtered out. If False,...
0.005284
def bbox_rot90(bbox, factor, rows, cols): """Rotates a bounding box by 90 degrees CCW (see np.rot90) Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int): Image co...
0.002837
def _compare_frame_rankings(ref, est, transitive=False): '''Compute the number of ranking disagreements in two lists. Parameters ---------- ref : np.ndarray, shape=(n,) est : np.ndarray, shape=(n,) Reference and estimate ranked lists. `ref[i]` is the relevance score for point `i`. ...
0.000458
def make_config_file(guided=False): """ Options: --auto, --guided, --manual Places for the file: --inplace, --user """ config_path = _make_config_location(guided=guided) config_data = make_config_data(guided=guided) write_config_file(config_path, config_data)
0.00346
def _determine_unfiltered_package_names(self): """ Return a list of package names to be filtered base on the configuration file. """ # This plugin only processes packages, if the line in the packages # configuration contains a PEP440 specifier it will be processed by the ...
0.002155
def dropout_no_scaling(x, keep_prob): """Like tf.nn.dropout, but does not scale up. Works on integers also. Args: x: a Tensor keep_prob: a floating point number Returns: Tensor of the same shape as x. """ if keep_prob == 1.0: return x mask = tf.less(tf.random_uniform(tf.shape(x)), keep_pr...
0.014085
def parse_config_output(self, output): """ This method will parse a string containing FortiOS config and will load it into the current :class:`~pyFG.forticonfig.FortiConfig` object. Args: - **output** (string) - A string containing a supported version of FortiOS config ...
0.002367
def get_ir_reciprocal_mesh(self, mesh=(10, 10, 10), is_shift=(0, 0, 0)): """ k-point mesh of the Brillouin zone generated taken into account symmetry.The method returns the irreducible kpoints of the mesh and their weights Args: mesh (3x1 array): The number of kpoint...
0.001767
def connect(self, interface, event, handler): """Connect to a DBus signal. Returns subscription id (int).""" object_path = self.object_path return self.bus.connect(interface, event, object_path, handler)
0.008811
def get_program(self, program_path, controller=None): """ Find the program within this manifest. If key is found, and it contains a list, iterate over the list and return the program that matches the controller tag. NOTICE: program_path must have a leading slash. """ if n...
0.003516
def extract_attrs(x, n): """Extracts attributes from element list 'x' beginning at index 'n'. The elements encapsulating the attributes (typically a series of Str and Space elements) are removed from 'x'. Items before index 'n' are left unchanged. Returns the attributes in pandoc format. A Value...
0.000799
def find(self, state, recp): """WARNING: This function do not return partners currently being initialized.""" if recipient.IRecipient.providedBy(recp): agent_id = recipient.IRecipient(recp).key else: agent_id = recp desc = state.agent.get_descriptor() ...
0.004219
def show_doc_from_name(mod_name, ft_name:str, doc_string:bool=True, arg_comments:dict={}, alt_doc_string:str=''): "Show documentation for `ft_name`, see `show_doc`." mod = import_mod(mod_name) splits = str.split(ft_name, '.') assert hasattr(mod, splits[0]), print(f"Module {mod_name} doesn't have a funct...
0.023474
def process(self, state, irsb=None, skip_stmts=0, last_stmt=99999999, whitelist=None, inline=False, force_addr=None, insn_bytes=None, size=None, num_inst=None, traceflags=0, thumb=False, ...
0.008814
def render_template(template): """ takes a template to render to and returns a function that takes an object to render the data for this template. If callable_or_dict is callable, it will be called with the request and any additional arguments to produce the template paramaters. This is useful ...
0.000793
def nl_list_del(obj): """https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L49. Positional arguments: obj -- nl_list_head class instance. """ obj.next.prev = obj.prev obj.prev.next_ = obj.next_
0.004149
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: dir...
0.002262
def ParseFileObject(self, parser_mediator, file_object): """Parses a plist file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: Un...
0.004447
def Cleanse(obj, encoding='utf-8'): """Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Args: obj: Python data structure. encodi...
0.012452
def get_dos(self): '''Find the total DOS shifted by the Fermi energy''' # find the dos file fildos = '' for f in self._files: with open(f, 'r') as fp: first_line = next(fp) if "E (eV)" in first_line and "Int dos(E)" in first_line: ...
0.006832
def get_random_condcount(mode): """ HITs can be in one of three states: - jobs that are finished - jobs that are started but not finished - jobs that are never going to finish (user decided not to do it) Our count should be based on the first two, so we count any tasks finished o...
0.00282
def audio_set_format(self, format, rate, channels): '''Set decoded audio format. This only works in combination with L{audio_set_callbacks}(), and is mutually exclusive with L{audio_set_format_callbacks}(). @param format: a four-characters string identifying the sample format (e.g. "S16N...
0.007117
def create(self, configuration, name, description): """ Creates a data view from the search template and ml template given :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Desc...
0.003614
def validate(cls, mapper_spec): """Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid. """ if mapper_spec.input_reader_class() != cls: raise BadReaderPar...
0.008143
def getLaplaceCovar(self): """ USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self.cache['Sigma']==Non...
0.018868
def from_decimal(number, width=1): """ Takes a decimal and returns base91 char string. With optional parameter for fix with output """ text = [] if not isinstance(number, int_type): raise TypeError("Expected number to be int, got %s", type(number)) elif not isinstance(width, int_typ...
0.001321
def on_connect(self, connection): "Re-subscribe to any channels and patterns previously subscribed to" # NOTE: for python3, we can't pass bytestrings as keyword arguments # so we need to decode channel/pattern names back to unicode strings # before passing them to [p]subscribe. s...
0.00243
def _load_config(self, path): """Return YAML values from given config file. @param path file to load """ try: with open(path) as f: values = yaml.safe_load(f) if isinstance(values, dict): return values else:...
0.005435
def address(self): """ IP Address using bacpypes Address format """ port = "" if self._port: port = ":{}".format(self._port) return Address( "{}/{}{}".format( self.interface.ip.compressed, self.interface.exploded.spl...
0.005291
def get_existing_pipelines(self): """Get existing pipeline configs for specific application. Returns: str: Pipeline config json """ url = "{0}/applications/{1}/pipelineConfigs".format(API_URL, self.app_name) resp = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_...
0.008715
def get_metadata(self, path, include_entities=False, **kwargs): """Return metadata found in JSON sidecars for the specified file. Args: path (str): Path to the file to get metadata for. include_entities (bool): If True, all available entities extracted from the f...
0.001463
def id(self): """获取用户id,就是网址最后那一部分. :return: 用户id :rtype: str """ return re.match(r'^.*/([^/]+)/$', self.url).group(1) \ if self.url is not None else ''
0.009756
def mark_checked(self, institute, case, user, link, unmark=False): """Mark a case as checked from an analysis point of view. Arguments: institute (dict): A Institute object case (dict): Case object user (dict): A User object link (str...
0.003754
def is_true(entity, prop, name): "bool: True if the value of a property is True." return is_not_empty(entity, prop, name) and name in entity._data and bool(getattr(entity, name))
0.010753
def is_syscall_addr(self, addr): """ Return whether or not the given address corresponds to a syscall implementation. """ if self.kernel_base is None or addr < self.kernel_base: return False addr -= self.kernel_base if addr % self.syscall_addr_alignment != 0...
0.006772
def validate_email(self, email): """ Validate the provided email address. The email address is first modified to match the RFC spec. Namely, the domain portion of the email is lowercased. Returns: The validated email address. Raises: serializers...
0.002336
def seek_file_end(file): '''Seek to the end of the file.''' try: file.seek(0, 2) except ValueError: # gzip files don't support seek from end while True: data = file.read(4096) if not data: break
0.003704
def distance_to_arc(alon, alat, aazimuth, plons, plats): """ Calculate a closest distance between a great circle arc and a point (or a collection of points). :param float alon, alat: Arc reference point longitude and latitude, in decimal degrees. :param azimuth: Arc azimuth (an angl...
0.000593
def get_memberships(self): """Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ response = self._get_xml(self.rest_url + "/group/membership") if not response.ok: return None ...
0.004711
def delete_peer(self, peer_address, stale=False): """ Remove the Nomad server with given address from the Raft configuration. The return code signifies success or failure. https://www.nomadproject.io/docs/http/operator.html arguments: - peer_address, The addre...
0.006445
def frommatrix(cls, apart, dpart, init_matrix, **kwargs): """Create an instance of `Parallel3dAxisGeometry` using a matrix. This alternative constructor uses a matrix to rotate and translate the default configuration. It is most useful when the transformation to be applied is already gi...
0.000565
def extract(self, html_contents, css_contents=None, base_url=None): """ Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree :param html_contents: The HTML contents to parse :type html_contents: str :param css_contents: The CSS con...
0.001844
def pipeline(*functions, funcs=None): """like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs))) """ if funcs: functions = funcs head, *tail = functions return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail)
0.003448
def execution_engine_model_changed(self, model, prop_name, info): """Active observation of state machine and show and hide widget. """ if not self._view_initialized: return active_sm_id = rafcon.gui.singleton.state_machine_manager_model.state_machine_manager.active_state_machine_id ...
0.008143
def get_top_n_action_types(self, top_n): """Returns the top N actions by count.""" # Count action types action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action_typ...
0.001248