sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def best_oob_mae_weight(trees): """ Returns weights so that the tree with smallest out-of-bag mean absolute error """ best = (+1e999999, None) for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: cont...
Returns weights so that the tree with smallest out-of-bag mean absolute error
entailment
def mean_oob_mae_weight(trees): """ Returns weights proportional to the out-of-bag mean absolute error for each tree. """ weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: ...
Returns weights proportional to the out-of-bag mean absolute error for each tree.
entailment
def _grow_trees(self): """ Adds new trees to the forest according to the specified growth method. """ if self.grow_method == GROW_AUTO_INCREMENTAL: self.tree_kwargs['auto_grow'] = True while len(self.trees) < self.size: self.trees.append(Tree(data...
Adds new trees to the forest according to the specified growth method.
entailment
def predict(self, record): """ Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights. """ ...
Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights.
entailment
def train(self, record): """ Updates the trees with the given training record. """ self._fell_trees() self._grow_trees() for tree in self.trees: if random.random() < self.sample_ratio: tree.train(record) else: tree.o...
Updates the trees with the given training record.
entailment
def get_configfile_paths(system=True, user=True, local=True, only_existing=True): """Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwav...
Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwave.conf`` in the current working directory (CWD), user-local ``.config/dwave/``, and s...
entailment
def get_default_configfile_path(): """Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration fi...
Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system runnin...
entailment
def load_config_from_files(filenames=None): """Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. ...
Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows ...
entailment
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config....
Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standar...
entailment
def load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None): """Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highes...
Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`load_config()`. These values replace values read from a configu...
entailment
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs): """Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~d...
Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~dwave.cloud.client.Client.from_config` instead. This method tries to load a legacy configuration file from ``~/.dwrc``, select...
entailment
def _check_data(data): """Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied. """ if not (data.dt...
Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied.
entailment
def src_simple(input_data, output_data, ratio, converter_type, channels): """Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initia...
Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initialisation as it can only operate on a single buffer worth of audio.
entailment
def src_new(converter_type, channels): """Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converte...
Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. error : int Error code.
entailment
def src_process(state, input_data, output_data, ratio, end_of_input=0): """Standard processing function. Returns non zero on error. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data...
Standard processing function. Returns non zero on error.
entailment
def _src_input_callback(cb_data, data): """Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A referen...
Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A reference to these data is kept internally. R...
entailment
def src_callback_new(callback, converter_type, channels): """Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Conver...
Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Converter to be used. channels : int Number of channels. ...
entailment
def src_callback_read(state, ratio, frames, data): """Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error. """ data_ptr = ffi.cast('float*f', ffi.from_buffer(data)) return _lib.src_callback_read(state, ratio, fr...
Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error.
entailment
def from_config(cls, config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=False, **kwargs): """Client factory method to instantiate a client instance from configuration. Configuration values can b...
Client factory method to instantiate a client instance from configuration. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`from_config()` 2. Values specified as environ...
entailment
def close(self): """Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use...
Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use a context manager (a :code:...
entailment
def get_solvers(self, refresh=False, order_by='avg_load', **filters): """Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_...
Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute...
entailment
def solvers(self, refresh=False, **filters): """Deprecated in favor of :meth:`.get_solvers`.""" warnings.warn("'solvers' is deprecated in favor of 'get_solvers'.", DeprecationWarning) return self.get_solvers(refresh=refresh, **filters)
Deprecated in favor of :meth:`.get_solvers`.
entailment
def get_solver(self, name=None, refresh=False, **filters): """Load the configuration for a single solver. Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}` is a URL configured for the client, and returns a :class:`.Solver` instance that can be u...
Load the configuration for a single solver. Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}` is a URL configured for the client, and returns a :class:`.Solver` instance that can be used to submit sampling problems to the D-Wave API and retrieve results...
entailment
def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ self._submission_queue.put(self._submit.Message(body, future))
Enqueue a problem for submission to the server. This method is thread safe.
entailment
def _do_submit_problems(self): """Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block on the first one, #...
Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread.
entailment
def _handle_problem_status(self, message, future): """Handle the results of a problem submission or results request. This method checks the status of the problem and puts it in the correct queue. Args: message (dict): Update message from the SAPI server wrt. this problem. ...
Handle the results of a problem submission or results request. This method checks the status of the problem and puts it in the correct queue. Args: message (dict): Update message from the SAPI server wrt. this problem. future `Future`: future corresponding to the problem ...
entailment
def _do_cancel_problems(self): """Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block when none are available. # ...
Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread.
entailment
def _poll(self, future): """Enqueue a problem to poll the server for status.""" if future._poll_backoff is None: # on first poll, start with minimal back-off future._poll_backoff = self._POLL_BACKOFF_MIN # if we have ETA of results, schedule the first poll for then ...
Enqueue a problem to poll the server for status.
entailment
def _do_poll_problems(self): """Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread. """ try: # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME) frame_futures = {} def...
Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread.
entailment
def _do_load_results(self): """Submit a query asking for the results for a particular problem. To request the results of a problem: ``GET /problems/{problem_id}/`` Note: This method is always run inside of a daemon thread. """ try: while True: ...
Submit a query asking for the results for a particular problem. To request the results of a problem: ``GET /problems/{problem_id}/`` Note: This method is always run inside of a daemon thread.
entailment
def encode_bqm_as_qp(solver, linear, quadratic): """Encode the binary quadratic problem for submission to a given solver, using the `qp` format for data. Args: solver (:class:`dwave.cloud.solver.Solver`): The solver used. linear (dict[variable, bias]/list[variable, bias]): ...
Encode the binary quadratic problem for submission to a given solver, using the `qp` format for data. Args: solver (:class:`dwave.cloud.solver.Solver`): The solver used. linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (d...
entailment
def decode_qp(msg): """Decode SAPI response that uses `qp` format, without numpy. The 'qp' format is the current encoding used for problems and samples. In this encoding the reply is generally json, but the samples, energy, and histogram data (the occurrence count of each solution), are all base64 ...
Decode SAPI response that uses `qp` format, without numpy. The 'qp' format is the current encoding used for problems and samples. In this encoding the reply is generally json, but the samples, energy, and histogram data (the occurrence count of each solution), are all base64 encoded arrays.
entailment
def _decode_byte(byte): """Helper for decode_qp, turns a single byte into a list of bits. Args: byte: byte to be decoded Returns: list of bits corresponding to byte """ bits = [] for _ in range(8): bits.append(byte & 1) byte >>= 1 return bits
Helper for decode_qp, turns a single byte into a list of bits. Args: byte: byte to be decoded Returns: list of bits corresponding to byte
entailment
def _decode_ints(message): """Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. """ binary = base64.b64decode(message) return struct.unpack('<' + (...
Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse.
entailment
def _decode_doubles(message): """Helper for decode_qp, decodes a double array. The double array is stored as little endian 64 bit doubles. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. Args: message: the double array Returns: decod...
Helper for decode_qp, decodes a double array. The double array is stored as little endian 64 bit doubles. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. Args: message: the double array Returns: decoded double array
entailment
def decode_qp_numpy(msg, return_matrix=True): """Decode SAPI response, results in a `qp` format, explicitly using numpy. If numpy is not installed, the method will fail. To use numpy for decoding, but return the results a lists (instead of numpy matrices), set `return_matrix=False`. """ import ...
Decode SAPI response, results in a `qp` format, explicitly using numpy. If numpy is not installed, the method will fail. To use numpy for decoding, but return the results a lists (instead of numpy matrices), set `return_matrix=False`.
entailment
def evaluate_ising(linear, quad, state): """Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the gi...
Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the given energy function.
entailment
def active_qubits(linear, quadratic): """Calculate a set of all active qubits. Qubit is "active" if it has bias or coupling attached. Args: linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (dict[(variable, variable), bias]): Q...
Calculate a set of all active qubits. Qubit is "active" if it has bias or coupling attached. Args: linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (dict[(variable, variable), bias]): Quadratic terms of the model. Returns: ...
entailment
def generate_random_ising_problem(solver, h_range=None, j_range=None): """Generates an Ising problem formulation valid for a particular solver, using all qubits and all couplings and linear/quadratic biases sampled uniformly from `h_range`/`j_range`. """ if h_range is None: h_range = solver...
Generates an Ising problem formulation valid for a particular solver, using all qubits and all couplings and linear/quadratic biases sampled uniformly from `h_range`/`j_range`.
entailment
def uniform_iterator(sequence): """Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.""" if isinstance(sequence, abc.Mapping): return six.iteritems(sequence) else: return enumerate(sequence)
Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.
entailment
def uniform_get(sequence, index, default=None): """Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.""" if isinstance(sequence, abc.Mapping): return sequence.get(index, default) else: return sequence[index] if index < len(s...
Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.
entailment
def strip_head(sequence, values): """Strips elements of `values` from the beginning of `sequence`.""" values = set(values) return list(itertools.dropwhile(lambda x: x in values, sequence))
Strips elements of `values` from the beginning of `sequence`.
entailment
def strip_tail(sequence, values): """Strip `values` from the end of `sequence`.""" return list(reversed(list(strip_head(reversed(sequence), values))))
Strip `values` from the end of `sequence`.
entailment
def click_info_switch(f): """Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.opt...
Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.option('--my-option', is_flag=True, ...
entailment
def datetime_to_timestamp(dt): """Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+. """ epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC) return (dt - epoch).total_seconds()
Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+.
entailment
def user_agent(name, version): """Return User-Agent ~ "name/version language/version interpreter/version os/version".""" def _interpreter(): name = platform.python_implementation() version = platform.python_version() bitness = platform.architecture()[0] if name == 'PyPy': ...
Return User-Agent ~ "name/version language/version interpreter/version os/version".
entailment
def argshash(self, args, kwargs): "Hash mutable arguments' containers with immutable keys and values." a = repr(args) b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items())) return a + b
Hash mutable arguments' containers with immutable keys and values.
entailment
def get_context_data(self, **kwargs): """ Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid. """ ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs) ctx.update({ ...
Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid.
entailment
def get_success_url(self): """ Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value. """ if self.next: return self.next if self.object and self.object.content_object: ...
Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value.
entailment
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_t...
Adds useful objects to the class and performs security checks.
entailment
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(DeleteImageView, self).dispatch(request, *args, **kwargs)
Adds useful objects to the class.
entailment
def get_queryset(self): """ Making sure that a user can only delete his own images. Even when he forges the request URL. """ queryset = super(DeleteImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
Making sure that a user can only delete his own images. Even when he forges the request URL.
entailment
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(UpdateImageView, self).dispatch(request, *args, **kwargs)
Adds useful objects to the class.
entailment
def get_queryset(self): """ Making sure that a user can only edit his own images. Even when he forges the request URL. """ queryset = super(UpdateImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
Making sure that a user can only edit his own images. Even when he forges the request URL.
entailment
def _delete_images(self, instance): """Deletes all user media images of the given instance.""" UserMediaImage.objects.filter( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, user=instance.user, ).delete()
Deletes all user media images of the given instance.
entailment
def clean_image(self): """ It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot crea...
It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot create the new file path because it nee...
entailment
def get_image_file_path(instance, filename): """Returns a unique filename for images.""" ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
Returns a unique filename for images.
entailment
def image_post_delete_handler(sender, instance, **kwargs): """ Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc. """ for f in glob.glob('{}/{}*'.format(instance.image.storage.location, ...
Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc.
entailment
def box_coordinates(self): """Returns a thumbnail's coordinates.""" if ( self.thumb_x is not None and self.thumb_y is not None and self.thumb_x2 is not None and self.thumb_y2 is not None ): return ( int(self.thumb_x), ...
Returns a thumbnail's coordinates.
entailment
def large_size(self, as_string=True): """Returns a thumbnail's large size.""" size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
Returns a thumbnail's large size.
entailment
def crop_box(im, box=False, **kwargs): """Uses box coordinates to crop an image without resizing it first.""" if box: im = im.crop(box) return im
Uses box coordinates to crop an image without resizing it first.
entailment
def load_germanet(host = None, port = None, database_name = 'germanet'): ''' Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet...
Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet database on the MongoDB instance
entailment
def cache_size(self, new_value): ''' Set the cache size used to reduce the number of database access operations. ''' if type(new_value) == int and 0 < new_value: if self._lemma_cache is not None: self._lemma_cache = repoze.lru.LRUCache(new_value) ...
Set the cache size used to reduce the number of database access operations.
entailment
def all_lemmas(self): ''' A generator over all the lemmas in the GermaNet database. ''' for lemma_dict in self._mongo_db.lexunits.find(): yield Lemma(self, lemma_dict)
A generator over all the lemmas in the GermaNet database.
entailment
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`:
entailment
def all_synsets(self): ''' A generator over all the synsets in the GermaNet database. ''' for synset_dict in self._mongo_db.synsets.find(): yield Synset(self, synset_dict)
A generator over all the synsets in the GermaNet database.
entailment
def synsets(self, lemma, pos = None): ''' Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' return sorted(set(lemma_obj.synset for lemma_obj in self.lemmas(lemma, pos)))
Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`:
entailment
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') Synset(funktionieren.v.2)
entailment
def get_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = self...
Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object
entailment
def get_lemma_by_id(self, mongo_id): ''' Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._lemma_cache is not None: cache_hit = self._l...
Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object
entailment
def lemmatise(self, word): ''' Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') ...
Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') [u'XYZ123']
entailment
def find_germanet_xml_files(xml_path): ''' Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files ''' xml_files = sorted(glob.glob(os.p...
Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files
entailment
def warn_attribs(loc, node, recognised_attribs, reqd_attribs=None): ''' Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with som...
Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with some information about the location of the error in the XML file - `node`: the node to check - `recognised_attribs`: a s...
entailment
def read_lexical_file(filename): ''' Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) sy...
Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read
entailment
def read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`:
entailment
def read_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`:
entailment
def insert_lexical_information(germanet_db, lex_files): ''' Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial ...
Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial information
entailment
def insert_relation_information(germanet_db, gn_rels_file): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`: ''' lex_rels, con_rels = read_relation_fil...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`:
entailment
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`:
entailment
def insert_lemmatisation_data(germanet_db): ''' Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object ''' # drop the database collection if it already exist...
Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object
entailment
def insert_infocontent_data(germanet_db): ''' For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) # use add one smoothing gn_counts = defa...
For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object
entailment
def compute_max_min_depth(germanet_db): ''' For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) max_min_depths = defaultdict(lambda: -1)...
For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object
entailment
def main(): '''Main function.''' usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n ' 'XML_PATH the directory containing the ' 'GermaNet .xml files') parser = optparse.OptionParser(usage=usage) parser.add_option('--host', default=None, ...
Main function.
entailment
def handle_In(self, node): '''in''' try: elts = node.elts except AttributeError: raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__), col_offset=node.col_offset) return {'$in': list(map(self.fie...
in
entailment
def AssignVar(self, value): """Assign a value to this Value.""" self.value = value # Call OnAssignVar on options. [option.OnAssignVar() for option in self.options]
Assign a value to this Value.
entailment
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
entailment
def _CheckLine(self, line): """Passes the line through each rule until a match is made. Args: line: A string, the current input line. """ for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: for value in matched.groupdict(): self._AssignVar(...
Passes the line through each rule until a match is made. Args: line: A string, the current input line.
entailment
def _make_graphite_api_points_list(influxdb_data): """Make graphite-api data points dictionary from Influxdb ResultSet data""" _data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data...
Make graphite-api data points dictionary from Influxdb ResultSet data
entailment
def _setup_logger(self, level, log_file): """Setup log level and log file if set""" if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcNam...
Setup log level and log file if set
entailment
def compile_regex(self, fmt, query): """Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !""" return re.compile(fmt.format( query.pattern.replace('.', '\.').repl...
Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !
entailment
def find(expression, schema=None): ''' Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types. ''' parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema) return parser.pars...
Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types.
entailment
def sort(fields): ''' Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height. ''' from pymongo import ...
Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height.
entailment
def ordered(obj): """ Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972 """ if isinstance(obj, collections.abc.Mapping): return sorted((k, ordered(v)) for k, v in obj.items()) # Special case str since it's a collections.abc...
Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972
entailment
def walk_subclasses(root): """Does not yield the input class""" classes = [root] visited = set() while classes: cls = classes.pop() if cls is type or cls in visited: continue classes.extend(cls.__subclasses__()) visited.add(cls) if cls is not root: ...
Does not yield the input class
entailment
def dump_key(engine, obj): """dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} """ key = {} for key_column in obj.Meta.keys: key_value = getattr(obj, key_column.name, mis...
dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys}
entailment
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
Return an expiration `days` in the future
entailment
def sync(obj, engine): """Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.""" snapshot = Condition() # Only expect values (or lack of a value) for columns that have been explicitly set for column in sorted(_obj_tracking[obj]["marked"], key=lamb...
Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.
entailment
def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """ pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segmen...
Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar
entailment
def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).""" conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic cond...
Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).
entailment
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths.
entailment