sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def post(self, action, data=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='POST', data=data, headers=headers)
Makes a GET request
entailment
def delete(self, action, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='DELETE', headers=headers)
Makes a GET request
entailment
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000): """ Calculates a good piece size for a size """ logger.debug('Calculating piece size for %i' % size) for i in range(min_piece_size, max_piece_size): # 20 = 1MB if size / (2**i) < max_piece_count: ...
Calculates a good piece size for a size
entailment
def split_pieces(piece_list, segments, num): """ Prepare a list of all pieces grouped together """ piece_groups = [] pieces = list(piece_list) while pieces: for i in range(segments): p = pieces[i::segments][:num] if not p: break piece_g...
Prepare a list of all pieces grouped together
entailment
def rglob(dirname, pattern, dirs=False, sort=True): """recursive glob, gets all files that match the pattern within the directory tree""" fns = [] path = str(dirname) if os.path.isdir(path): fns = glob(os.path.join(escape(path), pattern)) dns = [fn for fn in [os.p...
recursive glob, gets all files that match the pattern within the directory tree
entailment
def after(parents, func=None): '''Create a new Future whose completion depends on parent futures The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in which the dependent future's ...
Create a new Future whose completion depends on parent futures The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in which the dependent future's callback returns a future or list of...
entailment
def wait_any(futures, timeout=None): '''Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One o...
Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One of the futures from the provided list -- the ...
entailment
def wait_all(futures, timeout=None): '''Wait for the completion of all futures in a list :param list future: a list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, can block indefinitely. :type timeout: float or None :raises WaitTimeout: if a timeout is provid...
Wait for the completion of all futures in a list :param list future: a list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, can block indefinitely. :type timeout: float or None :raises WaitTimeout: if a timeout is provided and hit
entailment
def value(self): '''The final value, if it has arrived :raises: AttributeError, if not yet complete :raises: an exception if the Future was :meth:`abort`\ed ''' if not self._done.is_set(): raise AttributeError("value") if self._failure: raise self...
The final value, if it has arrived :raises: AttributeError, if not yet complete :raises: an exception if the Future was :meth:`abort`\ed
entailment
def finish(self, value): '''Give the future it's value and trigger any associated callbacks :param value: the new value for the future :raises: :class:`AlreadyComplete <junction.errors.AlreadyComplete>` if already complete ''' if self._done.is_set(): ...
Give the future it's value and trigger any associated callbacks :param value: the new value for the future :raises: :class:`AlreadyComplete <junction.errors.AlreadyComplete>` if already complete
entailment
def abort(self, klass, exc, tb=None): '''Finish this future (maybe early) in an error state Takes a standard exception triple as arguments (like returned by ``sys.exc_info``) and will re-raise them as the value. Any :class:`Dependents` that are children of this one will also be ...
Finish this future (maybe early) in an error state Takes a standard exception triple as arguments (like returned by ``sys.exc_info``) and will re-raise them as the value. Any :class:`Dependents` that are children of this one will also be aborted. :param class klass: the class ...
entailment
def on_finish(self, func): '''Assign a callback function to be run when successfully complete :param function func: A callback to run when complete. It will be given one argument (the value that has arrived), and it's return value is ignored. ''' if self._done.is...
Assign a callback function to be run when successfully complete :param function func: A callback to run when complete. It will be given one argument (the value that has arrived), and it's return value is ignored.
entailment
def on_abort(self, func): '''Assign a callback function to be run when :meth:`abort`\ed :param function func: A callback to run when aborted. It will be given three arguments: - ``klass``: the exception class - ``exc``: the exception instance ...
Assign a callback function to be run when :meth:`abort`\ed :param function func: A callback to run when aborted. It will be given three arguments: - ``klass``: the exception class - ``exc``: the exception instance - ``tb``: the traceback object assoc...
entailment
def after(self, func=None, other_parents=None): '''Create a new Future whose completion depends on this one The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in whic...
Create a new Future whose completion depends on this one The new future will have a function that it calls once all its parents have completed, the return value of which will be its final value. There is a special case, however, in which the dependent future's callback returns a future ...
entailment
def partial_results(self): '''The results that the RPC has received *so far* This may also be the complete results if :attr:`complete` is ``True``. ''' results = [] for r in self._results: if isinstance(r, Exception): results.append(type(r)(*deepcopy(...
The results that the RPC has received *so far* This may also be the complete results if :attr:`complete` is ``True``.
entailment
def os_path_transform(self, s, sep=os.path.sep): """ transforms any os path into unix style """ if sep == '/': return s else: return s.replace(sep, '/')
transforms any os path into unix style
entailment
def transform(self, tr_list, files): """ replaces $tokens$ with values will be replaced with config rendering """ singular = False if not isinstance(files, list) and not isinstance(files, tuple): singular = True files = [files] for _find, ...
replaces $tokens$ with values will be replaced with config rendering
entailment
def resolve_dst(self, dst_dir, src): """ finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to base dst_dir """ if os.path.isabs(src): return os.path.join(dst_dir, os.path.basename(src)) return os.pa...
finds the destination based on source if source is an absolute path, and there's no pattern, it copies the file to base dst_dir
entailment
def write(self, fn=None): """copy the zip file from its filename to the given filename.""" fn = fn or self.fn if not os.path.exists(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) f = open(self.fn, 'rb') b = f.read() f.close() f = open(fn, 'wb')...
copy the zip file from its filename to the given filename.
entailment
def assign(self, attrs): """Merge new attributes """ for k, v in attrs.items(): setattr(self, k, v)
Merge new attributes
entailment
def normalize_rust_function(self, function, line): """Normalizes a single rust frame with a function""" # Drop the prefix and return type if there is any function = drop_prefix_and_return_type(function) # Collapse types function = collapse( function, open...
Normalizes a single rust frame with a function
entailment
def normalize_cpp_function(self, function, line): """Normalizes a single cpp frame with a function""" # Drop member function cv/ref qualifiers like const, const&, &, and && for ref in ('const', 'const&', '&&', '&'): if function.endswith(ref): function = function[:-len...
Normalizes a single cpp frame with a function
entailment
def normalize_frame( self, module=None, function=None, file=None, line=None, module_offset=None, offset=None, normalized=None, **kwargs # eat any extra kwargs passed in ): """Normalizes a single frame Returns a structured cong...
Normalizes a single frame Returns a structured conglomeration of the input parameters to serve as a signature. The parameter names of this function reflect the exact names of the fields from the jsonMDSW frame output. This allows this function to be invoked by passing a frame as ``**a_f...
entailment
def _do_generate(self, source_list, hang_type, crashed_thread, delimiter=' | '): """ each element of signatureList names a frame in the crash stack; and is: - a prefix of a relevant frame: Append this element to the signature - a relevant frame: Append this element and stop looking ...
each element of signatureList names a frame in the crash stack; and is: - a prefix of a relevant frame: Append this element to the signature - a relevant frame: Append this element and stop looking - irrelevant: Append this element only after seeing a prefix frame The signature is ...
entailment
def _clean_tag(t): """Fix up some garbage errors.""" # TODO: when score present, include info. t = _scored_patt.sub(string=t, repl='') if t == '_country_' or t.startswith('_country:'): t = 'nnp_country' elif t == 'vpb': t = 'vb' # "carjack" is listed with vpb tag. elif t == 'nnd...
Fix up some garbage errors.
entailment
def local_settings(settings, prefix): """Localizes the settings for the dotted prefix. For example, if the prefix where 'xyz':: {'xyz.foo': 'bar', 'other': 'something'} Would become:: {'foo': 'bar'} Note, that non-prefixed items are left out and the prefix is dropped. """ pre...
Localizes the settings for the dotted prefix. For example, if the prefix where 'xyz':: {'xyz.foo': 'bar', 'other': 'something'} Would become:: {'foo': 'bar'} Note, that non-prefixed items are left out and the prefix is dropped.
entailment
def humanize_bytes(bytes, precision=1): """Return a humanized string representation of a number of bytes. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*1234...
Return a humanized string representation of a number of bytes. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12...
entailment
def parent(self): """return the parent URL, with params, query, and fragment in place""" path = '/'.join(self.path.split('/')[:-1]) s = path.strip('/').split(':') if len(s)==2 and s[1]=='': return None else: return self.__class__(self, path=path)
return the parent URL, with params, query, and fragment in place
entailment
def join(C, *args, **kwargs): """join a list of url elements, and include any keyword arguments, as a new URL""" u = C('/'.join([str(arg).strip('/') for arg in args]), **kwargs) return u
join a list of url elements, and include any keyword arguments, as a new URL
entailment
def select_peer(peer_addrs, service, routing_id, method): '''Choose a target from the available peers for a singular message :param peer_addrs: the ``(host, port)``s of the peers eligible to handle the RPC, and possibly a ``None`` entry if this hub can handle it locally :type peer_addrs: li...
Choose a target from the available peers for a singular message :param peer_addrs: the ``(host, port)``s of the peers eligible to handle the RPC, and possibly a ``None`` entry if this hub can handle it locally :type peer_addrs: list :param service: the service of the message :type servi...
entailment
def setup(app): """Setup the sphinx extension This will setup autodoc and autosummary. Add the :class:`ext.ModDocstringDocumenter`. Add the config values. Connect builder-inited event to :func:`gendoc.main`. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` ...
Setup the sphinx extension This will setup autodoc and autosummary. Add the :class:`ext.ModDocstringDocumenter`. Add the config values. Connect builder-inited event to :func:`gendoc.main`. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None ...
entailment
def start(self, key=None, **params): """initialize process timing for the current stack""" self.params.update(**params) key = key or self.stack_key if key is not None: self.current_times[key] = time()
initialize process timing for the current stack
entailment
def report(self, fraction=None): """report the total progress for the current stack, optionally given the local fraction completed. fraction=None: if given, used as the fraction of the local method so far completed. runtimes=None: if given, used as the expected runtimes for the current stack. """ r = Dict() ...
report the total progress for the current stack, optionally given the local fraction completed. fraction=None: if given, used as the fraction of the local method so far completed. runtimes=None: if given, used as the expected runtimes for the current stack.
entailment
def finish(self): """record the current stack process as finished""" self.report(fraction=1.0) key = self.stack_key if key is not None: if self.data.get(key) is None: self.data[key] = [] start_time = self.current_times.get(key) or time() self.data[key].append(Dict(runtime=time()-start_time, **self....
record the current stack process as finished
entailment
def add_directive_header(self, sig): """Add the directive header and options to the generated content.""" domain = getattr(self, 'domain', 'py') directive = getattr(self, 'directivetype', "module") name = self.format_name() self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, n...
Add the directive header and options to the generated content.
entailment
def connect(self): "Initiate the connection to a proxying hub" log.info("connecting") # don't have the connection attempt reconnects, because when it goes # down we are going to cycle to the next potential peer from the Client self._peer = connection.Peer( None, ...
Initiate the connection to a proxying hub
entailment
def wait_connected(self, timeout=None): '''Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were mad...
Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were made, ``False`` if one or more failed.
entailment
def reset(self): "Close the current failed connection and prepare for a new one" log.info("resetting client") rpc_client = self._rpc_client self._addrs.append(self._peer.addr) self.__init__(self._addrs) self._rpc_client = rpc_client self._dispatcher.rpc_client = r...
Close the current failed connection and prepare for a new one
entailment
def shutdown(self): 'Close the hub connection' log.info("shutting down") self._peer.go_down(reconnect=False, expected=True)
Close the hub connection
entailment
def publish(self, service, routing_id, method, args=None, kwargs=None, broadcast=False): '''Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the regis...
Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the registered handlers of the service. :type routing_id: int :param method: the method name ...
entailment
def publish_receiver_count( self, service, routing_id, method, timeout=None): '''Get the number of peers that would handle a particular publish This method will block until a response arrives :param service: the service name :type service: anything hash-able :param ...
Get the number of peers that would handle a particular publish This method will block until a response arrives :param service: the service name :type service: anything hash-able :param routing_id: the id used for narrowing within the service handlers :type routing_i...
entailment
def send_rpc(self, service, routing_id, method, args=None, kwargs=None, broadcast=False): '''Send out an RPC request :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the r...
Send out an RPC request :param service: the service name (the routing top level) :type service: anything hash-able :param routing_id: The id used for routing within the registered handlers of the service. :type routing_id: int :param method: the method na...
entailment
def rpc_receiver_count(self, service, routing_id, method, timeout=None): '''Get the number of peers that would handle a particular RPC This method will block until a response arrives :param service: the service name :type service: anything hash-able :param routing_id: ...
Get the number of peers that would handle a particular RPC This method will block until a response arrives :param service: the service name :type service: anything hash-able :param routing_id: the id used for narrowing within the service handlers :type routing_id: i...
entailment
def _headers(self, others={}): """Return the default headers and others as necessary""" headers = { 'Content-Type': 'application/json' } for p in others.keys(): headers[p] = others[p] return headers
Return the default headers and others as necessary
entailment
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True): ''' Read the config file with spec validation ''' # configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec), # encoding='UTF8', # ...
Read the config file with spec validation
entailment
def elapsed_time_string(start_time, stop_time): r""" Return a formatted string with the elapsed time between two time points. The string includes years (365 days), months (30 days), days (24 hours), hours (60 minutes), minutes (60 seconds) and seconds. If both arguments are equal, the string return...
r""" Return a formatted string with the elapsed time between two time points. The string includes years (365 days), months (30 days), days (24 hours), hours (60 minutes), minutes (60 seconds) and seconds. If both arguments are equal, the string returned is :code:`'None'`; otherwise, the string retu...
entailment
def pcolor(text, color, indent=0): r""" Return a string that once printed is colorized. :param text: Text to colorize :type text: string :param color: Color to use, one of :code:`'black'`, :code:`'red'`, :code:`'green'`, :code:`'yellow'`, :code:`'blue'`, :co...
r""" Return a string that once printed is colorized. :param text: Text to colorize :type text: string :param color: Color to use, one of :code:`'black'`, :code:`'red'`, :code:`'green'`, :code:`'yellow'`, :code:`'blue'`, :code:`'magenta'`, :code:`'cyan'`, :code:`...
entailment
def quote_str(obj): r""" Add extra quotes to a string. If the argument is not a string it is returned unmodified. :param obj: Object :type obj: any :rtype: Same as argument For example: >>> import pmisc >>> pmisc.quote_str(5) 5 >>> pmisc.quote_str('Hello...
r""" Add extra quotes to a string. If the argument is not a string it is returned unmodified. :param obj: Object :type obj: any :rtype: Same as argument For example: >>> import pmisc >>> pmisc.quote_str(5) 5 >>> pmisc.quote_str('Hello!') '"Hello!"' ...
entailment
def strframe(obj, extended=False): """ Return a string with a frame record pretty-formatted. The record is typically an item in a list generated by `inspect.stack() <https://docs.python.org/3/library/inspect.html#inspect.stack>`_). :param obj: Frame record :type obj: tuple :param extende...
Return a string with a frame record pretty-formatted. The record is typically an item in a list generated by `inspect.stack() <https://docs.python.org/3/library/inspect.html#inspect.stack>`_). :param obj: Frame record :type obj: tuple :param extended: Flag that indicates whether contents of the ...
entailment
def set(self, x): """ Set variable values via a dictionary mapping name to value. """ for name, value in iter(x.items()): if hasattr(value, "ndim"): if self[name].value.ndim < value.ndim: self[name].value.itemset(value.squeeze()) ...
Set variable values via a dictionary mapping name to value.
entailment
def select(self, fixed): """ Return a subset of variables according to ``fixed``. """ names = [n for n in self.names() if self[n].isfixed == fixed] return Variables({n: self[n] for n in names})
Return a subset of variables according to ``fixed``.
entailment
def validate(self, tracking_number): "Return True if this is a valid USPS tracking number." tracking_num = tracking_number[:-1].replace(' ', '') odd_total = 0 even_total = 0 for ii, digit in enumerate(tracking_num): if ii % 2: odd_total += int(digit) ...
Return True if this is a valid USPS tracking number.
entailment
def validate(self, tracking_number): "Return True if this is a valid UPS tracking number." tracking_num = tracking_number[2:-1] odd_total = 0 even_total = 0 for ii, digit in enumerate(tracking_num.upper()): try: value = int(digit) except V...
Return True if this is a valid UPS tracking number.
entailment
def track(self, tracking_number): "Track a UPS package by number. Returns just a delivery date." resp = self.send_request(tracking_number) return self.parse_response(resp)
Track a UPS package by number. Returns just a delivery date.
entailment
def load(pathtovector, wordlist=(), num_to_load=None, truncate_embeddings=None, unk_word=None, sep=" "): r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which d...
r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which do not conform to line lengths. Parameters ---------- pathtovector : string The path to the vector file. header : bool Whe...
entailment
def _load(pathtovector, wordlist, num_to_load=None, truncate_embeddings=None, sep=" "): """Load a matrix and wordlist from a .vec file.""" vectors = [] addedwords = set() words = [] try: wordlist = set(wordlist)...
Load a matrix and wordlist from a .vec file.
entailment
def vectorize(self, tokens, remove_oov=False, norm=False): """ Vectorize a sentence by replacing all items with their vectors. Parameters ---------- tokens : object or list of objects The tokens to vectorize. remove_oov : bool, optional, default False ...
Vectorize a sentence by replacing all items with their vectors. Parameters ---------- tokens : object or list of objects The tokens to vectorize. remove_oov : bool, optional, default False Whether to remove OOV items. If False, OOV items are replaced by ...
entailment
def bow(self, tokens, remove_oov=False): """ Create a bow representation of a list of tokens. Parameters ---------- tokens : list. The list of items to change into a bag of words representation. remove_oov : bool. Whether to remove OOV items from ...
Create a bow representation of a list of tokens. Parameters ---------- tokens : list. The list of items to change into a bag of words representation. remove_oov : bool. Whether to remove OOV items from the input. If this is True, the length of the ret...
entailment
def transform(self, corpus, remove_oov=False, norm=False): """ Transform a corpus by repeated calls to vectorize, defined above. Parameters ---------- corpus : A list of strings, list of list of strings. Represents a corpus as a list of sentences, where sentences ...
Transform a corpus by repeated calls to vectorize, defined above. Parameters ---------- corpus : A list of strings, list of list of strings. Represents a corpus as a list of sentences, where sentences can either be strings or lists of tokens. remove_oov : bool, o...
entailment
def most_similar(self, items, num=10, batch_size=100, show_progressbar=False, return_names=True): """ Return the num most similar items to a given list of items. Parameters ---------...
Return the num most similar items to a given list of items. Parameters ---------- items : list of objects or a single object. The items to get the most similar items to. num : int, optional, default 10 The number of most similar items to retrieve. batch_s...
entailment
def threshold(self, items, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): """ Return all items whose similarity is higher than threshold. Parameters ---------- it...
Return all items whose similarity is higher than threshold. Parameters ---------- items : list of objects or a single object. The items to get the most similar items to. threshold : float, optional, default .5 The radius within which to retrieve items. ba...
entailment
def nearest_neighbor(self, vectors, num=10, batch_size=100, show_progressbar=False, return_names=True): """ Find the nearest neighbors to some arbitrary vector. This func...
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily no...
entailment
def nearest_neighbor_threshold(self, vectors, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): """ Find ...
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily no...
entailment
def _threshold_batch(self, vectors, batch_size, threshold, show_progressbar, return_names): """Batched cosine distance.""" vectors = self.normalize(vectors) # Single tran...
Batched cosine distance.
entailment
def _batch(self, vectors, batch_size, num, show_progressbar, return_names): """Batched cosine distance.""" vectors = self.normalize(vectors) # Single transpose, makes things faster. reference_transposed = self.no...
Batched cosine distance.
entailment
def normalize(vectors): """ Normalize a matrix of row vectors to unit length. Contains a shortcut if there are no zero vectors in the matrix. If there are zero vectors, we do some indexing tricks to avoid dividing by 0. Parameters ---------- vectors : np...
Normalize a matrix of row vectors to unit length. Contains a shortcut if there are no zero vectors in the matrix. If there are zero vectors, we do some indexing tricks to avoid dividing by 0. Parameters ---------- vectors : np.array The vectors to normalize....
entailment
def vector_similarity(self, vector, items): """Compute the similarity between a vector and a set of items.""" vector = self.normalize(vector) items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items]) return vector.dot(items_vec.T)
Compute the similarity between a vector and a set of items.
entailment
def similarity(self, i1, i2): """ Compute the similarity between two sets of items. Parameters ---------- i1 : object The first set of items. i2 : object The second set of item. Returns ------- sim : array of floats ...
Compute the similarity between two sets of items. Parameters ---------- i1 : object The first set of items. i2 : object The second set of item. Returns ------- sim : array of floats An array of similarity scores between 1 and ...
entailment
def prune(self, wordlist): """ Prune the current reach instance by removing items. Parameters ---------- wordlist : list of str A list of words to keep. Note that this wordlist need not include all words in the Reach instance. Any words which are in the ...
Prune the current reach instance by removing items. Parameters ---------- wordlist : list of str A list of words to keep. Note that this wordlist need not include all words in the Reach instance. Any words which are in the wordlist, but not in the reach insta...
entailment
def save(self, path, write_header=True): """ Save the current vector space in word2vec format. Parameters ---------- path : str The path to save the vector file to. write_header : bool, optional, default True Whether to write a word2vec-style head...
Save the current vector space in word2vec format. Parameters ---------- path : str The path to save the vector file to. write_header : bool, optional, default True Whether to write a word2vec-style header as the first line of the file
entailment
def save_fast_format(self, filename): """ Save a reach instance in a fast format. The reach fast format stores the words and vectors of a Reach instance separately in a JSON and numpy format, respectively. Parameters ---------- filename : str The pre...
Save a reach instance in a fast format. The reach fast format stores the words and vectors of a Reach instance separately in a JSON and numpy format, respectively. Parameters ---------- filename : str The prefix to add to the saved filename. Note that this is not th...
entailment
def load_fast_format(filename): """ Load a reach instance in fast format. As described above, the fast format stores the words and vectors of the Reach instance separately, and is drastically faster than loading from .txt files. Parameters ---------- fil...
Load a reach instance in fast format. As described above, the fast format stores the words and vectors of the Reach instance separately, and is drastically faster than loading from .txt files. Parameters ---------- filename : str The filename prefix from whi...
entailment
def _load_fast(filename): """Sub for fast loader.""" it = json.load(open("{}_items.json".format(filename))) words, unk_index, name = it["items"], it["unk_index"], it["name"] vectors = np.load(open("{}_vectors.npy".format(filename), 'rb')) return words, unk_index, name, vectors
Sub for fast loader.
entailment
def demo_usage(n_data=50, n_fit=537, nhead=5, ntail=5, plot=False, alt=0): """ Plots a noisy sine curve and the fitting to it. Also presents the error and the error in the approximation of its first derivative (cosine curve) Usage example for benchmarking: $ time python sine.py --nhead 3 --nta...
Plots a noisy sine curve and the fitting to it. Also presents the error and the error in the approximation of its first derivative (cosine curve) Usage example for benchmarking: $ time python sine.py --nhead 3 --ntail 3 --n-fit 500000 --n-data 50000 Usage example for plotting: $ python sine....
entailment
def demo_err(): """ This demo shows how the error in the estimate varies depending on how many data points are included in the interpolation (m parameter in this function). """ max_order = 7 n = 20 l = 0.25 fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}' fmt2 = '{0:...
This demo shows how the error in the estimate varies depending on how many data points are included in the interpolation (m parameter in this function).
entailment
def display_results(repo_name, contributors, api_len): """ Fancy display. """ print("\n") print("All Contributors:") # Sort and consolidate on Name seen = [] for user in sorted(contributors, key=_sort_by_name): if user.get("name"): key = user["name"] else: ...
Fancy display.
entailment
def get_json(uri): """ Handle headers and json for us :3 """ response = requests.get(API + uri, headers=HEADERS) limit = int(response.headers.get("x-ratelimit-remaining")) if limit == 0: sys.stdout.write("\n") message = "You have run out of GitHub request tokens. " if i...
Handle headers and json for us :3
entailment
def api_walk(uri, per_page=100, key="login"): """ For a GitHub URI, walk all the pages until there's no more content """ page = 1 result = [] while True: response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page)) if len(response) == 0: break else: ...
For a GitHub URI, walk all the pages until there's no more content
entailment
def api_get(uri, key=None): """ Simple API endpoint get, return only the keys we care about """ response = get_json(uri) if response: if type(response) == list: r = response[0] elif type(response) == dict: r = response if type(r) == dict: ...
Simple API endpoint get, return only the keys we care about
entailment
def reducejson(j): """ Not sure if there's a better way to walk the ... interesting result """ authors = [] for key in j["data"]["repository"]["commitComments"]["edges"]: authors.append(key["node"]["author"]) for key in j["data"]["repository"]["issues"]["nodes"]: auth...
Not sure if there's a better way to walk the ... interesting result
entailment
def stringify_with_dot_if_path(x): '''Pathlib never renders a leading './' in front of a local path. That's an issue because on POSIX subprocess.py (like bash) won't execute scripts in the current directory without it. In the same vein, we also don't want Path('echo') to match '/usr/bin/echo' from the $...
Pathlib never renders a leading './' in front of a local path. That's an issue because on POSIX subprocess.py (like bash) won't execute scripts in the current directory without it. In the same vein, we also don't want Path('echo') to match '/usr/bin/echo' from the $PATH. To work around both issues, we e...
entailment
def maybe_canonicalize_exe_path(exe_name, iocontext): '''There's a tricky interaction between exe paths and `dir`. Exe paths can be relative, and so we have to ask: Is an exe path interpreted relative to the parent's cwd, or the child's? The answer is that it's platform dependent! >.< (Windows uses the ...
There's a tricky interaction between exe paths and `dir`. Exe paths can be relative, and so we have to ask: Is an exe path interpreted relative to the parent's cwd, or the child's? The answer is that it's platform dependent! >.< (Windows uses the parent's cwd, but because of the fork-chdir-exec pattern,...
entailment
def safe_popen(*args, **kwargs): '''This wrapper works around two major deadlock issues to do with pipes. The first is that, before Python 3.2 on POSIX systems, os.pipe() creates inheritable file descriptors, which leak to all child processes and prevent reads from reaching EOF. The workaround for this ...
This wrapper works around two major deadlock issues to do with pipes. The first is that, before Python 3.2 on POSIX systems, os.pipe() creates inheritable file descriptors, which leak to all child processes and prevent reads from reaching EOF. The workaround for this is to set close_fds=True on POSIX, w...
entailment
def run(self): '''Execute the expression and return a Result, which includes the exit status and any captured output. Raise an exception if the status is non-zero.''' with spawn_output_reader() as (stdout_capture, stdout_thread): with spawn_output_reader() as (stderr_capture,...
Execute the expression and return a Result, which includes the exit status and any captured output. Raise an exception if the status is non-zero.
entailment
def read(self): '''Execute the expression and capture its output, similar to backticks or $() in the shell. This is a wrapper around run() which captures stdout, decodes it, trims it, and returns it directly.''' result = self.stdout_capture().run() stdout_str = decode_with_univer...
Execute the expression and capture its output, similar to backticks or $() in the shell. This is a wrapper around run() which captures stdout, decodes it, trims it, and returns it directly.
entailment
def start(self): '''Equivalent to `run`, but instead of blocking the current thread, return a WaitHandle that doesn't block until `wait` is called. This is currently implemented with a simple background thread, though in theory it could avoid using threads in most cases.''' threa...
Equivalent to `run`, but instead of blocking the current thread, return a WaitHandle that doesn't block until `wait` is called. This is currently implemented with a simple background thread, though in theory it could avoid using threads in most cases.
entailment
def _exec(self, cmd, url, json_data=None): """ execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be at...
execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be attached to the command
entailment
def set_device(self, dev): """ set the current device (that will be used for following API calls) :param dict dev: device that should be used for the API calls (can be obtained via get_devices function) """ log.debug("setting device to '{}'".format(dev))...
set the current device (that will be used for following API calls) :param dict dev: device that should be used for the API calls (can be obtained via get_devices function)
entailment
def _get_widget_id(self, package_name): """ returns widget_id for given package_name does not care about multiple widget ids at the moment, just picks the first :param str package_name: package to check for :return: id of first widget which belongs to the given package_name ...
returns widget_id for given package_name does not care about multiple widget ids at the moment, just picks the first :param str package_name: package to check for :return: id of first widget which belongs to the given package_name :rtype: str
entailment
def get_user(self): """ get the user details via the cloud """ log.debug("getting user information from LaMetric cloud...") _, url = CLOUD_URLS["get_user"] res = self._cloud_session.session.get(url) if res is not None: # raise an exception on error ...
get the user details via the cloud
entailment
def get_devices(self, force_reload=False, save_devices=True): """ get all devices that are linked to the user, if the local device file is not existing the devices will be obtained from the LaMetric cloud, otherwise the local device file will be read. :param bool force_reload: W...
get all devices that are linked to the user, if the local device file is not existing the devices will be obtained from the LaMetric cloud, otherwise the local device file will be read. :param bool force_reload: When True, devices are read again from cloud :param bool save_devices: When...
entailment
def save_devices(self): """ save devices that have been obtained from LaMetric cloud to a local file """ log.debug("saving devices to ''...".format(self._devices_filename)) if self._devices != []: with codecs.open(self._devices_filename, "wb", "utf-8") as f: ...
save devices that have been obtained from LaMetric cloud to a local file
entailment
def get_endpoint_map(self): """ returns API version and endpoint map """ log.debug("getting end points...") cmd, url = DEVICE_URLS["get_endpoint_map"] return self._exec(cmd, url)
returns API version and endpoint map
entailment
def load_devices(self): """ load stored devices from the local file """ self._devices = [] if os.path.exists(self._devices_filename): log.debug( "loading devices from '{}'...".format(self._devices_filename) ) with codecs.open(se...
load stored devices from the local file
entailment
def get_device_state(self): """ returns the full device state """ log.debug("getting device state...") cmd, url = DEVICE_URLS["get_device_state"] return self._exec(cmd, url)
returns the full device state
entailment
def send_notification( self, model, priority="warning", icon_type=None, lifetime=None ): """ sends new notification to the device :param Model model: an instance of the Model class that should be used :param str priority: the priority of the notification ...
sends new notification to the device :param Model model: an instance of the Model class that should be used :param str priority: the priority of the notification [info, warning or critical] (default: warning) :param str icon_type: the icon type of the notification ...
entailment
def get_notifications(self): """ returns the list of all notifications in queue """ log.debug("getting notifications in queue...") cmd, url = DEVICE_URLS["get_notifications_queue"] return self._exec(cmd, url)
returns the list of all notifications in queue
entailment
def get_current_notification(self): """ returns the current notification (i.e. the one that is visible) """ log.debug("getting visible notification...") cmd, url = DEVICE_URLS["get_current_notification"] return self._exec(cmd, url)
returns the current notification (i.e. the one that is visible)
entailment
def get_notification(self, notification_id): """ returns a specific notification by given id :param str notification_id: the ID of the notification """ log.debug("getting notification '{}'...".format(notification_id)) cmd, url = DEVICE_URLS["get_notification"] re...
returns a specific notification by given id :param str notification_id: the ID of the notification
entailment
def get_display(self): """ returns information about the display, including brightness, screensaver etc. """ log.debug("getting display information...") cmd, url = DEVICE_URLS["get_display"] return self._exec(cmd, url)
returns information about the display, including brightness, screensaver etc.
entailment