_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q278400
Mesh.add_fields
test
def add_fields(self, fields = None, **kwargs): """ Add the fields into the list of fields. """ if fields != None: for field in fields: self.fields.append(field)
python
{ "resource": "" }
q278401
Mesh.check_elements
test
def check_elements(self): """ Checks element definitions. """ # ELEMENT TYPE CHECKING existing_types = set(self.elements.type.argiope.values.flatten()) allowed_types = set(ELEMENTS.keys()) if (existing_types <= allowed_types) == False: raise ValueError("Element types {0} not in know el...
python
{ "resource": "" }
q278402
Mesh.space
test
def space(self): """ Returns the dimension of the embedded space of each element. """ return self.elements.type.argiope.map( lambda t: ELEMENTS[t].space)
python
{ "resource": "" }
q278403
Mesh.centroids_and_volumes
test
def centroids_and_volumes(self, sort_index = True): """ Returns a dataframe containing volume and centroids of all the elements. """ elements = self.elements out = [] for etype, group in self.elements.groupby([("type", "argiope", "")]): etype_info = ELEMENTS[etype] simplices_info = e...
python
{ "resource": "" }
q278404
Mesh.angles
test
def angles(self, zfill = 3): """ Returns the internal angles of all elements and the associated statistics """ elements = self.elements.sort_index(axis = 1) etypes = elements[("type", "argiope")].unique() out = [] for etype in etypes: etype_info = ELEMENTS[etype] angles_info = e...
python
{ "resource": "" }
q278405
Mesh.edges
test
def edges(self, zfill = 3): """ Returns the aspect ratio of all elements. """ edges = self.split("edges", at = "coords").unstack() edges["lx"] = edges.x[1]-edges.x[0] edges["ly"] = edges.y[1]-edges.y[0] edges["lz"] = edges.z[1]-edges.z[0] edges["l"] = np.linalg.norm(edges[["lx", "ly", "l...
python
{ "resource": "" }
q278406
Mesh.stats
test
def stats(self): """ Returns mesh quality and geometric stats. """ cv = self.centroids_and_volumes() angles = self.angles() edges = self.edges() return pd.concat([cv , angles[["stats"]], edges[["stats"]] ], axis = 1).sort_index(axis = 1)
python
{ "resource": "" }
q278407
Mesh.element_set_to_node_set
test
def element_set_to_node_set(self, tag): """ Makes a node set from an element set. """ nodes, elements = self.nodes, self.elements loc = (elements.conn[elements[("sets", tag, "")]] .stack().stack().unique()) loc = loc[loc != 0] nodes[("sets", tag)] = False nodes.loc[loc, ("sets...
python
{ "resource": "" }
q278408
Mesh.node_set_to_surface
test
def node_set_to_surface(self, tag): """ Converts a node set to surface. """ # Create a dummy node with label 0 nodes = self.nodes.copy() dummy = nodes.iloc[0].copy() dummy["coords"] *= np.nan dummy["sets"] = True nodes.loc[0] = dummy # Getting element surfaces element_surface...
python
{ "resource": "" }
q278409
Mesh.surface_to_element_sets
test
def surface_to_element_sets(self, tag): """ Creates elements sets corresponding to a surface. """ surface = self.elements.surfaces[tag] for findex in surface.keys(): if surface[findex].sum() != 0: self.elements[("sets", "_SURF_{0}_FACE{1}" .format(tag, findex[1:]),...
python
{ "resource": "" }
q278410
Mesh.fields_metadata
test
def fields_metadata(self): """ Returns fields metadata as a dataframe. """ return (pd.concat([f.metadata() for f in self.fields], axis = 1) .transpose() .sort_values(["step_num", "frame", "label", "position"]))
python
{ "resource": "" }
q278411
MetaField.metadata
test
def metadata(self): """ Returns metadata as a dataframe. """ return pd.Series({ "part": self.part, "step_num": self.step_num, "step_label": self.step_label, "frame": self.frame, "frame_value": self.frame_value, "label": self.label, ...
python
{ "resource": "" }
q278412
Model.make_directories
test
def make_directories(self): """ Checks if required directories exist and creates them if needed. """ if os.path.isdir(self.workdir) == False: os.mkdir(self.workdir)
python
{ "resource": "" }
q278413
Model.run_postproc
test
def run_postproc(self): """ Runs the post-proc script. """ t0 = time.time() if self.verbose: print('#### POST-PROCESSING "{0}" USING POST-PROCESSOR "{1}"'.format(self.label, self.solver.upper())) if self.solver == "abaqus": command =...
python
{ "resource": "" }
q278414
Part.run_gmsh
test
def run_gmsh(self): """ Makes the mesh using gmsh. """ argiope.utils.run_gmsh(gmsh_path = self.gmsh_path, gmsh_space = self.gmsh_space, gmsh_options = self.gmsh_options, name = self.file_name + ".geo", ...
python
{ "resource": "" }
q278415
read_history_report
test
def read_history_report(path, steps, x_name = None): """ Reads an history output report. """ data = pd.read_csv(path, delim_whitespace = True) if x_name != None: data[x_name] = data.X del data["X"] data["step"] = 0 t = 0. for i in range(len(steps)): dt = steps[i].duration loc = data...
python
{ "resource": "" }
q278416
read_field_report
test
def read_field_report(path, data_flag = "*DATA", meta_data_flag = "*METADATA"): """ Reads a field output report. """ text = open(path).read() mdpos = text.find(meta_data_flag) dpos = text.find(data_flag) mdata = io.StringIO( "\n".join(text[mdpos:dpos].split("\n")[1:])) data = io.StringIO( "\n".join(text...
python
{ "resource": "" }
q278417
list_to_string
test
def list_to_string(l = range(200), width = 40, indent = " "): """ Converts a list-like to string with given line width. """ l = [str(v) + "," for v in l] counter = 0 out = "" + indent for w in l: s = len(w) if counter + s > width: out += "\n" + indent ...
python
{ "resource": "" }
q278418
_equation
test
def _equation(nodes = (1, 2), dofs = (1, 1), coefficients = (1., 1.), comment = None): """ Returns an Abaqus INP formated string for a given linear equation. """ N = len(nodes) if comment == None: out = "" else: out = "**EQUATION: {0}\n".format(comment) out+= "*E...
python
{ "resource": "" }
q278419
_unsorted_set
test
def _unsorted_set(df, label, **kwargs): """ Returns a set as inp string with unsorted option. """ out = "*NSET, NSET={0}, UNSORTED\n".format(label) labels = df.index.values return out + argiope.utils.list_to_string(labels, **kwargs)
python
{ "resource": "" }
q278420
PhaxioApi.parse_response
test
def parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True :param response: response from requests http call :returns: dictionary of response :rtype: dict """ payload = None try: ...
python
{ "resource": "" }
q278421
PhaxioApi._get
test
def _get(self, method, **kwargs): """Builds the url for the specified method and arguments and returns the response as a dictionary. """ payload = kwargs.copy() payload['api_key'] = self.api_key payload['api_secret'] = self.api_secret to = payload.pop('to', None...
python
{ "resource": "" }
q278422
write_xy_report
test
def write_xy_report(odb, path, tags, columns, steps): """ Writes a xy_report based on xy data. """ xyData = [session.XYDataFromHistory(name = columns[i], odb = odb, outputVariableName = tags[i], steps = steps) for i in xrange(len(tags))]...
python
{ "resource": "" }
q278423
write_field_report
test
def write_field_report(odb, path, label, argiope_class, variable, instance, output_position, step = -1, frame = -1, sortItem='Node Label'): """ Writes a field report and rewrites it in a cleaner format. """ stepKeys = get_steps(odb) step = xrange(len(stepKeys))[step] frame = xrange(g...
python
{ "resource": "" }
q278424
list
test
def list(component_type): """List components that are available on your machine""" config_loader = initialise_component_loader() component_types = sorted({ "displays": lambda: config_loader.load_by_type(ComponentType.DISPLAY), "datafeeds": lambda: config_loader.load_by_type(ComponentType.D...
python
{ "resource": "" }
q278425
Descriptor.err_msg
test
def err_msg(self, instance, value): """Return an error message for use in exceptions thrown by subclasses. """ if not hasattr(self, "name"): # err_msg will be called by the composed descriptor return "" return ( "Attempted to set the {f_type} ...
python
{ "resource": "" }
q278426
Descriptor.exc_thrown_by_descriptor
test
def exc_thrown_by_descriptor(): """Return True if the last exception was thrown by a Descriptor instance. """ traceback = sys.exc_info()[2] tb_locals = traceback.tb_frame.f_locals # relying on naming convention to get the object that threw # the exception ...
python
{ "resource": "" }
q278427
Series._set_data
test
def _set_data(self): """ This method will be called to set Series data """ if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False): _x = XVariable() _y = YVariable() _x.contribute_to_class(self, 'X', self.d...
python
{ "resource": "" }
q278428
Graph._get_axis_mode
test
def _get_axis_mode(self, axis): "will get the axis mode for the current series" if all([isinstance(getattr(s, axis), TimeVariable) for s in self._series]): return 'time' return None
python
{ "resource": "" }
q278429
Graph._set_options
test
def _set_options(self): "sets the graph ploting options" # this is aweful # FIXME: Axis options should be passed completly by a GraphOption if 'xaxis' in self._options.keys(): self._options['xaxis'].update( {'mode' : self._get_axis_mode(XAxis._var_name...
python
{ "resource": "" }
q278430
make_class
test
def make_class(clsname, func, attrs): """Turn a funcs list element into a class object.""" clsdict = {"__set__": create_setter(func, attrs)} if len(attrs) > 0: clsdict["__init__"] = create_init(attrs) clsobj = type(str(clsname), (Descriptor, ), clsdict) clsobj.__doc__ = docstrings.get(clsnam...
python
{ "resource": "" }
q278431
DashboardRunner.cycle
test
def cycle(self): """ Cycles through notifications with latest results from data feeds. """ messages = self.poll_datafeeds() notifications = self.process_notifications(messages) self.draw_notifications(notifications)
python
{ "resource": "" }
q278432
ForceNumeric.try_convert
test
def try_convert(value): """Convert value to a numeric value or raise a ValueError if that isn't possible. """ convertible = ForceNumeric.is_convertible(value) if not convertible or isinstance(value, bool): raise ValueError if isinstance(str(value), str): ...
python
{ "resource": "" }
q278433
ForceNumeric.str_to_num
test
def str_to_num(str_value): """Convert str_value to an int or a float, depending on the numeric value represented by str_value. """ str_value = str(str_value) try: return int(str_value) except ValueError: return float(str_value)
python
{ "resource": "" }
q278434
plot
test
def plot(parser, token): """ Tag to plot graphs into the template """ tokens = token.split_contents() tokens.pop(0) graph = tokens.pop(0) attrs = dict([token.split("=") for token in tokens]) if 'id' not in attrs.keys(): attrs['id'] = ''.join([chr(choice(range(65, 90))) for i i...
python
{ "resource": "" }
q278435
force_unicode
test
def force_unicode(raw): '''Try really really hard to get a Unicode copy of a string. First try :class:`BeautifulSoup.UnicodeDammit` to try to force to Unicode; if that fails, assume UTF-8 encoding, and ignore all errors. :param str raw: string to coerce :return: Unicode approximation of `raw` ...
python
{ "resource": "" }
q278436
make_clean_html
test
def make_clean_html(raw, stream_item=None, encoding=None): '''Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode....
python
{ "resource": "" }
q278437
clean_html.is_matching_mime_type
test
def is_matching_mime_type(self, mime_type): '''This implements the MIME-type matching logic for deciding whether to run `make_clean_html` ''' if len(self.include_mime_types) == 0: return True if mime_type is None: return False mime_type = mime_typ...
python
{ "resource": "" }
q278438
domain_name_cleanse
test
def domain_name_cleanse(raw_string): '''extract a lower-case, no-slashes domain name from a raw string that might be a URL ''' try: parts = urlparse(raw_string) domain = parts.netloc.split(':')[0] except: domain = '' if not domain: domain = raw_string if not d...
python
{ "resource": "" }
q278439
domain_name_left_cuts
test
def domain_name_left_cuts(domain): '''returns a list of strings created by splitting the domain on '.' and successively cutting off the left most portion ''' cuts = [] if domain: parts = domain.split('.') for i in range(len(parts)): cuts.append( '.'.join(parts[i:])) r...
python
{ "resource": "" }
q278440
keyword_indexer.make_hash_kw
test
def make_hash_kw(self, tok): '''Get a Murmur hash and a normalized token. `tok` may be a :class:`unicode` string or a UTF-8-encoded byte string. :data:`DOCUMENT_HASH_KEY`, hash value 0, is reserved for the document count, and this function remaps that value. :param tok...
python
{ "resource": "" }
q278441
keyword_indexer.collect_words
test
def collect_words(self, si): '''Collect all of the words to be indexed from a stream item. This scans `si` for all of the configured tagger IDs. It collects all of the token values (the :attr:`streamcorpus.Token.token`) and returns a :class:`collections.Counter` of them. ...
python
{ "resource": "" }
q278442
keyword_indexer.index
test
def index(self, si): '''Record index records for a single document. Which indexes this creates depends on the parameters to the constructor. This records all of the requested indexes for a single document. ''' if not si.body.clean_visible: logger.warn('stre...
python
{ "resource": "" }
q278443
keyword_indexer.invert_hash
test
def invert_hash(self, tok_hash): '''Get strings that correspond to some hash. No string will correspond to :data:`DOCUMENT_HASH_KEY`; use :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead. :param int tok_hash: Murmur hash to query :return: list of :class:`unicode` strings ...
python
{ "resource": "" }
q278444
keyword_indexer.document_frequencies
test
def document_frequencies(self, hashes): '''Get document frequencies for a list of hashes. This will return all zeros unless the index was written with `hash_frequencies` set. If :data:`DOCUMENT_HASH_KEY` is included in `hashes`, that value will be returned with the total number...
python
{ "resource": "" }
q278445
keyword_indexer.lookup
test
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a ...
python
{ "resource": "" }
q278446
keyword_indexer.lookup_tf
test
def lookup_tf(self, h): '''Get stream IDs and term frequencies for a single hash. This yields pairs of strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item` and the corresponding term frequency. ..see:: :meth:`lookup` ''' ...
python
{ "resource": "" }
q278447
_make_stream_items
test
def _make_stream_items(f): """Given a spinn3r feed, produce a sequence of valid StreamItems. Because of goopy Python interactions, you probably need to call this and re-yield its results, as >>> with open(filename, 'rb') as f: ... for si in _make_stream_items(f): ... yield si """ ...
python
{ "resource": "" }
q278448
_make_stream_item
test
def _make_stream_item(entry): """Given a single spinn3r feed entry, produce a single StreamItem. Returns 'None' if a complete item can't be constructed. """ # get standard metadata, assuming it's present... if not hasattr(entry, 'permalink_entry'): return None pe = entry.permalink_entr...
python
{ "resource": "" }
q278449
_make_content_item
test
def _make_content_item(node, mime_type=None, alternate_data=None): """Create a ContentItem from a node in the spinn3r data tree. The ContentItem is created with raw data set to ``node.data``, decompressed if the node's encoding is 'zlib', and UTF-8 normalized, with a MIME type from ``node.mime_type``. ...
python
{ "resource": "" }
q278450
ProtoStreamReader._read_varint
test
def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) return n
python
{ "resource": "" }
q278451
ProtoStreamReader._read_a
test
def _read_a(self, cls): """Read some protobuf-encoded object stored in a single block out of the file.""" o = cls() o.ParseFromString(self._read_block()) return o
python
{ "resource": "" }
q278452
serialize_si_key
test
def serialize_si_key(si_key): ''' Return packed bytes representation of StreamItem kvlayer key. The result is 20 bytes, 16 of md5 hash, 4 of int timestamp. ''' if len(si_key[0]) != 16: raise ValueError('bad StreamItem key, expected 16 byte ' 'md5 hash binary digest, ...
python
{ "resource": "" }
q278453
streamitem_to_key_data
test
def streamitem_to_key_data(si): ''' extract the parts of a StreamItem that go into a kvlayer key, convert StreamItem to blob for storage. return (kvlayer key tuple), data blob ''' key = key_for_stream_item(si) data = streamcorpus.serialize(si) errors, data = streamcorpus.compress_and_en...
python
{ "resource": "" }
q278454
working_directory
test
def working_directory(path): """Change working directory and restore the previous on exit""" prev_dir = os.getcwd() os.chdir(str(path)) try: yield finally: os.chdir(prev_dir)
python
{ "resource": "" }
q278455
strip_prefix
test
def strip_prefix(s, prefix, strict=False): """Removes the prefix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the prefix was present""" if s.startswith(prefix): return s[len(prefix) :] elif strict: raise WimpyError("string doesn't start with p...
python
{ "resource": "" }
q278456
strip_suffix
test
def strip_suffix(s, suffix, strict=False): """Removes the suffix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the suffix was present""" if s.endswith(suffix): return s[: len(s) - len(suffix)] elif strict: raise WimpyError("string doesn't end w...
python
{ "resource": "" }
q278457
is_subsequence
test
def is_subsequence(needle, haystack): """Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout""" it = iter(haystack) for element in needle: if element not in it: return False return True
python
{ "resource": "" }
q278458
cube
test
def cube(): """Return an Ice application with a default home page. Create :class:`Ice` object, add a route to return the default page when a client requests the server root, i.e. /, using HTTP GET method, add an error handler to return HTTP error pages when an error occurs and return this object. T...
python
{ "resource": "" }
q278459
Ice.run
test
def run(self, host='127.0.0.1', port=8080): """Run the application using a simple WSGI server. Arguments: host (str, optional): Host on which to listen. port (int, optional): Port number on which to listen. """ from wsgiref import simple_server self._server =...
python
{ "resource": "" }
q278460
Ice.exit
test
def exit(self): """Stop the simple WSGI server running the appliation.""" if self._server is not None: self._server.shutdown() self._server.server_close() self._server = None
python
{ "resource": "" }
q278461
Ice.route
test
def route(self, method, pattern): """Decorator to add route for a request with any HTTP method. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. pattern (str): Routing pattern the path must match. Returns: function: Decorator function to add route. ...
python
{ "resource": "" }
q278462
Ice.error
test
def error(self, status=None): """Decorator to add a callback that generates error page. The *status* parameter specifies the HTTP response status code for which the decorated callback should be invoked. If the *status* argument is not specified, then the decorated callable is co...
python
{ "resource": "" }
q278463
Ice.static
test
def static(self, root, path, media_type=None, charset='UTF-8'): """Send content of a static file as response. The path to the document root directory should be specified as the root argument. This is very important to prevent directory traversal attack. This method guarantees that only ...
python
{ "resource": "" }
q278464
Ice._get_error_page_callback
test
def _get_error_page_callback(self): """Return an error page for the current response status.""" if self.response.status in self._error_handlers: return self._error_handlers[self.response.status] elif None in self._error_handlers: return self._error_handlers[None] ...
python
{ "resource": "" }
q278465
Router.add
test
def add(self, method, pattern, callback): """Add a route. Arguments: method (str): HTTP method, e.g. GET, POST, etc. pattern (str): Pattern that request paths must match. callback (str): Route handler that is invoked when a request path matches the *pattern*. ...
python
{ "resource": "" }
q278466
Router.resolve
test
def resolve(self, method, path): """Resolve a request to a route handler. Arguments: method (str): HTTP method, e.g. GET, POST, etc. (type: str) path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) ...
python
{ "resource": "" }
q278467
Router._resolve_non_literal_route
test
def _resolve_non_literal_route(self, method, path): """Resolve a request to a wildcard or regex route handler. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. path (str): Request path Returns: tuple or None: A tuple of three items: 1. ...
python
{ "resource": "" }
q278468
Router._normalize_pattern
test
def _normalize_pattern(pattern): """Return a normalized form of the pattern. Normalize the pattern by removing pattern type prefix if it exists in the pattern. Then return the pattern type and the pattern as a tuple of two strings. Arguments: pattern (str): Route patt...
python
{ "resource": "" }
q278469
Response.response
test
def response(self): """Return the HTTP response body. Returns: bytes: HTTP response body as a sequence of bytes """ if isinstance(self.body, bytes): out = self.body elif isinstance(self.body, str): out = self.body.encode(self.charset) el...
python
{ "resource": "" }
q278470
Response.add_header
test
def add_header(self, name, value): """Add an HTTP header to response object. Arguments: name (str): HTTP header field name value (str): HTTP header field value """ if value is not None: self._headers.append((name, value))
python
{ "resource": "" }
q278471
Response.set_cookie
test
def set_cookie(self, name, value, attrs={}): """Add a Set-Cookie header to response object. For a description about cookie attribute values, see https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel. Arguments: name (str): Name of the cookie value ...
python
{ "resource": "" }
q278472
Response.status_line
test
def status_line(self): """Return the HTTP response status line. The status line is determined from :attr:`status` code. For example, if the status code is 200, then '200 OK' is returned. Returns: str: Status line """ return (str(self.status) + ' ' + ...
python
{ "resource": "" }
q278473
Response.content_type
test
def content_type(self): """Return the value of Content-Type header field. The value for the Content-Type header field is determined from the :attr:`media_type` and :attr:`charset` data attributes. Returns: str: Value of Content-Type header field """ if (self.m...
python
{ "resource": "" }
q278474
MultiDict.getall
test
def getall(self, key, default=[]): """Return the list of all values for the specified key. Arguments: key (object): Key default (list): Default value to return if the key does not exist, defaults to ``[]``, i.e. an empty list. Returns: list: List of al...
python
{ "resource": "" }
q278475
rmtree
test
def rmtree(path, use_shutil=True, followlinks=False, retries=10): '''remove all files and directories below path, including path itself; works even when shutil.rmtree fails because of read-only files in NFS and Windows. Follows symlinks. `use_shutil` defaults to True; useful for testing `followli...
python
{ "resource": "" }
q278476
get_open_fds
test
def get_open_fds(verbose=False): '''return list of open files for current process .. warning: will only work on UNIX-like os-es. ''' pid = os.getpid() procs = subprocess.check_output( [ "lsof", '-w', '-Ff', "-p", str( pid ) ] ) if verbose: oprocs = subprocess.check_output( ...
python
{ "resource": "" }
q278477
file_type_stats
test
def file_type_stats(config): ''' returns a kba.pipeline "transform" function that generates file type stats from the stream_items that it sees. Currently, these stats are just the first five non-whitespace characters. ''' ## make a closure around config def _file_type_stats(stream_item, con...
python
{ "resource": "" }
q278478
rejester_run
test
def rejester_run(work_unit): '''get a rejester.WorkUnit with KBA s3 path, fetch it, and save some counts about it. ''' #fname = 'verify-chunks-%d-%d' % (os.getpid(), time.time()) fname = work_unit.key.strip().split('/')[-1] output_dir_path = work_unit.data.get('output_dir_path', '/mn...
python
{ "resource": "" }
q278479
attempt_fetch
test
def attempt_fetch(work_unit, fpath): '''attempt a fetch and iteration over a work_unit.key path in s3 ''' url = 'http://s3.amazonaws.com/aws-publicdatasets/' + work_unit.key.strip() ## cheapest way to iterate over the corpus is a few stages of ## streamed child processes. Note that stderr nee...
python
{ "resource": "" }
q278480
get_file_lines
test
def get_file_lines(file_name): """Return a list of non-empty lines from `file_path`.""" file_path = path.join(path.dirname(path.abspath(__file__)), file_name) with open(file_path) as file_obj: return [line for line in file_obj.read().splitlines() if line]
python
{ "resource": "" }
q278481
_random_adjspecies_pair
test
def _random_adjspecies_pair(): """Return an ordered 2-tuple containing a species and a describer.""" describer, desc_position = random_describer() if desc_position == 'prefix': return (describer, random_species()) elif desc_position == 'suffix': return (random_species(), describer)
python
{ "resource": "" }
q278482
random_adjspecies_pair
test
def random_adjspecies_pair(maxlen=None, prevent_stutter=True): """ Return an ordered 2-tuple containing a species and a describer. The letter-count of the pair is guarantee to not exceed `maxlen` if it is given. If `prevent_stutter` is True, the last letter of the first item of the pair will be diff...
python
{ "resource": "" }
q278483
morph
test
def morph(ctx, app_id, sentence_file, json_flag, sentence, info_filter, pos_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode, unicode) -> None # NOQA """ Morphological analysis for Japanese.""" app_id = clean_app_id(app_id) sentence = clean_senten...
python
{ "resource": "" }
q278484
similarity
test
def similarity(ctx, app_id, json_flag, query_pair, request_id): # type: (Context, unicode, bool, List[unicode], unicode) -> None """ Scoring the similarity of two words. """ app_id = clean_app_id(app_id) api = GoolabsAPI(app_id) ret = api.similarity( query_pair=query_pair, request_...
python
{ "resource": "" }
q278485
hiragana
test
def hiragana(ctx, app_id, sentence_file, json_flag, sentence, output_type, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Convert the Japanese to Hiragana or Katakana. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sen...
python
{ "resource": "" }
q278486
entity
test
def entity(ctx, app_id, sentence_file, json_flag, sentence, class_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Extract unique representation from sentence. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sentenc...
python
{ "resource": "" }
q278487
shortsum
test
def shortsum(ctx, app_id, review_file, json_flag, review, length, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Summarize reviews into a short summary.""" app_id = clean_app_id(app_id) review_list = clean_review(review, review_file...
python
{ "resource": "" }
q278488
keyword
test
def keyword(ctx, app_id, body_file, json_flag, title, body, max_num, forcus, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, int, unicode, unicode) -> None # NOQA """Extract "keywords" from an input document. """ app_id = clean_app_id(app_id) body = clean_body(...
python
{ "resource": "" }
q278489
chrono
test
def chrono(ctx, app_id, sentence_file, json_flag, sentence, doc_time, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Extract expression expressing date and time and normalize its value """ app_id = clean_app_id(app_id) sentence = cle...
python
{ "resource": "" }
q278490
PipelineFactory.create
test
def create(self, stage, scp_config, config=None): '''Create a pipeline stage. Instantiates `stage` with `config`. This essentially translates to ``stage(config)``, except that two keys from `scp_config` are injected into the configuration: ``tmp_dir_path`` is an execution-speci...
python
{ "resource": "" }
q278491
PipelineFactory._init_stages
test
def _init_stages(self, config, name): '''Create a list of indirect stages. `name` should be the name of a config item that holds a list of names of stages, for instance, ``writers``. This looks up the names of those stages, then creates and returns the corresponding list of sta...
python
{ "resource": "" }
q278492
PipelineFactory._init_all_stages
test
def _init_all_stages(self, config): '''Create stages that are used for the pipeline. :param dict config: `streamcorpus_pipeline` configuration :return: tuple of (reader, incremental transforms, batch transforms, post-batch incremental transforms, writers, temporary directory...
python
{ "resource": "" }
q278493
Pipeline.run
test
def run(self, i_str, start_count=0, start_chunk_time=None): '''Run the pipeline. This runs all of the steps described in the pipeline constructor, reading from some input and writing to some output. :param str i_str: name of the input file, or other reader-specific descriptio...
python
{ "resource": "" }
q278494
Pipeline._run_writers
test
def _run_writers(self, start_count, next_idx, sources, i_str, t_path): '''Run all of the writers over some intermediate chunk. :param int start_count: index of the first item :param int next_idx: index of the next item (after the last item in this chunk) :param list sources: s...
python
{ "resource": "" }
q278495
Pipeline._run_incremental_transforms
test
def _run_incremental_transforms(self, si, transforms): ''' Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None. ''' ## operate each transform on this one Strea...
python
{ "resource": "" }
q278496
replace_config
test
def replace_config(config, name): '''Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_...
python
{ "resource": "" }
q278497
make_app
test
def make_app(): """Make a WSGI app that has all the HTTPie pieces baked in.""" env = Environment() # STDIN is ignored because HTTPony runs a server that doesn't care. # Additionally, it is needed or else pytest blows up. args = parser.parse_args(args=['/', '--ignore-stdin'], env=env) args.output...
python
{ "resource": "" }
q278498
make_chains_with_names
test
def make_chains_with_names(sentences): ''' assemble in-doc coref chains by mapping equiv_id to tokens and their cleansed name strings :param sentences: iterator over token generators :returns dict: keys are equiv_ids, values are tuple(concatentated name string, list of tokens) '...
python
{ "resource": "" }
q278499
ALL_mentions
test
def ALL_mentions(target_mentions, chain_mentions): ''' For each name string in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains the name. Returns True only if all of the target_mention strings appeared as substrings of at least one cle...
python
{ "resource": "" }