_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q46600
tvdb_search_series
train
def tvdb_search_series( token, series=None, id_imdb=None, id_zap2it=None, lang="en", cache=True ): """ Allows the user to search for a series based on the following parameters Online docs: https://api.thetvdb.com/swagger#!/Search/get_search_series Note: results a maximum of 100 entries per page, no opt...
python
{ "resource": "" }
q46601
HeaderParser.remove_header
train
def remove_header(self, name): """Remove a field from the header""" if name in self.info_dict: self.info_dict.pop(name) logger.info("Removed '{0}' from INFO".format(name)) if name in self.filter_dict: self.filter_dict.pop(name) logger.info("Removed...
python
{ "resource": "" }
q46602
HeaderParser.add_fileformat
train
def add_fileformat(self, fileformat): """ Add fileformat line to the header. Arguments: fileformat (str): The id of the info line """ self.fileformat = fileformat logger.info("Adding fileformat to vcf: {0}".format(fileformat)) return
python
{ "resource": "" }
q46603
HeaderParser.add_meta_line
train
def add_meta_line(self, key, value): """ Adds an arbitrary metadata line to the header. This must be a key value pair Arguments: key (str): The key of the metadata line value (str): The value of the metadata line """ meta_line = '##{0}={1}'.form...
python
{ "resource": "" }
q46604
HeaderParser.add_filter
train
def add_filter(self, filter_id, description): """ Add a filter line to the header. Arguments: filter_id (str): The id of the filter line description (str): A description of the info line """ filter_line = '##FILTER=<ID={0},Description="{1}">'.format( ...
python
{ "resource": "" }
q46605
HeaderParser.add_format
train
def add_format(self, format_id, number, entry_type, description): """ Add a format line to the header. Arguments: format_id (str): The id of the format line number (str): Integer or any of [A,R,G,.] entry_type (str): Any of [Integer,Float,Flag,Character,Strin...
python
{ "resource": "" }
q46606
HeaderParser.add_alt
train
def add_alt(self, alt_id, description): """ Add a alternative allele format field line to the header. Arguments: alt_id (str): The id of the alternative line description (str): A description of the info line """ alt_line = '##ALT=<ID={0},Description="{1}...
python
{ "resource": "" }
q46607
HeaderParser.add_contig
train
def add_contig(self, contig_id, length): """ Add a contig line to the header. Arguments: contig_id (str): The id of the alternative line length (str): A description of the info line """ contig_line = '##contig=<ID={0},length={1}>'.format( con...
python
{ "resource": "" }
q46608
get_vcf_handle
train
def get_vcf_handle(fsock=None, infile=None): """Open the vcf file and return a handle""" vcf = None if (fsock or infile): if fsock: # if not infile and hasattr(fsock, 'name'): logger.info("Reading vcf form stdin") if sys.version_info < (3, 0): ...
python
{ "resource": "" }
q46609
DeleteTagCallMixin.delete_tag
train
def delete_tag(self, tag_id): """ Deletes a Tag to current object :param tag_id: the id of the tag which should be deleted :type tag_id: int :rtype: None """ from highton.models.tag import Tag self._delete_request( endpoint=self.ENDPOINT + '/...
python
{ "resource": "" }
q46610
ListTaskCallMixin.list_tasks
train
def list_tasks(self): """ Get the tasks of current object :return: the tasks :rtype: list """ from highton.models.task import Task return fields.ListField( name=self.ENDPOINT, init_class=Task ).decode( self.element_fro...
python
{ "resource": "" }
q46611
Company.people
train
def people(self): """ Retrieve all people of the company :return: list of people objects :rtype: list """ return fields.ListField(name=HightonConstants.PEOPLE, init_class=Person).decode( self.element_from_string( self._get_request( ...
python
{ "resource": "" }
q46612
nx_to_ontology
train
def nx_to_ontology(graph, source_node, output_path, base_iri): """Graph nodes are ID's, and have a 'label' in the node data with the right label :param graph: :param source_node: :param str output_path: :param base_iri: """ ontology = owlready.Ontology(base_iri) parent_lookup = { ...
python
{ "resource": "" }
q46613
Participant.check_in
train
async def check_in(self): """ Checks this participant in |methcoro| Warning: |unstable| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/{}/check_in'.format(self._tournament_id, self._id)) self._...
python
{ "resource": "" }
q46614
Participant.undo_check_in
train
async def undo_check_in(self): """ Undo the check in for this participant |methcoro| Warning: |unstable| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/{}/undo_check_in'.format(self._tournament_id, sel...
python
{ "resource": "" }
q46615
Participant.get_matches
train
async def get_matches(self, state: MatchState = MatchState.all_): """ Return the matches of the given state |methcoro| Args: state: see :class:`MatchState` Raises: APIException """ matches = await self.connection('GET', ...
python
{ "resource": "" }
q46616
Participant.get_next_match
train
async def get_next_match(self): """ Return the first open match found, or if none, the first pending match found |methcoro| Raises: APIException """ if self._final_rank is not None: return None matches = await self.get_matches(MatchState.open_)...
python
{ "resource": "" }
q46617
Type2Helper._get_pseudo_key
train
def _get_pseudo_key(self, row): """ Returns the pseudo key in a row. :param dict row: The row. :rtype: tuple """ ret = list() for key in self._pseudo_key: ret.append(row[key]) return tuple(ret)
python
{ "resource": "" }
q46618
Type2Helper._date2int
train
def _date2int(date): """ Returns an integer representation of a date. :param str|datetime.date date: The date. :rtype: int """ if isinstance(date, str): if date.endswith(' 00:00:00') or date.endswith('T00:00:00'): # Ignore time suffix. ...
python
{ "resource": "" }
q46619
Type2Helper._rows_date2int
train
def _rows_date2int(self, rows): """ Replaces start and end dates in a row set with their integer representation :param list[dict[str,T]] rows: The list of rows. """ for row in rows: # Determine the type of dates based on the first start date. if not self....
python
{ "resource": "" }
q46620
Type2Helper._rows_int2date
train
def _rows_int2date(self, rows): """ Replaces start and end dates in the row set with their integer representation :param list[dict[str,T]] rows: The list of rows. """ for row in rows: if self._date_type == 'str': row[self._key_start_date] = datetime.d...
python
{ "resource": "" }
q46621
Type2Helper._rows_sort
train
def _rows_sort(self, rows): """ Returns a list of rows sorted by start and end date. :param list[dict[str,T]] rows: The list of rows. :rtype: list[dict[str,T]] """ return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))
python
{ "resource": "" }
q46622
Type2Helper._get_date_type
train
def _get_date_type(date): """ Returns the type of a date. :param str|datetime.date date: The date. :rtype: str """ if isinstance(date, str): return 'str' if isinstance(date, datetime.date): return 'date' if isinstance(date, int)...
python
{ "resource": "" }
q46623
Type2Helper._equal
train
def _equal(self, row1, row2): """ Returns True if two rows are identical excluding start and end date. Returns False otherwise. :param dict[str,T] row1: The first row. :param dict[str,T] row2: The second row. :rtype: bool """ for key in row1.keys(): ...
python
{ "resource": "" }
q46624
Type2Helper.enumerate
train
def enumerate(self, name, start=1): """ Enumerates all rows such that the pseudo key and the ordinal number are a unique key. :param str name: The key holding the ordinal number. :param int start: The start of the ordinal numbers. Foreach pseudo key the first row has this ordinal number...
python
{ "resource": "" }
q46625
Type2Helper.get_rows
train
def get_rows(self, sort=False): """ Returns the rows of this Type2Helper. :param bool sort: If True the rows are sorted by the pseudo key. """ ret = [] for _, rows in sorted(self._rows.items()) if sort else self._rows.items(): self._rows_int2date(rows) ...
python
{ "resource": "" }
q46626
Type2Helper.prepare_data
train
def prepare_data(self, rows): """ Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key. :param list[dict] rows: The rows """ s...
python
{ "resource": "" }
q46627
make_parser
train
def make_parser(func_sig, description, epilog, add_nos): ''' Given the signature of a function, create an ArgumentParser ''' parser = ArgumentParser(description=description, epilog=epilog) used_char_args = {'h'} # Arange the params so that single-character arguments are first. This # esnur...
python
{ "resource": "" }
q46628
parse_docstring
train
def parse_docstring(docstring): ''' Given a docstring, parse it into a description and epilog part ''' if docstring is None: return '', '' parts = _DOCSTRING_SPLIT.split(docstring) if len(parts) == 1: return docstring, '' elif len(parts) == 2: return parts[0], parts...
python
{ "resource": "" }
q46629
ListCommentCallMixin.list_comments
train
def list_comments(self, page=0): """ Get the comments of current object :param page: the page starting at 0 :return: the emails :rtype: list """ from highton.models.comment import Comment params = {'page': int(page) * self.COMMENT_OFFSET} return ...
python
{ "resource": "" }
q46630
Deal.update_status
train
def update_status(self, status): """ Updates the status of the deal :param status: status have to be ('won', 'pending', 'lost') :return: successfull response or raise Exception :rtype: """ assert (status in (HightonConstants.WON, HightonConstants.PENDING, Highton...
python
{ "resource": "" }
q46631
dict_merge
train
def dict_merge(s, m): """Recursively merge one dict into another.""" if not isinstance(m, dict): return m out = copy.deepcopy(s) for k, v in m.items(): if k in out and isinstance(out[k], dict): out[k] = dict_merge(out[k], v) else: out[k] = copy.deepcopy(v)...
python
{ "resource": "" }
q46632
settings
train
def settings(instance): """Definition to set settings from config file to the app instance.""" with open(instance.root_dir + '/Config/config.yml') as config: config = yaml.load(config) instance.name = config['name'] instance.port = config['web']['port'] # default host ins...
python
{ "resource": "" }
q46633
uri_creator
train
def uri_creator(uri, regex, defaults): """Creates url and replaces regex and gives variables""" # strip trailing slash uri = uri.strip('/') # take out variables in uri matches = re.findall('{[a-zA-Z0-9\_]+}', uri) default_regex = '[a-zA-Z0-9]+' variables = [] # iter through match...
python
{ "resource": "" }
q46634
DetailCallMixin.get
train
def get(cls, object_id): """ Retrieves a single model :param object_id: the primary id of the model :type object_id: integer :return: the object of the parsed xml object :rtype: object """ return fields.ObjectField(name=cls.ENDPOINT, init_class=cls).decod...
python
{ "resource": "" }
q46635
cached_unless_authenticated
train
def cached_unless_authenticated(timeout=50, key_prefix='default'): """Cache anonymous traffic.""" def caching(f): @wraps(f) def wrapper(*args, **kwargs): cache_fun = current_cache.cached( timeout=timeout, key_prefix=key_prefix, unless=lambda: current_c...
python
{ "resource": "" }
q46636
Tournament.reset
train
async def reset(self): """ reset the tournament on Challonge |methcoro| Note: |from_api| Reset a tournament, clearing all of its scores and attachments. You can then add/remove/edit participants before starting the tournament again. Raises: APIException ...
python
{ "resource": "" }
q46637
Tournament.update
train
async def update(self, **params): """ update some parameters of the tournament Use this function if you want to update multiple options at once, but prefer helpers functions like :func:`allow_attachments`, :func:`set_start_date`... |methcoro| Args: params: one or more of: ...
python
{ "resource": "" }
q46638
Tournament.update_notifications
train
async def update_notifications(self, on_match_open: bool = None, on_tournament_end: bool = None): """ update participants notifications for this tournament |methcoro| Args: on_match_open: Email registered Challonge participants when matches open up for them on_tournamen...
python
{ "resource": "" }
q46639
Tournament.get_participant
train
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...
python
{ "resource": "" }
q46640
Tournament.get_participants
train
async def get_participants(self, force_update=False) -> list: """ get all participants |methcoro| Args: force_update (default=False): True to force an update to the Challonge API Returns: list[Participant]: Raises: APIException """...
python
{ "resource": "" }
q46641
Tournament.add_participant
train
async def add_participant(self, display_name: str = None, username: str = None, email: str = None, seed: int = 0, misc: str = None, **params): """ add a participant to the tournament |methcoro| Args: display_name: The name displayed in the bracket/schedule - not required if email o...
python
{ "resource": "" }
q46642
Tournament.remove_participant
train
async def remove_participant(self, p: Participant): """ remove a participant from the tournament |methcoro| Args: p: the participant to remove Raises: APIException """ await self.connection('DELETE', 'tournaments/{}/participants/{}'.format(self...
python
{ "resource": "" }
q46643
Tournament.get_match
train
async def get_match(self, m_id, force_update=False) -> Match: """ get a single match by id |methcoro| Args: m_id: match id force_update (default=False): True to force an update to the Challonge API Returns: Match Raises: APIExce...
python
{ "resource": "" }
q46644
Tournament.shuffle_participants
train
async def shuffle_participants(self): """ Shuffle participants' seeds |methcoro| Note: |from_api| Randomize seeds among participants. Only applicable before a tournament has started. Raises: APIException """ res = await self.connection('POST', ...
python
{ "resource": "" }
q46645
Tournament.process_check_ins
train
async def process_check_ins(self): """ finalize the check in phase |methcoro| Warning: |unstable| Note: |from_api| This should be invoked after a tournament's check-in window closes before the tournament is started. 1. Marks participants who have no...
python
{ "resource": "" }
q46646
Tournament.get_final_ranking
train
async def get_final_ranking(self) -> OrderedDict: """ Get the ordered players ranking Returns: collections.OrderedDict[rank, List[Participant]]: Raises: APIException """ if self._state != TournamentState.complete.value: return None ...
python
{ "resource": "" }
q46647
get_entries
train
def get_entries(path): """Return sorted lists of directories and files in the given path.""" dirs, files = [], [] for entry in os.listdir(path): # Categorize entry as directory or file. if os.path.isdir(os.path.join(path, entry)): dirs.append(entry) else: ...
python
{ "resource": "" }
q46648
spectrogram
train
def spectrogram(t_signal, frame_width=FRAME_WIDTH, overlap=FRAME_STRIDE): """ Calculate the magnitude spectrogram of a single-channel time-domain signal from the real frequency components of the STFT with a hanning window applied to each frame. The frame size and overlap between frames should be spe...
python
{ "resource": "" }
q46649
_extract_peaks
train
def _extract_peaks(specgram, neighborhood, threshold): """ Partition the spectrogram into subcells and extract peaks from each cell if the peak is sufficiently energetic compared to the neighborhood. """ kernel = np.ones(shape=neighborhood) local_averages = convolve(specgram, kernel / kernel.sum...
python
{ "resource": "" }
q46650
Api.req
train
def req(self, meth, url, http_data=''): """ sugar that wraps the 'requests' module with basic auth and some headers. """ self.logger.debug("Making request: %s %s\nBody:%s" % (meth, url, http_data)) req_method = getattr(requests, meth) return (req_method(url, ...
python
{ "resource": "" }
q46651
Api.user_agent
train
def user_agent(self): """ its a user agent string! """ version = "" project_root = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(project_root, 'VERSION')) as version_file: version = version_file.read().strip() return "Python Snow A...
python
{ "resource": "" }
q46652
Api.resolve_link
train
def resolve_link(self, snow_record, field_to_resolve, **kparams): """ Get the info from the link and return a SnowRecord. """ try: link = snow_record.links()[field_to_resolve] except KeyError as e: return SnowRecord.NotFound(self, snow_record._table_name, "Cou...
python
{ "resource": "" }
q46653
HightonModel.to_serializable_value
train
def to_serializable_value(self): """ Parses the Hightonmodel to a serializable value such dicts, lists, strings This can be used to save the model in a NoSQL database :return: the serialized HightonModel :rtype: dict """ return_dict = {} for name, field i...
python
{ "resource": "" }
q46654
textile
train
def textile(text, **kwargs): """ Applies Textile conversion to a string, and returns the HTML. This is simply a pass-through to the ``textile`` template filter included in ``django.contrib.markup``, which works around issues PyTextile has with Unicode strings. If you're not using Django but ...
python
{ "resource": "" }
q46655
restructuredtext
train
def restructuredtext(text, **kwargs): """ Applies reStructuredText conversion to a string, and returns the HTML. """ from docutils import core parts = core.publish_parts(source=text, writer_name='html4css1', **kwargs) return ...
python
{ "resource": "" }
q46656
typed
train
def typed(cls): """ Class decorator that updates a class definition with strongly typed property attributes. See Also: If the class will be inherited, use :class:`~exa.typed.TypedClass`. """ for name, attr in _typed_from_items(vars(cls).items()).items(): setattr(cls, name, attr)...
python
{ "resource": "" }
q46657
reconcile
train
def reconcile(constraint): ''' Returns an assignment of type variable names to types that makes this constraint satisfiable, or a Refutation ''' if isinstance(constraint.subtype, NamedType): if isinstance(constraint.supertype, NamedType): if constraint.subtype.name == constr...
python
{ "resource": "" }
q46658
Model.prnt
train
def prnt(self): """ Prints DB data representation of the object. """ print("= = = =\n\n%s object key: \033[32m%s\033[0m" % (self.__class__.__name__, self.key)) pprnt(self._data or self.clean_value())
python
{ "resource": "" }
q46659
Model.get_choices_for
train
def get_choices_for(self, field): """ Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...] """ choices = self._fields[field].choices if isinstance(choices, six.string_types):...
python
{ "resource": "" }
q46660
Model._update_new_linked_model
train
def _update_new_linked_model(self, internal, linked_mdl_ins, link): """ Iterates through linked_models of given model instance to match it's "reverse" with given link's "field" values. """ # If there is a link between two sides (A and B), if a link from A to B, # link sh...
python
{ "resource": "" }
q46661
Model.reload
train
def reload(self): """ Reloads current instance from DB store """ self._load_data(self.objects.data().filter(key=self.key)[0][0], True)
python
{ "resource": "" }
q46662
Model._handle_uniqueness
train
def _handle_uniqueness(self): """ Checks marked as unique and unique_together fields of the Model at each creation and update, and if it violates the uniqueness raises IntegrityError. First, looks at the fields which marked as "unique". If Model's unique fields did not change, i...
python
{ "resource": "" }
q46663
Model.save
train
def save(self, internal=False, meta=None, index_fields=None): """ Save's object to DB. Do not override this method, use pre_save and post_save methods. Args: internal (bool): True if called within model. Used to prevent unneccessary calls to pre_save and ...
python
{ "resource": "" }
q46664
Model.blocking_save
train
def blocking_save(self, query_dict=None, meta=None, index_fields=None): """ Saves object to DB. Waits till the backend properly indexes the new object. Args: query_dict(dict) : contains keys - values of the model fields meta (dict): JSON serializable meta data for loggi...
python
{ "resource": "" }
q46665
Model.delete
train
def delete(self, dry=False, meta=None, index_fields=None): """ Sets the objects "deleted" field to True and, current time to "deleted_at" fields then saves it to DB. Args: dry (bool): False. Do not execute the actual deletion. Just list what will be deleted as a...
python
{ "resource": "" }
q46666
Recognizer.__recognize_scalar
train
def __recognize_scalar(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a scalar. Args: node: The node to recognize. expected_type: The type it is expected to be. Returns: A list of...
python
{ "resource": "" }
q46667
Recognizer.__recognize_list
train
def __recognize_list(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a list of some kind. Args: node: The node to recognize. expected_type: List[...something...] Returns expected_typ...
python
{ "resource": "" }
q46668
Recognizer.__recognize_dict
train
def __recognize_dict(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be a dict of some kind. Args: node: The node to recognize. expected_type: Dict[str, ...something...] Returns: expect...
python
{ "resource": "" }
q46669
Recognizer.__recognize_union
train
def __recognize_union(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The ...
python
{ "resource": "" }
q46670
Recognizer.recognize
train
def recognize(self, node: yaml.Node, expected_type: Type) -> RecResult: """Figure out how to interpret this node. This is not quite a type check. This function makes a list of \ all types that match the expected type and also the node, and \ returns that list. The goal here is not to te...
python
{ "resource": "" }
q46671
cli
train
def cli(ctx, vcf, verbose, outfile, silent): """Simple vcf operations""" # configure root logger to print to STDERR loglevel = LEVELS.get(min(verbose, 3)) configure_stream(level=loglevel) if vcf == '-': handle = get_vcf_handle(fsock=sys.stdin) else: handle = get_vcf_handle(i...
python
{ "resource": "" }
q46672
delete_info
train
def delete_info(ctx, info): """Delete a info field from all variants in a vcf""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent if not info: logger.error("No info provided") sys.exit("Please provide a info string...
python
{ "resource": "" }
q46673
variants
train
def variants(ctx, snpeff): """Print the variants in a vcf""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent print_headers(head, outfile=outfile, silent=silent) for line in vcf_handle: print_variant(variant_line=...
python
{ "resource": "" }
q46674
sort
train
def sort(ctx): """Sort the variants of a vcf file""" head = ctx.parent.head vcf_handle = ctx.parent.handle outfile = ctx.parent.outfile silent = ctx.parent.silent print_headers(head, outfile=outfile, silent=silent) for line in sort_variants(vcf_handle): print_variant(variant_line=l...
python
{ "resource": "" }
q46675
OpenIDBackend.validate
train
def validate(self, request, data): """ Validate response from OpenID server. Set identity in case of successfull validation. """ client = consumer.Consumer(request.session, None) try: resp = client.complete(data, request.session['openid_return_to']) e...
python
{ "resource": "" }
q46676
Stylus.use
train
def use(self, plugin, arguments={}): """Add plugin to use during compilation. plugin: Plugin to include. arguments: Dictionary of arguments to pass to the import. """ self.plugins[plugin] = dict(arguments) return self.plugins
python
{ "resource": "" }
q46677
Stylus.compile
train
def compile(self, source, options={}): """Compile stylus into css source: A string containing the stylus code options: A dictionary of arguments to pass to the compiler Returns a string of css resulting from the compilation """ options = dict(options) if "paths" in options: options["...
python
{ "resource": "" }
q46678
Stylus.context
train
def context(self): "Internal property that returns the stylus compiler" if self._context is None: with io.open(path.join(path.abspath(path.dirname(__file__)), "compiler.js")) as compiler_file: compiler_source = compiler_file.read() self._context = self.backend.compile(compiler_source) re...
python
{ "resource": "" }
q46679
Stylus.backend
train
def backend(self): "Internal property that returns the Node script running harness" if self._backend is None: with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file: runner_source = runner_file.read() self._backend = execjs.ExternalRuntime(name="Node.js (V8...
python
{ "resource": "" }
q46680
CTYPES_IOCPProactor.run
train
def run(self, timeout = 0): """ Calls GetQueuedCompletionStatus and handles completion via process_op. """ # same resolution as epoll ptimeout = int( timeout.days * 86400000 + timeout.microseconds / 1000 + timeout.seconds * 100...
python
{ "resource": "" }
q46681
Compamp.header
train
def header(self): ''' This returns the first header in the data file ''' if self._header is None: self._header = self._read_half_frame_header(self.data) return self._header
python
{ "resource": "" }
q46682
Compamp._packed_data
train
def _packed_data(self): ''' Returns the bit-packed data extracted from the data file. This is not so useful to analyze. Use the complex_data method instead. ''' header = self.header() packed_data = np.frombuffer(self.data, dtype=np.int8)\ .reshape((header['number_of_half_frames'], heade...
python
{ "resource": "" }
q46683
SimCompamp.complex_data
train
def complex_data(self): ''' This unpacks the data into a time-series data, of complex values. Also, any DC offset from the time-series is removed. This is a 1D complex-valued numpy array. ''' cp = np.frombuffer(self.data, dtype='i1').astype(np.float32).view(np.complex64) cp = cp - cp.mean(...
python
{ "resource": "" }
q46684
SimCompamp._spec_fft
train
def _spec_fft(self, complex_data): ''' Calculates the DFT of the complex_data along axis = 1. This assumes complex_data is a 2D array. This uses numpy and the code is straight forward np.fft.fftshift( np.fft.fft(complex_data), 1) Note that we automatically shift the FFT frequency bins so that alo...
python
{ "resource": "" }
q46685
SimCompamp.get_spectrogram
train
def get_spectrogram(self): ''' Transforms the input simulated data and computes a standard-sized spectrogram. If self.sigProc function is not None, the 2D complex-valued time-series data will be processed with that function before the FFT and spectrogram are calculated. ''' return self._spec...
python
{ "resource": "" }
q46686
Adapter.distinct_values_of
train
def distinct_values_of(self, field, count_deleted=False): """ Uses riak http search query endpoint for advanced SOLR queries. Args: field (str): facet field count_deleted (bool): ignore deleted or not Returns: (dict): pairs of field values and numbe...
python
{ "resource": "" }
q46687
Adapter._clear
train
def _clear(self, wait): """ clear outs the all content of current bucket only for development purposes """ i = 0 t1 = time.time() for k in self.bucket.get_keys(): i += 1 self.bucket.get(k).delete() print("\nDELETION TOOK: %s" % roun...
python
{ "resource": "" }
q46688
Adapter._write_version
train
def _write_version(self, data, model): """ Writes a copy of the objects current state to write-once mirror bucket. Args: data (dict): Model instance's all data for versioning. model (instance): Model instance. Returns: Key of version record. ...
python
{ "resource": "" }
q46689
Adapter.count
train
def count(self): """Counts the number of results that could be accessed with the current parameters. :return: number of objects matches to the query :rtype: int """ # Save the existing rows and start parameters to see how many results were actually expected _rows = self...
python
{ "resource": "" }
q46690
Adapter._escape_query
train
def _escape_query(self, query, escaped=False): """ Escapes query if it's not already escaped. Args: query: Query value. escaped (bool): expresses if query already escaped or not. Returns: Escaped query value. """ if escaped: ...
python
{ "resource": "" }
q46691
Adapter._parse_query_modifier
train
def _parse_query_modifier(self, modifier, qval, is_escaped): """ Parses query_value according to query_type Args: modifier (str): Type of query. Exact, contains, lte etc. qval: Value partition of the query. Returns: Parsed query_value. """ ...
python
{ "resource": "" }
q46692
Adapter._parse_query_key
train
def _parse_query_key(self, key, val, is_escaped): """ Strips query modifier from key and call's the appropriate value modifier. Args: key (str): Query key val: Query value Returns: Parsed query key and value. """ if key.endswith('__co...
python
{ "resource": "" }
q46693
Adapter._sort_to_str
train
def _sort_to_str(self): """ Before exec query, this method transforms sort dict string from {"name": "asc", "timestamp":"desc"} to "name asc, timestamp desc" """ params_list = [] timestamp = "" for k, v in self._solr_params['s...
python
{ "resource": "" }
q46694
Adapter._process_params
train
def _process_params(self): """ Adds default row size if it's not given in the query. Converts param values into unicode strings. Returns: Processed self._solr_params dict. """ # transform sort dict into str self._sort_to_str() if 'rows' not i...
python
{ "resource": "" }
q46695
Adapter._exec_query
train
def _exec_query(self): """ Executes solr query if it hasn't already executed. Returns: Self. """ if not self._solr_locked: if not self.compiled_query: self._compile_query() try: solr_params = self._process_param...
python
{ "resource": "" }
q46696
parse_arguments
train
def parse_arguments(args=sys.argv[1:]): """Parse arguments of script.""" cmd_description = "Download tracklistings for BBC radio shows.\n\n" \ "Saves to a text file, tags audio file or does both.\n" \ "To select output file, filename " \ "must bo...
python
{ "resource": "" }
q46697
main
train
def main(): """Check arguments are retrieved.""" args = parse_arguments() print(args) print("action" + args.action) print("pid" + args.pid) print("directory" + args.directory) print("fileprefix" + args.fileprefix)
python
{ "resource": "" }
q46698
OAuthBackend.begin
train
def begin(self, request, data): """ Try to get Request Token from OAuth Provider and redirect user to provider's site for approval. """ request = self.get_request( http_url = self.REQUEST_TOKEN_URL, parameters = dict(oauth_callback = self.get_callback(...
python
{ "resource": "" }
q46699
CoroGreenlet.run
train
def run(self, *args, **kwargs): """This runs in a greenlet""" return_value = self.coro(*args, **kwargs) # i don't like this but greenlets are so dodgy i have no other choice raise StopIteration(return_value)
python
{ "resource": "" }