partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Solver._format_params
Reformat some of the parameters for sapi.
dwave/cloud/solver.py
def _format_params(self, type_, params): """Reformat some of the parameters for sapi.""" if 'initial_state' in params: # NB: at this moment the error raised when initial_state does not match lin/quad (in # active qubits) is not very informative, but there is also no clean way to ...
def _format_params(self, type_, params): """Reformat some of the parameters for sapi.""" if 'initial_state' in params: # NB: at this moment the error raised when initial_state does not match lin/quad (in # active qubits) is not very informative, but there is also no clean way to ...
[ "Reformat", "some", "of", "the", "parameters", "for", "sapi", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L390-L412
[ "def", "_format_params", "(", "self", ",", "type_", ",", "params", ")", ":", "if", "'initial_state'", "in", "params", ":", "# NB: at this moment the error raised when initial_state does not match lin/quad (in", "# active qubits) is not very informative, but there is also no clean way...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Solver.check_problem
Test if an Ising model matches the graph provided by the solver. Args: linear (list/dict): Linear terms of the model (h). quadratic (dict of (int, int):float): Quadratic terms of the model (J). Returns: boolean Examples: This example creates a c...
dwave/cloud/solver.py
def check_problem(self, linear, quadratic): """Test if an Ising model matches the graph provided by the solver. Args: linear (list/dict): Linear terms of the model (h). quadratic (dict of (int, int):float): Quadratic terms of the model (J). Returns: boolean ...
def check_problem(self, linear, quadratic): """Test if an Ising model matches the graph provided by the solver. Args: linear (list/dict): Linear terms of the model (h). quadratic (dict of (int, int):float): Quadratic terms of the model (J). Returns: boolean ...
[ "Test", "if", "an", "Ising", "model", "matches", "the", "graph", "provided", "by", "the", "solver", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L415-L451
[ "def", "check_problem", "(", "self", ",", "linear", ",", "quadratic", ")", ":", "for", "key", ",", "value", "in", "uniform_iterator", "(", "linear", ")", ":", "if", "value", "!=", "0", "and", "key", "not", "in", "self", ".", "nodes", ":", "return", "...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Solver._retrieve_problem
Resume polling for a problem previously submitted. Args: id_: Identification of the query. Returns: :obj: `Future`
dwave/cloud/solver.py
def _retrieve_problem(self, id_): """Resume polling for a problem previously submitted. Args: id_: Identification of the query. Returns: :obj: `Future` """ future = Future(self, id_, self.return_matrix, None) self.client._poll(future) ret...
def _retrieve_problem(self, id_): """Resume polling for a problem previously submitted. Args: id_: Identification of the query. Returns: :obj: `Future` """ future = Future(self, id_, self.return_matrix, None) self.client._poll(future) ret...
[ "Resume", "polling", "for", "a", "problem", "previously", "submitted", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L453-L464
[ "def", "_retrieve_problem", "(", "self", ",", "id_", ")", ":", "future", "=", "Future", "(", "self", ",", "id_", ",", "self", ".", "return_matrix", ",", "None", ")", "self", ".", "client", ".", "_poll", "(", "future", ")", "return", "future" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
_get_converter_type
Return the converter type for `identifier`.
samplerate/converters.py
def _get_converter_type(identifier): """Return the converter type for `identifier`.""" if isinstance(identifier, str): return ConverterType[identifier] if isinstance(identifier, ConverterType): return identifier return ConverterType(identifier)
def _get_converter_type(identifier): """Return the converter type for `identifier`.""" if isinstance(identifier, str): return ConverterType[identifier] if isinstance(identifier, ConverterType): return identifier return ConverterType(identifier)
[ "Return", "the", "converter", "type", "for", "identifier", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L22-L28
[ "def", "_get_converter_type", "(", "identifier", ")", ":", "if", "isinstance", "(", "identifier", ",", "str", ")", ":", "return", "ConverterType", "[", "identifier", "]", "if", "isinstance", "(", "identifier", ",", "ConverterType", ")", ":", "return", "identif...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
resample
Resample the signal in `input_data` at once. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several channels is represented as a 2D array of shape (`num_frames`, `num_channels`). For use with ...
samplerate/converters.py
def resample(input_data, ratio, converter_type='sinc_best', verbose=False): """Resample the signal in `input_data` at once. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several channels is repre...
def resample(input_data, ratio, converter_type='sinc_best', verbose=False): """Resample the signal in `input_data` at once. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several channels is repre...
[ "Resample", "the", "signal", "in", "input_data", "at", "once", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L31-L90
[ "def", "resample", "(", "input_data", ",", "ratio", ",", "converter_type", "=", "'sinc_best'", ",", "verbose", "=", "False", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_simple", "from", "samplerate", ".", "exceptions", "import", "ResamplingEr...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
Resampler.set_ratio
Set a new conversion ratio immediately.
samplerate/converters.py
def set_ratio(self, new_ratio): """Set a new conversion ratio immediately.""" from samplerate.lowlevel import src_set_ratio return src_set_ratio(self._state, new_ratio)
def set_ratio(self, new_ratio): """Set a new conversion ratio immediately.""" from samplerate.lowlevel import src_set_ratio return src_set_ratio(self._state, new_ratio)
[ "Set", "a", "new", "conversion", "ratio", "immediately", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L130-L133
[ "def", "set_ratio", "(", "self", ",", "new_ratio", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_set_ratio", "return", "src_set_ratio", "(", "self", ".", "_state", ",", "new_ratio", ")" ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
Resampler.process
Resample the signal in `input_data`. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several channels is represented as a 2D array of shape (`num_frames`, `num_channels`...
samplerate/converters.py
def process(self, input_data, ratio, end_of_input=False, verbose=False): """Resample the signal in `input_data`. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several chan...
def process(self, input_data, ratio, end_of_input=False, verbose=False): """Resample the signal in `input_data`. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several chan...
[ "Resample", "the", "signal", "in", "input_data", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L135-L189
[ "def", "process", "(", "self", ",", "input_data", ",", "ratio", ",", "end_of_input", "=", "False", ",", "verbose", "=", "False", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_process", "from", "samplerate", ".", "exceptions", "import", "Res...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
CallbackResampler._create
Create new callback resampler.
samplerate/converters.py
def _create(self): """Create new callback resampler.""" from samplerate.lowlevel import ffi, src_callback_new, src_delete from samplerate.exceptions import ResamplingError state, handle, error = src_callback_new( self._callback, self._converter_type.value, self._channels) ...
def _create(self): """Create new callback resampler.""" from samplerate.lowlevel import ffi, src_callback_new, src_delete from samplerate.exceptions import ResamplingError state, handle, error = src_callback_new( self._callback, self._converter_type.value, self._channels) ...
[ "Create", "new", "callback", "resampler", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L222-L232
[ "def", "_create", "(", "self", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "ffi", ",", "src_callback_new", ",", "src_delete", "from", "samplerate", ".", "exceptions", "import", "ResamplingError", "state", ",", "handle", ",", "error", "=", "src_c...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
CallbackResampler.set_starting_ratio
Set the starting conversion ratio for the next `read` call.
samplerate/converters.py
def set_starting_ratio(self, ratio): """ Set the starting conversion ratio for the next `read` call. """ from samplerate.lowlevel import src_set_ratio if self._state is None: self._create() src_set_ratio(self._state, ratio) self.ratio = ratio
def set_starting_ratio(self, ratio): """ Set the starting conversion ratio for the next `read` call. """ from samplerate.lowlevel import src_set_ratio if self._state is None: self._create() src_set_ratio(self._state, ratio) self.ratio = ratio
[ "Set", "the", "starting", "conversion", "ratio", "for", "the", "next", "read", "call", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L246-L252
[ "def", "set_starting_ratio", "(", "self", ",", "ratio", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_set_ratio", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_create", "(", ")", "src_set_ratio", "(", "self", ".", "_state...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
CallbackResampler.reset
Reset state.
samplerate/converters.py
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
[ "Reset", "state", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L254-L259
[ "def", "reset", "(", "self", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_reset", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_create", "(", ")", "src_reset", "(", "self", ".", "_state", ")" ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
CallbackResampler.read
Read a number of frames from the resampler. Parameters ---------- num_frames : int Number of frames to read. Returns ------- output_data : ndarray Resampled frames as a (`num_output_frames`, `num_channels`) or (`num_output_frames`,) a...
samplerate/converters.py
def read(self, num_frames): """Read a number of frames from the resampler. Parameters ---------- num_frames : int Number of frames to read. Returns ------- output_data : ndarray Resampled frames as a (`num_output_frames`, `num_channels`) ...
def read(self, num_frames): """Read a number of frames from the resampler. Parameters ---------- num_frames : int Number of frames to read. Returns ------- output_data : ndarray Resampled frames as a (`num_output_frames`, `num_channels`) ...
[ "Read", "a", "number", "of", "frames", "from", "the", "resampler", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L270-L304
[ "def", "read", "(", "self", ",", "num_frames", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_callback_read", ",", "src_error", "from", "samplerate", ".", "exceptions", "import", "ResamplingError", "if", "self", ".", "_state", "is", "None", ":...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
get_variance
Batch variance calculation.
dtree.py
def get_variance(seq): """ Batch variance calculation. """ m = get_mean(seq) return sum((v-m)**2 for v in seq)/float(len(seq))
def get_variance(seq): """ Batch variance calculation. """ m = get_mean(seq) return sum((v-m)**2 for v in seq)/float(len(seq))
[ "Batch", "variance", "calculation", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L91-L96
[ "def", "get_variance", "(", "seq", ")", ":", "m", "=", "get_mean", "(", "seq", ")", "return", "sum", "(", "(", "v", "-", "m", ")", "**", "2", "for", "v", "in", "seq", ")", "/", "float", "(", "len", "(", "seq", ")", ")" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
mean_absolute_error
Batch mean absolute error calculation.
dtree.py
def mean_absolute_error(seq, correct): """ Batch mean absolute error calculation. """ assert len(seq) == len(correct) diffs = [abs(a-b) for a, b in zip(seq, correct)] return sum(diffs)/float(len(diffs))
def mean_absolute_error(seq, correct): """ Batch mean absolute error calculation. """ assert len(seq) == len(correct) diffs = [abs(a-b) for a, b in zip(seq, correct)] return sum(diffs)/float(len(diffs))
[ "Batch", "mean", "absolute", "error", "calculation", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L101-L107
[ "def", "mean_absolute_error", "(", "seq", ",", "correct", ")", ":", "assert", "len", "(", "seq", ")", "==", "len", "(", "correct", ")", "diffs", "=", "[", "abs", "(", "a", "-", "b", ")", "for", "a", ",", "b", "in", "zip", "(", "seq", ",", "corr...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
normalize
Scales each number in the sequence so that the sum of all numbers equals 1.
dtree.py
def normalize(seq): """ Scales each number in the sequence so that the sum of all numbers equals 1. """ s = float(sum(seq)) return [v/s for v in seq]
def normalize(seq): """ Scales each number in the sequence so that the sum of all numbers equals 1. """ s = float(sum(seq)) return [v/s for v in seq]
[ "Scales", "each", "number", "in", "the", "sequence", "so", "that", "the", "sum", "of", "all", "numbers", "equals", "1", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L109-L114
[ "def", "normalize", "(", "seq", ")", ":", "s", "=", "float", "(", "sum", "(", "seq", ")", ")", "return", "[", "v", "/", "s", "for", "v", "in", "seq", "]" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
normcdf
Describes the probability that a real-valued random variable X with a given probability distribution will be found at a value less than or equal to X in a normal distribution. http://en.wikipedia.org/wiki/Cumulative_distribution_function
dtree.py
def normcdf(x, mu, sigma): """ Describes the probability that a real-valued random variable X with a given probability distribution will be found at a value less than or equal to X in a normal distribution. http://en.wikipedia.org/wiki/Cumulative_distribution_function """ t = x-mu y...
def normcdf(x, mu, sigma): """ Describes the probability that a real-valued random variable X with a given probability distribution will be found at a value less than or equal to X in a normal distribution. http://en.wikipedia.org/wiki/Cumulative_distribution_function """ t = x-mu y...
[ "Describes", "the", "probability", "that", "a", "real", "-", "valued", "random", "variable", "X", "with", "a", "given", "probability", "distribution", "will", "be", "found", "at", "a", "value", "less", "than", "or", "equal", "to", "X", "in", "a", "normal",...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L131-L143
[ "def", "normcdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "t", "=", "x", "-", "mu", "y", "=", "0.5", "*", "erfcc", "(", "-", "t", "/", "(", "sigma", "*", "math", ".", "sqrt", "(", "2.0", ")", ")", ")", "if", "y", ">", "1.0", ":", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
normpdf
Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function
dtree.py
def normpdf(x, mu, sigma): """ Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function """ u = (x-mu)/abs(sigma) y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2) return y
def normpdf(x, mu, sigma): """ Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function """ u = (x-mu)/abs(sigma) y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2) return y
[ "Describes", "the", "relative", "likelihood", "that", "a", "real", "-", "valued", "random", "variable", "X", "will", "take", "on", "a", "given", "value", ".", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Probability_density_fun...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L145-L154
[ "def", "normpdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "u", "=", "(", "x", "-", "mu", ")", "/", "abs", "(", "sigma", ")", "y", "=", "(", "1", "/", "(", "math", ".", "sqrt", "(", "2", "*", "pi", ")", "*", "abs", "(", "sigma", ")"...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
entropy
Calculates the entropy of the attribute attr in given data set data. Parameters: data<dict|list> := if dict, treated as value counts of the given attribute name if list, treated as a raw list from which the value counts will be generated attr<string> := the name of the class attribute
dtree.py
def entropy(data, class_attr=None, method=DEFAULT_DISCRETE_METRIC): """ Calculates the entropy of the attribute attr in given data set data. Parameters: data<dict|list> := if dict, treated as value counts of the given attribute name if list, treated as a raw list from which the valu...
def entropy(data, class_attr=None, method=DEFAULT_DISCRETE_METRIC): """ Calculates the entropy of the attribute attr in given data set data. Parameters: data<dict|list> := if dict, treated as value counts of the given attribute name if list, treated as a raw list from which the valu...
[ "Calculates", "the", "entropy", "of", "the", "attribute", "attr", "in", "given", "data", "set", "data", ".", "Parameters", ":", "data<dict|list", ">", ":", "=", "if", "dict", "treated", "as", "value", "counts", "of", "the", "given", "attribute", "name", "i...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L374-L412
[ "def", "entropy", "(", "data", ",", "class_attr", "=", "None", ",", "method", "=", "DEFAULT_DISCRETE_METRIC", ")", ":", "assert", "(", "class_attr", "is", "None", "and", "isinstance", "(", "data", ",", "dict", ")", ")", "or", "(", "class_attr", "is", "no...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
entropy_variance
Calculates the variance fo a continuous class attribute, to be used as an entropy metric.
dtree.py
def entropy_variance(data, class_attr=None, method=DEFAULT_CONTINUOUS_METRIC): """ Calculates the variance fo a continuous class attribute, to be used as an entropy metric. """ assert method in CONTINUOUS_METRICS, "Unknown entropy variance metric: %s" % (method,) assert (class_attr is None a...
def entropy_variance(data, class_attr=None, method=DEFAULT_CONTINUOUS_METRIC): """ Calculates the variance fo a continuous class attribute, to be used as an entropy metric. """ assert method in CONTINUOUS_METRICS, "Unknown entropy variance metric: %s" % (method,) assert (class_attr is None a...
[ "Calculates", "the", "variance", "fo", "a", "continuous", "class", "attribute", "to", "be", "used", "as", "an", "entropy", "metric", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L414-L427
[ "def", "entropy_variance", "(", "data", ",", "class_attr", "=", "None", ",", "method", "=", "DEFAULT_CONTINUOUS_METRIC", ")", ":", "assert", "method", "in", "CONTINUOUS_METRICS", ",", "\"Unknown entropy variance metric: %s\"", "%", "(", "method", ",", ")", "assert",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
get_gain
Calculates the information gain (reduction in entropy) that would result by splitting the data on the chosen attribute (attr). Parameters: prefer_fewer_values := Weights the gain by the count of the attribute's unique values. If multiple attributes have the same gain, but one has s...
dtree.py
def get_gain(data, attr, class_attr, method=DEFAULT_DISCRETE_METRIC, only_sub=0, prefer_fewer_values=False, entropy_func=None): """ Calculates the information gain (reduction in entropy) that would result by splitting the data on the chosen attribute (attr). Parameters: prefer_fewe...
def get_gain(data, attr, class_attr, method=DEFAULT_DISCRETE_METRIC, only_sub=0, prefer_fewer_values=False, entropy_func=None): """ Calculates the information gain (reduction in entropy) that would result by splitting the data on the chosen attribute (attr). Parameters: prefer_fewe...
[ "Calculates", "the", "information", "gain", "(", "reduction", "in", "entropy", ")", "that", "would", "result", "by", "splitting", "the", "data", "on", "the", "chosen", "attribute", "(", "attr", ")", ".", "Parameters", ":", "prefer_fewer_values", ":", "=", "W...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L429-L473
[ "def", "get_gain", "(", "data", ",", "attr", ",", "class_attr", ",", "method", "=", "DEFAULT_DISCRETE_METRIC", ",", "only_sub", "=", "0", ",", "prefer_fewer_values", "=", "False", ",", "entropy_func", "=", "None", ")", ":", "entropy_func", "=", "entropy_func",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
majority_value
Creates a list of all values in the target attribute for each record in the data list object, and returns the value that appears in this list the most frequently.
dtree.py
def majority_value(data, class_attr): """ Creates a list of all values in the target attribute for each record in the data list object, and returns the value that appears in this list the most frequently. """ if is_continuous(data[0][class_attr]): return CDist(seq=[record[class_attr] for...
def majority_value(data, class_attr): """ Creates a list of all values in the target attribute for each record in the data list object, and returns the value that appears in this list the most frequently. """ if is_continuous(data[0][class_attr]): return CDist(seq=[record[class_attr] for...
[ "Creates", "a", "list", "of", "all", "values", "in", "the", "target", "attribute", "for", "each", "record", "in", "the", "data", "list", "object", "and", "returns", "the", "value", "that", "appears", "in", "this", "list", "the", "most", "frequently", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L481-L490
[ "def", "majority_value", "(", "data", ",", "class_attr", ")", ":", "if", "is_continuous", "(", "data", "[", "0", "]", "[", "class_attr", "]", ")", ":", "return", "CDist", "(", "seq", "=", "[", "record", "[", "class_attr", "]", "for", "record", "in", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
most_frequent
Returns the item that appears most frequently in the given list.
dtree.py
def most_frequent(lst): """ Returns the item that appears most frequently in the given list. """ lst = lst[:] highest_freq = 0 most_freq = None for val in unique(lst): if lst.count(val) > highest_freq: most_freq = val highest_freq = lst.count(val) ...
def most_frequent(lst): """ Returns the item that appears most frequently in the given list. """ lst = lst[:] highest_freq = 0 most_freq = None for val in unique(lst): if lst.count(val) > highest_freq: most_freq = val highest_freq = lst.count(val) ...
[ "Returns", "the", "item", "that", "appears", "most", "frequently", "in", "the", "given", "list", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L492-L505
[ "def", "most_frequent", "(", "lst", ")", ":", "lst", "=", "lst", "[", ":", "]", "highest_freq", "=", "0", "most_freq", "=", "None", "for", "val", "in", "unique", "(", "lst", ")", ":", "if", "lst", ".", "count", "(", "val", ")", ">", "highest_freq",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
unique
Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst.
dtree.py
def unique(lst): """ Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst. """ lst = lst[:] unique_lst = [] # Cycle through the list and add each value to the unique list only once. for item in lst: if unique_lst.count(item) <= ...
def unique(lst): """ Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst. """ lst = lst[:] unique_lst = [] # Cycle through the list and add each value to the unique list only once. for item in lst: if unique_lst.count(item) <= ...
[ "Returns", "a", "list", "made", "up", "of", "the", "unique", "values", "found", "in", "lst", ".", "i", ".", "e", ".", "it", "removes", "the", "redundant", "values", "in", "lst", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L507-L521
[ "def", "unique", "(", "lst", ")", ":", "lst", "=", "lst", "[", ":", "]", "unique_lst", "=", "[", "]", "# Cycle through the list and add each value to the unique list only once.", "for", "item", "in", "lst", ":", "if", "unique_lst", ".", "count", "(", "item", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
choose_attribute
Cycles through all the attributes and returns the attribute with the highest information gain (or lowest entropy).
dtree.py
def choose_attribute(data, attributes, class_attr, fitness, method): """ Cycles through all the attributes and returns the attribute with the highest information gain (or lowest entropy). """ best = (-1e999999, None) for attr in attributes: if attr == class_attr: continue ...
def choose_attribute(data, attributes, class_attr, fitness, method): """ Cycles through all the attributes and returns the attribute with the highest information gain (or lowest entropy). """ best = (-1e999999, None) for attr in attributes: if attr == class_attr: continue ...
[ "Cycles", "through", "all", "the", "attributes", "and", "returns", "the", "attribute", "with", "the", "highest", "information", "gain", "(", "or", "lowest", "entropy", ")", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L530-L541
[ "def", "choose_attribute", "(", "data", ",", "attributes", ",", "class_attr", ",", "fitness", ",", "method", ")", ":", "best", "=", "(", "-", "1e999999", ",", "None", ")", "for", "attr", "in", "attributes", ":", "if", "attr", "==", "class_attr", ":", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
create_decision_tree
Returns a new decision tree based on the examples given.
dtree.py
def create_decision_tree(data, attributes, class_attr, fitness_func, wrapper, **kwargs): """ Returns a new decision tree based on the examples given. """ split_attr = kwargs.get('split_attr', None) split_val = kwargs.get('split_val', None) assert class_attr not in attributes node =...
def create_decision_tree(data, attributes, class_attr, fitness_func, wrapper, **kwargs): """ Returns a new decision tree based on the examples given. """ split_attr = kwargs.get('split_attr', None) split_val = kwargs.get('split_val', None) assert class_attr not in attributes node =...
[ "Returns", "a", "new", "decision", "tree", "based", "on", "the", "examples", "given", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L546-L619
[ "def", "create_decision_tree", "(", "data", ",", "attributes", ",", "class_attr", ",", "fitness_func", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "split_attr", "=", "kwargs", ".", "get", "(", "'split_attr'", ",", "None", ")", "split_val", "=", "kwa...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
DDist.add
Increments the count for the given element.
dtree.py
def add(self, k, count=1): """ Increments the count for the given element. """ self.counts[k] += count self.total += count
def add(self, k, count=1): """ Increments the count for the given element. """ self.counts[k] += count self.total += count
[ "Increments", "the", "count", "for", "the", "given", "element", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L215-L220
[ "def", "add", "(", "self", ",", "k", ",", "count", "=", "1", ")", ":", "self", ".", "counts", "[", "k", "]", "+=", "count", "self", ".", "total", "+=", "count" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
DDist.best
Returns the element with the highest probability.
dtree.py
def best(self): """ Returns the element with the highest probability. """ b = (-1e999999, None) for k, c in iteritems(self.counts): b = max(b, (c, k)) return b[1]
def best(self): """ Returns the element with the highest probability. """ b = (-1e999999, None) for k, c in iteritems(self.counts): b = max(b, (c, k)) return b[1]
[ "Returns", "the", "element", "with", "the", "highest", "probability", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L223-L230
[ "def", "best", "(", "self", ")", ":", "b", "=", "(", "-", "1e999999", ",", "None", ")", "for", "k", ",", "c", "in", "iteritems", "(", "self", ".", "counts", ")", ":", "b", "=", "max", "(", "b", ",", "(", "c", ",", "k", ")", ")", "return", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
DDist.probs
Returns a list of probabilities for all elements in the form [(value1,prob1),(value2,prob2),...].
dtree.py
def probs(self): """ Returns a list of probabilities for all elements in the form [(value1,prob1),(value2,prob2),...]. """ return [ (k, self.counts[k]/float(self.total)) for k in iterkeys(self.counts) ]
def probs(self): """ Returns a list of probabilities for all elements in the form [(value1,prob1),(value2,prob2),...]. """ return [ (k, self.counts[k]/float(self.total)) for k in iterkeys(self.counts) ]
[ "Returns", "a", "list", "of", "probabilities", "for", "all", "elements", "in", "the", "form", "[", "(", "value1", "prob1", ")", "(", "value2", "prob2", ")", "...", "]", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L260-L268
[ "def", "probs", "(", "self", ")", ":", "return", "[", "(", "k", ",", "self", ".", "counts", "[", "k", "]", "/", "float", "(", "self", ".", "total", ")", ")", "for", "k", "in", "iterkeys", "(", "self", ".", "counts", ")", "]" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
DDist.update
Adds the given distribution's counts to the current distribution.
dtree.py
def update(self, dist): """ Adds the given distribution's counts to the current distribution. """ assert isinstance(dist, DDist) for k, c in iteritems(dist.counts): self.counts[k] += c self.total += dist.total
def update(self, dist): """ Adds the given distribution's counts to the current distribution. """ assert isinstance(dist, DDist) for k, c in iteritems(dist.counts): self.counts[k] += c self.total += dist.total
[ "Adds", "the", "given", "distribution", "s", "counts", "to", "the", "current", "distribution", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L270-L277
[ "def", "update", "(", "self", ",", "dist", ")", ":", "assert", "isinstance", "(", "dist", ",", "DDist", ")", "for", "k", ",", "c", "in", "iteritems", "(", "dist", ".", "counts", ")", ":", "self", ".", "counts", "[", "k", "]", "+=", "c", "self", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
CDist.probability_lt
Returns the probability of a random variable being less than the given value.
dtree.py
def probability_lt(self, x): """ Returns the probability of a random variable being less than the given value. """ if self.mean is None: return return normdist(x=x, mu=self.mean, sigma=self.standard_deviation)
def probability_lt(self, x): """ Returns the probability of a random variable being less than the given value. """ if self.mean is None: return return normdist(x=x, mu=self.mean, sigma=self.standard_deviation)
[ "Returns", "the", "probability", "of", "a", "random", "variable", "being", "less", "than", "the", "given", "value", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L344-L351
[ "def", "probability_lt", "(", "self", ",", "x", ")", ":", "if", "self", ".", "mean", "is", "None", ":", "return", "return", "normdist", "(", "x", "=", "x", ",", "mu", "=", "self", ".", "mean", ",", "sigma", "=", "self", ".", "standard_deviation", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
CDist.probability_in
Returns the probability of a random variable falling between the given values.
dtree.py
def probability_in(self, a, b): """ Returns the probability of a random variable falling between the given values. """ if self.mean is None: return p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation) p2 = normdist(x=b, mu=self.mean, sigma=s...
def probability_in(self, a, b): """ Returns the probability of a random variable falling between the given values. """ if self.mean is None: return p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation) p2 = normdist(x=b, mu=self.mean, sigma=s...
[ "Returns", "the", "probability", "of", "a", "random", "variable", "falling", "between", "the", "given", "values", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L353-L362
[ "def", "probability_in", "(", "self", ",", "a", ",", "b", ")", ":", "if", "self", ".", "mean", "is", "None", ":", "return", "p1", "=", "normdist", "(", "x", "=", "a", ",", "mu", "=", "self", ".", "mean", ",", "sigma", "=", "self", ".", "standar...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
CDist.probability_gt
Returns the probability of a random variable being greater than the given value.
dtree.py
def probability_gt(self, x): """ Returns the probability of a random variable being greater than the given value. """ if self.mean is None: return p = normdist(x=x, mu=self.mean, sigma=self.standard_deviation) return 1-p
def probability_gt(self, x): """ Returns the probability of a random variable being greater than the given value. """ if self.mean is None: return p = normdist(x=x, mu=self.mean, sigma=self.standard_deviation) return 1-p
[ "Returns", "the", "probability", "of", "a", "random", "variable", "being", "greater", "than", "the", "given", "value", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L364-L372
[ "def", "probability_gt", "(", "self", ",", "x", ")", ":", "if", "self", ".", "mean", "is", "None", ":", "return", "p", "=", "normdist", "(", "x", "=", "x", ",", "mu", "=", "self", ".", "mean", ",", "sigma", "=", "self", ".", "standard_deviation", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Data.copy_no_data
Returns a copy of the object without any data.
dtree.py
def copy_no_data(self): """ Returns a copy of the object without any data. """ return type(self)( [], order=list(self.header_modes), types=self.header_types.copy(), modes=self.header_modes.copy())
def copy_no_data(self): """ Returns a copy of the object without any data. """ return type(self)( [], order=list(self.header_modes), types=self.header_types.copy(), modes=self.header_modes.copy())
[ "Returns", "a", "copy", "of", "the", "object", "without", "any", "data", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L667-L675
[ "def", "copy_no_data", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "[", "]", ",", "order", "=", "list", "(", "self", ".", "header_modes", ")", ",", "types", "=", "self", ".", "header_types", ".", "copy", "(", ")", ",", "modes", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Data.is_valid
Returns true if the given value matches the type for the given name according to the schema. Returns false otherwise.
dtree.py
def is_valid(self, name, value): """ Returns true if the given value matches the type for the given name according to the schema. Returns false otherwise. """ if name not in self.header_types: return False t = self.header_types[name] if t == AT...
def is_valid(self, name, value): """ Returns true if the given value matches the type for the given name according to the schema. Returns false otherwise. """ if name not in self.header_types: return False t = self.header_types[name] if t == AT...
[ "Returns", "true", "if", "the", "given", "value", "matches", "the", "type", "for", "the", "given", "name", "according", "to", "the", "schema", ".", "Returns", "false", "otherwise", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L710-L723
[ "def", "is_valid", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "not", "in", "self", ".", "header_types", ":", "return", "False", "t", "=", "self", ".", "header_types", "[", "name", "]", "if", "t", "==", "ATTR_TYPE_DISCRETE", ":", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Data._read_header
When a CSV file is given, extracts header information the file. Otherwise, this header data must be explicitly given when the object is instantiated.
dtree.py
def _read_header(self): """ When a CSV file is given, extracts header information the file. Otherwise, this header data must be explicitly given when the object is instantiated. """ if not self.filename or self.header_types: return rows = csv.reader(op...
def _read_header(self): """ When a CSV file is given, extracts header information the file. Otherwise, this header data must be explicitly given when the object is instantiated. """ if not self.filename or self.header_types: return rows = csv.reader(op...
[ "When", "a", "CSV", "file", "is", "given", "extracts", "header", "information", "the", "file", ".", "Otherwise", "this", "header", "data", "must", "be", "explicitly", "given", "when", "the", "object", "is", "instantiated", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L725-L753
[ "def", "_read_header", "(", "self", ")", ":", "if", "not", "self", ".", "filename", "or", "self", ".", "header_types", ":", "return", "rows", "=", "csv", ".", "reader", "(", "open", "(", "self", ".", "filename", ")", ")", "#header = rows.next()", "header...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Data.validate_row
Ensure each element in the row matches the schema.
dtree.py
def validate_row(self, row): """ Ensure each element in the row matches the schema. """ clean_row = {} if isinstance(row, (tuple, list)): assert self.header_order, "No attribute order specified." assert len(row) == len(self.header_order), \ ...
def validate_row(self, row): """ Ensure each element in the row matches the schema. """ clean_row = {} if isinstance(row, (tuple, list)): assert self.header_order, "No attribute order specified." assert len(row) == len(self.header_order), \ ...
[ "Ensure", "each", "element", "in", "the", "row", "matches", "the", "schema", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L755-L775
[ "def", "validate_row", "(", "self", ",", "row", ")", ":", "clean_row", "=", "{", "}", "if", "isinstance", "(", "row", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "self", ".", "header_order", ",", "\"No attribute order specified.\"", "assert", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Data.split
Returns two Data instances, containing the data randomly split between the two according to the given ratio. The first instance will contain the ratio of data specified. The second instance will contain the remaining ratio of data. If leave_one_out is True, the ratio wi...
dtree.py
def split(self, ratio=0.5, leave_one_out=False): """ Returns two Data instances, containing the data randomly split between the two according to the given ratio. The first instance will contain the ratio of data specified. The second instance will contain the remaining r...
def split(self, ratio=0.5, leave_one_out=False): """ Returns two Data instances, containing the data randomly split between the two according to the given ratio. The first instance will contain the ratio of data specified. The second instance will contain the remaining r...
[ "Returns", "two", "Data", "instances", "containing", "the", "data", "randomly", "split", "between", "the", "two", "according", "to", "the", "given", "ratio", ".", "The", "first", "instance", "will", "contain", "the", "ratio", "of", "data", "specified", ".", ...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L791-L822
[ "def", "split", "(", "self", ",", "ratio", "=", "0.5", ",", "leave_one_out", "=", "False", ")", ":", "a_labels", "=", "set", "(", ")", "a", "=", "self", ".", "copy_no_data", "(", ")", "b", "=", "self", ".", "copy_no_data", "(", ")", "for", "row", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node._get_attribute_value_for_node
Gets the closest value for the current node's attribute matching the given record.
dtree.py
def _get_attribute_value_for_node(self, record): """ Gets the closest value for the current node's attribute matching the given record. """ # Abort if this node has not get split on an attribute. if self.attr_name is None: return # O...
def _get_attribute_value_for_node(self, record): """ Gets the closest value for the current node's attribute matching the given record. """ # Abort if this node has not get split on an attribute. if self.attr_name is None: return # O...
[ "Gets", "the", "closest", "value", "for", "the", "current", "node", "s", "attribute", "matching", "the", "given", "record", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L896-L935
[ "def", "_get_attribute_value_for_node", "(", "self", ",", "record", ")", ":", "# Abort if this node has not get split on an attribute. ", "if", "self", ".", "attr_name", "is", "None", ":", "return", "# Otherwise, lookup the attribute value for this node in the", "# given record."...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_values
Retrieves the unique set of values seen for the given attribute at this node.
dtree.py
def get_values(self, attr_name): """ Retrieves the unique set of values seen for the given attribute at this node. """ ret = list(self._attr_value_cdist[attr_name].keys()) \ + list(self._attr_value_counts[attr_name].keys()) \ + list(self._branches.keys()) ...
def get_values(self, attr_name): """ Retrieves the unique set of values seen for the given attribute at this node. """ ret = list(self._attr_value_cdist[attr_name].keys()) \ + list(self._attr_value_counts[attr_name].keys()) \ + list(self._branches.keys()) ...
[ "Retrieves", "the", "unique", "set", "of", "values", "seen", "for", "the", "given", "attribute", "at", "this", "node", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L941-L950
[ "def", "get_values", "(", "self", ",", "attr_name", ")", ":", "ret", "=", "list", "(", "self", ".", "_attr_value_cdist", "[", "attr_name", "]", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ".",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_best_splitting_attr
Returns the name of the attribute with the highest gain.
dtree.py
def get_best_splitting_attr(self): """ Returns the name of the attribute with the highest gain. """ best = (-1e999999, None) for attr in self.attributes: best = max(best, (self.get_gain(attr), attr)) best_gain, best_attr = best return best_attr
def get_best_splitting_attr(self): """ Returns the name of the attribute with the highest gain. """ best = (-1e999999, None) for attr in self.attributes: best = max(best, (self.get_gain(attr), attr)) best_gain, best_attr = best return best_attr
[ "Returns", "the", "name", "of", "the", "attribute", "with", "the", "highest", "gain", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L956-L964
[ "def", "get_best_splitting_attr", "(", "self", ")", ":", "best", "=", "(", "-", "1e999999", ",", "None", ")", "for", "attr", "in", "self", ".", "attributes", ":", "best", "=", "max", "(", "best", ",", "(", "self", ".", "get_gain", "(", "attr", ")", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_entropy
Calculates the entropy of a specific attribute/value combination.
dtree.py
def get_entropy(self, attr_name=None, attr_value=None): """ Calculates the entropy of a specific attribute/value combination. """ is_con = self.tree.data.is_continuous_class if is_con: if attr_name is None: # Calculate variance of class attribute. ...
def get_entropy(self, attr_name=None, attr_value=None): """ Calculates the entropy of a specific attribute/value combination. """ is_con = self.tree.data.is_continuous_class if is_con: if attr_name is None: # Calculate variance of class attribute. ...
[ "Calculates", "the", "entropy", "of", "a", "specific", "attribute", "/", "value", "combination", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L966-L1026
[ "def", "get_entropy", "(", "self", ",", "attr_name", "=", "None", ",", "attr_value", "=", "None", ")", ":", "is_con", "=", "self", ".", "tree", ".", "data", ".", "is_continuous_class", "if", "is_con", ":", "if", "attr_name", "is", "None", ":", "# Calcula...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_gain
Calculates the information gain from splitting on the given attribute.
dtree.py
def get_gain(self, attr_name): """ Calculates the information gain from splitting on the given attribute. """ subset_entropy = 0.0 for value in iterkeys(self._attr_value_counts[attr_name]): value_prob = self.get_value_prob(attr_name, value) e = self.get_en...
def get_gain(self, attr_name): """ Calculates the information gain from splitting on the given attribute. """ subset_entropy = 0.0 for value in iterkeys(self._attr_value_counts[attr_name]): value_prob = self.get_value_prob(attr_name, value) e = self.get_en...
[ "Calculates", "the", "information", "gain", "from", "splitting", "on", "the", "given", "attribute", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1028-L1037
[ "def", "get_gain", "(", "self", ",", "attr_name", ")", ":", "subset_entropy", "=", "0.0", "for", "value", "in", "iterkeys", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ")", ":", "value_prob", "=", "self", ".", "get_value_prob", "(", "att...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_value_ddist
Returns the class value probability distribution of the given attribute value.
dtree.py
def get_value_ddist(self, attr_name, attr_value): """ Returns the class value probability distribution of the given attribute value. """ assert not self.tree.data.is_continuous_class, \ "Discrete distributions are only maintained for " + \ "discrete class ...
def get_value_ddist(self, attr_name, attr_value): """ Returns the class value probability distribution of the given attribute value. """ assert not self.tree.data.is_continuous_class, \ "Discrete distributions are only maintained for " + \ "discrete class ...
[ "Returns", "the", "class", "value", "probability", "distribution", "of", "the", "given", "attribute", "value", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1039-L1051
[ "def", "get_value_ddist", "(", "self", ",", "attr_name", ",", "attr_value", ")", ":", "assert", "not", "self", ".", "tree", ".", "data", ".", "is_continuous_class", ",", "\"Discrete distributions are only maintained for \"", "+", "\"discrete class types.\"", "ddist", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.get_value_prob
Returns the value probability of the given attribute at this node.
dtree.py
def get_value_prob(self, attr_name, value): """ Returns the value probability of the given attribute at this node. """ if attr_name not in self._attr_value_count_totals: return n = self._attr_value_counts[attr_name][value] d = self._attr_value_count_totals[att...
def get_value_prob(self, attr_name, value): """ Returns the value probability of the given attribute at this node. """ if attr_name not in self._attr_value_count_totals: return n = self._attr_value_counts[attr_name][value] d = self._attr_value_count_totals[att...
[ "Returns", "the", "value", "probability", "of", "the", "given", "attribute", "at", "this", "node", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1053-L1061
[ "def", "get_value_prob", "(", "self", ",", "attr_name", ",", "value", ")", ":", "if", "attr_name", "not", "in", "self", ".", "_attr_value_count_totals", ":", "return", "n", "=", "self", ".", "_attr_value_counts", "[", "attr_name", "]", "[", "value", "]", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.predict
Returns the estimated value of the class attribute for the given record.
dtree.py
def predict(self, record, depth=0): """ Returns the estimated value of the class attribute for the given record. """ # Check if we're ready to predict. if not self.ready_to_predict: raise NodeNotReadyToPredict # Lookup attribute value...
def predict(self, record, depth=0): """ Returns the estimated value of the class attribute for the given record. """ # Check if we're ready to predict. if not self.ready_to_predict: raise NodeNotReadyToPredict # Lookup attribute value...
[ "Returns", "the", "estimated", "value", "of", "the", "class", "attribute", "for", "the", "given", "record", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1070-L1105
[ "def", "predict", "(", "self", ",", "record", ",", "depth", "=", "0", ")", ":", "# Check if we're ready to predict.", "if", "not", "self", ".", "ready_to_predict", ":", "raise", "NodeNotReadyToPredict", "# Lookup attribute value.", "attr_value", "=", "self", ".", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.ready_to_split
Returns true if this node is ready to branch off additional nodes. Returns false otherwise.
dtree.py
def ready_to_split(self): """ Returns true if this node is ready to branch off additional nodes. Returns false otherwise. """ # Never split if we're a leaf that predicts adequately. threshold = self._tree.leaf_threshold if self._tree.data.is_continuous_class: ...
def ready_to_split(self): """ Returns true if this node is ready to branch off additional nodes. Returns false otherwise. """ # Never split if we're a leaf that predicts adequately. threshold = self._tree.leaf_threshold if self._tree.data.is_continuous_class: ...
[ "Returns", "true", "if", "this", "node", "is", "ready", "to", "branch", "off", "additional", "nodes", ".", "Returns", "false", "otherwise", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1112-L1132
[ "def", "ready_to_split", "(", "self", ")", ":", "# Never split if we're a leaf that predicts adequately.", "threshold", "=", "self", ".", "_tree", ".", "leaf_threshold", "if", "self", ".", "_tree", ".", "data", ".", "is_continuous_class", ":", "var", "=", "self", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.set_leaf_dist
Sets the probability distribution at a leaf node.
dtree.py
def set_leaf_dist(self, attr_value, dist): """ Sets the probability distribution at a leaf node. """ assert self.attr_name assert self.tree.data.is_valid(self.attr_name, attr_value), \ "Value %s is invalid for attribute %s." \ % (attr_value, self.attr_...
def set_leaf_dist(self, attr_value, dist): """ Sets the probability distribution at a leaf node. """ assert self.attr_name assert self.tree.data.is_valid(self.attr_name, attr_value), \ "Value %s is invalid for attribute %s." \ % (attr_value, self.attr_...
[ "Sets", "the", "probability", "distribution", "at", "a", "leaf", "node", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1134-L1156
[ "def", "set_leaf_dist", "(", "self", ",", "attr_value", ",", "dist", ")", ":", "assert", "self", ".", "attr_name", "assert", "self", ".", "tree", ".", "data", ".", "is_valid", "(", "self", ".", "attr_name", ",", "attr_value", ")", ",", "\"Value %s is inval...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Node.train
Incrementally update the statistics at this node.
dtree.py
def train(self, record): """ Incrementally update the statistics at this node. """ self.n += 1 class_attr = self.tree.data.class_attribute_name class_value = record[class_attr] # Update class statistics. is_con = self.tree.data.is_continuous_class...
def train(self, record): """ Incrementally update the statistics at this node. """ self.n += 1 class_attr = self.tree.data.class_attribute_name class_value = record[class_attr] # Update class statistics. is_con = self.tree.data.is_continuous_class...
[ "Incrementally", "update", "the", "statistics", "at", "this", "node", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1184-L1224
[ "def", "train", "(", "self", ",", "record", ")", ":", "self", ".", "n", "+=", "1", "class_attr", "=", "self", ".", "tree", ".", "data", ".", "class_attribute_name", "class_value", "=", "record", "[", "class_attr", "]", "# Update class statistics.", "is_con",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Tree.build
Constructs a classification or regression tree in a single batch by analyzing the given data.
dtree.py
def build(cls, data, *args, **kwargs): """ Constructs a classification or regression tree in a single batch by analyzing the given data. """ assert isinstance(data, Data) if data.is_continuous_class: fitness_func = gain_variance else: fitne...
def build(cls, data, *args, **kwargs): """ Constructs a classification or regression tree in a single batch by analyzing the given data. """ assert isinstance(data, Data) if data.is_continuous_class: fitness_func = gain_variance else: fitne...
[ "Constructs", "a", "classification", "or", "regression", "tree", "in", "a", "single", "batch", "by", "analyzing", "the", "given", "data", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1293-L1314
[ "def", "build", "(", "cls", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "data", ",", "Data", ")", "if", "data", ".", "is_continuous_class", ":", "fitness_func", "=", "gain_variance", "else", ":", "fitn...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Tree.out_of_bag_mae
Returns the mean absolute error for predictions on the out-of-bag samples.
dtree.py
def out_of_bag_mae(self): """ Returns the mean absolute error for predictions on the out-of-bag samples. """ if not self._out_of_bag_mae_clean: try: self._out_of_bag_mae = self.test(self.out_of_bag_samples) self._out_of_bag_mae_clean = ...
def out_of_bag_mae(self): """ Returns the mean absolute error for predictions on the out-of-bag samples. """ if not self._out_of_bag_mae_clean: try: self._out_of_bag_mae = self.test(self.out_of_bag_samples) self._out_of_bag_mae_clean = ...
[ "Returns", "the", "mean", "absolute", "error", "for", "predictions", "on", "the", "out", "-", "of", "-", "bag", "samples", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1331-L1342
[ "def", "out_of_bag_mae", "(", "self", ")", ":", "if", "not", "self", ".", "_out_of_bag_mae_clean", ":", "try", ":", "self", ".", "_out_of_bag_mae", "=", "self", ".", "test", "(", "self", ".", "out_of_bag_samples", ")", "self", ".", "_out_of_bag_mae_clean", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Tree.out_of_bag_samples
Returns the out-of-bag samples list, inside a wrapper to keep track of modifications.
dtree.py
def out_of_bag_samples(self): """ Returns the out-of-bag samples list, inside a wrapper to keep track of modifications. """ #TODO:replace with more a generic pass-through wrapper? class O(object): def __init__(self, tree): self.tree = tree ...
def out_of_bag_samples(self): """ Returns the out-of-bag samples list, inside a wrapper to keep track of modifications. """ #TODO:replace with more a generic pass-through wrapper? class O(object): def __init__(self, tree): self.tree = tree ...
[ "Returns", "the", "out", "-", "of", "-", "bag", "samples", "list", "inside", "a", "wrapper", "to", "keep", "track", "of", "modifications", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1345-L1365
[ "def", "out_of_bag_samples", "(", "self", ")", ":", "#TODO:replace with more a generic pass-through wrapper?", "class", "O", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "tree", ")", ":", "self", ".", "tree", "=", "tree", "def", "__len__", "("...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Tree.set_missing_value_policy
Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist.
dtree.py
def set_missing_value_policy(self, policy, target_attr_name=None): """ Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist. """ assert policy in MISSING_VALUE_POLICIES, \ ...
def set_missing_value_policy(self, policy, target_attr_name=None): """ Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist. """ assert policy in MISSING_VALUE_POLICIES, \ ...
[ "Sets", "the", "behavior", "for", "one", "or", "all", "attributes", "to", "use", "when", "traversing", "the", "tree", "using", "a", "query", "vector", "and", "it", "encounters", "a", "branch", "that", "does", "not", "exist", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1374-L1385
[ "def", "set_missing_value_policy", "(", "self", ",", "policy", ",", "target_attr_name", "=", "None", ")", ":", "assert", "policy", "in", "MISSING_VALUE_POLICIES", ",", "\"Unknown policy: %s\"", "%", "(", "policy", ",", ")", "for", "attr_name", "in", "self", ".",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Tree.train
Incrementally updates the tree with the given sample record.
dtree.py
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
[ "Incrementally", "updates", "the", "tree", "with", "the", "given", "sample", "record", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1415-L1423
[ "def", "train", "(", "self", ",", "record", ")", ":", "assert", "self", ".", "data", ".", "class_attribute_name", "in", "record", ",", "\"The class attribute must be present in the record.\"", "record", "=", "record", ".", "copy", "(", ")", "self", ".", "sample_...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest._fell_trees
Removes trees from the forest according to the specified fell method.
dtree.py
def _fell_trees(self): """ Removes trees from the forest according to the specified fell method. """ if callable(self.fell_method): for tree in self.fell_method(list(self.trees)): self.trees.remove(tree)
def _fell_trees(self): """ Removes trees from the forest according to the specified fell method. """ if callable(self.fell_method): for tree in self.fell_method(list(self.trees)): self.trees.remove(tree)
[ "Removes", "trees", "from", "the", "forest", "according", "to", "the", "specified", "fell", "method", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1470-L1476
[ "def", "_fell_trees", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "fell_method", ")", ":", "for", "tree", "in", "self", ".", "fell_method", "(", "list", "(", "self", ".", "trees", ")", ")", ":", "self", ".", "trees", ".", "remove", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest._get_best_prediction
Gets the prediction from the tree with the lowest mean absolute error.
dtree.py
def _get_best_prediction(self, record, train=True): """ Gets the prediction from the tree with the lowest mean absolute error. """ if not self.trees: return best = (+1e999999, None) for tree in self.trees: best = min(best, (tree.mae.mean, tree)) ...
def _get_best_prediction(self, record, train=True): """ Gets the prediction from the tree with the lowest mean absolute error. """ if not self.trees: return best = (+1e999999, None) for tree in self.trees: best = min(best, (tree.mae.mean, tree)) ...
[ "Gets", "the", "prediction", "from", "the", "tree", "with", "the", "lowest", "mean", "absolute", "error", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1478-L1489
[ "def", "_get_best_prediction", "(", "self", ",", "record", ",", "train", "=", "True", ")", ":", "if", "not", "self", ".", "trees", ":", "return", "best", "=", "(", "+", "1e999999", ",", "None", ")", "for", "tree", "in", "self", ".", "trees", ":", "...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest.best_oob_mae_weight
Returns weights so that the tree with smallest out-of-bag mean absolute error
dtree.py
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...
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" ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1492-L1505
[ "def", "best_oob_mae_weight", "(", "trees", ")", ":", "best", "=", "(", "+", "1e999999", ",", "None", ")", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", "i...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest.mean_oob_mae_weight
Returns weights proportional to the out-of-bag mean absolute error for each tree.
dtree.py
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: ...
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", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1508-L1523
[ "def", "mean_oob_mae_weight", "(", "trees", ")", ":", "weights", "=", "[", "]", "active_trees", "=", "[", "]", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest._grow_trees
Adds new trees to the forest according to the specified growth method.
dtree.py
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...
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", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1525-L1533
[ "def", "_grow_trees", "(", "self", ")", ":", "if", "self", ".", "grow_method", "==", "GROW_AUTO_INCREMENTAL", ":", "self", ".", "tree_kwargs", "[", "'auto_grow'", "]", "=", "True", "while", "len", "(", "self", ".", "trees", ")", "<", "self", ".", "size",...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest.predict
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.
dtree.py
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. """ ...
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", "tree...
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1539-L1582
[ "def", "predict", "(", "self", ",", "record", ")", ":", "# Get raw predictions.", "# {tree:raw prediction}", "predictions", "=", "{", "}", "for", "tree", "in", "self", ".", "trees", ":", "_p", "=", "tree", ".", "predict", "(", "record", ")", "if", "_p", ...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
Forest.train
Updates the trees with the given training record.
dtree.py
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...
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", "." ]
chrisspen/dtree
python
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1613-L1625
[ "def", "train", "(", "self", ",", "record", ")", ":", "self", ".", "_fell_trees", "(", ")", "self", ".", "_grow_trees", "(", ")", "for", "tree", "in", "self", ".", "trees", ":", "if", "random", ".", "random", "(", ")", "<", "self", ".", "sample_rat...
9e9c9992b22ad9a7e296af7e6837666b05db43ef
train
get_configfile_paths
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...
dwave/cloud/config.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L239-L304
[ "def", "get_configfile_paths", "(", "system", "=", "True", ",", "user", "=", "True", ",", "local", "=", "True", ",", "only_existing", "=", "True", ")", ":", "candidates", "=", "[", "]", "# system-wide has the lowest priority, `/etc/dwave/dwave.conf`", "if", "syste...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
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 file on an Ubuntu Unix system runnin...
dwave/cloud/config.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L336-L367
[ "def", "get_default_configfile_path", "(", ")", ":", "base", "=", "homebase", ".", "user_config_dir", "(", "app_author", "=", "CONF_AUTHOR", ",", "app_name", "=", "CONF_APP", ",", "roaming", "=", "False", ",", "use_virtualenv", "=", "False", ",", "create", "="...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
load_config_from_files
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 ...
dwave/cloud/config.py
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. ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L370-L468
[ "def", "load_config_from_files", "(", "filenames", "=", "None", ")", ":", "if", "filenames", "is", "None", ":", "filenames", "=", "get_configfile_paths", "(", ")", "config", "=", "configparser", ".", "ConfigParser", "(", "default_section", "=", "\"defaults\"", "...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
load_profile_from_files
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...
dwave/cloud/config.py
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....
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L471-L584
[ "def", "load_profile_from_files", "(", "filenames", "=", "None", ",", "profile", "=", "None", ")", ":", "# progressively build config from a file, or a list of auto-detected files", "# raises ConfigFileReadError/ConfigFileParseError on error", "config", "=", "load_config_from_files",...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
load_config
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...
dwave/cloud/config.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L619-L778
[ "def", "load_config", "(", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ")", ":", "if", "profile",...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
legacy_load_config
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...
dwave/cloud/config.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L781-L925
[ "def", "legacy_load_config", "(", "profile", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_parse_config", "(", "fp", ",", "file...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
_check_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.
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L41-L63
[ "def", "_check_data", "(", "data", ")", ":", "if", "not", "(", "data", ".", "dtype", "==", "_np", ".", "float32", "and", "data", ".", "flags", ".", "c_contiguous", ")", ":", "raise", "ValueError", "(", "'supplied data must be float32 and C contiguous'", ")", ...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
src_simple
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.
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L86-L102
[ "def", "src_simple", "(", "input_data", ",", "output_data", ",", "ratio", ",", "converter_type", ",", "channels", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "output_data",...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
src_new
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.
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L105-L124
[ "def", "src_new", "(", "converter_type", ",", "channels", ")", ":", "error", "=", "ffi", ".", "new", "(", "'int*'", ")", "state", "=", "_lib", ".", "src_new", "(", "converter_type", ",", "channels", ",", "error", ")", "return", "state", ",", "error", "...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
src_process
Standard processing function. Returns non zero on error.
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L135-L150
[ "def", "src_process", "(", "state", ",", "input_data", ",", "output_data", ",", "ratio", ",", "end_of_input", "=", "0", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "out...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
_src_input_callback
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...
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L184-L214
[ "def", "_src_input_callback", "(", "cb_data", ",", "data", ")", ":", "cb_data", "=", "ffi", ".", "from_handle", "(", "cb_data", ")", "ret", "=", "cb_data", "[", "'callback'", "]", "(", ")", "if", "ret", "is", "None", ":", "cb_data", "[", "'last_input'", ...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
src_callback_new
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. ...
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L217-L247
[ "def", "src_callback_new", "(", "callback", ",", "converter_type", ",", "channels", ")", ":", "cb_data", "=", "{", "'callback'", ":", "callback", ",", "'channels'", ":", "channels", "}", "handle", "=", "ffi", ".", "new_handle", "(", "cb_data", ")", "error", ...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
src_callback_read
Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error.
samplerate/lowlevel.py
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...
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", "." ]
tuxu/python-samplerate
python
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L250-L259
[ "def", "src_callback_read", "(", "state", ",", "ratio", ",", "frames", ",", "data", ")", ":", "data_ptr", "=", "ffi", ".", "cast", "(", "'float*f'", ",", "ffi", ".", "from_buffer", "(", "data", ")", ")", "return", "_lib", ".", "src_callback_read", "(", ...
ed73d7a39e61bfb34b03dade14ffab59aa27922a
train
Client.from_config
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...
dwave/cloud/client.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L168-L318
[ "def", "from_config", "(", "cls", ",", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "legacy_c...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client.close
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:...
dwave/cloud/client.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L427-L476
[ "def", "close", "(", "self", ")", ":", "# Finish all the work that requires the connection", "_LOGGER", ".", "debug", "(", "\"Joining submission queue\"", ")", "self", ".", "_submission_queue", ".", "join", "(", ")", "_LOGGER", ".", "debug", "(", "\"Joining cancel que...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client.get_solvers
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...
dwave/cloud/client.py
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_...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L553-L885
[ "def", "get_solvers", "(", "self", ",", "refresh", "=", "False", ",", "order_by", "=", "'avg_load'", ",", "*", "*", "filters", ")", ":", "def", "covers_op", "(", "prop", ",", "val", ")", ":", "\"\"\"Does LHS `prop` (range) fully cover RHS `val` (range or item)?\"\...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client.solvers
Deprecated in favor of :meth:`.get_solvers`.
dwave/cloud/client.py
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)
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L887-L890
[ "def", "solvers", "(", "self", ",", "refresh", "=", "False", ",", "*", "*", "filters", ")", ":", "warnings", ".", "warn", "(", "\"'solvers' is deprecated in favor of 'get_solvers'.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "get_solvers", "(", "r...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client.get_solver
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...
dwave/cloud/client.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L892-L955
[ "def", "get_solver", "(", "self", ",", "name", "=", "None", ",", "refresh", "=", "False", ",", "*", "*", "filters", ")", ":", "_LOGGER", ".", "debug", "(", "\"Requested a solver that best matches feature filters=%r\"", ",", "filters", ")", "# backward compatibilit...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._submit
Enqueue a problem for submission to the server. This method is thread safe.
dwave/cloud/client.py
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))
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L957-L962
[ "def", "_submit", "(", "self", ",", "body", ",", "future", ")", ":", "self", ".", "_submission_queue", ".", "put", "(", "self", ".", "_submit", ".", "Message", "(", "body", ",", "future", ")", ")" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._do_submit_problems
Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread.
dwave/cloud/client.py
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, #...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L965-L1025
[ "def", "_do_submit_problems", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Pull as many problems as we can, block on the first one,", "# but once we have one problem, switch to non-blocking then", "# submit without blocking again.", "# `None` task is used to signal thread ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._handle_problem_status
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 ...
dwave/cloud/client.py
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. ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1027-L1109
[ "def", "_handle_problem_status", "(", "self", ",", "message", ",", "future", ")", ":", "try", ":", "_LOGGER", ".", "trace", "(", "\"Handling response: %r\"", ",", "message", ")", "_LOGGER", ".", "debug", "(", "\"Handling response for %s with status %s\"", ",", "me...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._do_cancel_problems
Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread.
dwave/cloud/client.py
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. # ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1118-L1162
[ "def", "_do_cancel_problems", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Pull as many problems as we can, block when none are available.", "# `None` task is used to signal thread termination", "item", "=", "self", ".", "_cancel_queue", ".", "get", "(", ")",...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._poll
Enqueue a problem to poll the server for status.
dwave/cloud/client.py
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 ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1174-L1212
[ "def", "_poll", "(", "self", ",", "future", ")", ":", "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 t...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._do_poll_problems
Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread.
dwave/cloud/client.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1214-L1313
[ "def", "_do_poll_problems", "(", "self", ")", ":", "try", ":", "# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)", "frame_futures", "=", "{", "}", "def", "task_done", "(", ")", ":", "self", ".", "_poll_queue", ".", "task_done", "(", ")", "def", "add"...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
Client._do_load_results
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.
dwave/cloud/client.py
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: ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1325-L1370
[ "def", "_do_load_results", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Select a problem", "future", "=", "self", ".", "_load_queue", ".", "get", "(", ")", "# `None` task signifies thread termination", "if", "future", "is", "None", ":", "break", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
encode_bqm_as_qp
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...
dwave/cloud/coders.py
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]): ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L26-L70
[ "def", "encode_bqm_as_qp", "(", "solver", ",", "linear", ",", "quadratic", ")", ":", "active", "=", "active_qubits", "(", "linear", ",", "quadratic", ")", "# Encode linear terms. The coefficients of the linear terms of the objective", "# are encoded as an array of little endian...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
decode_qp
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.
dwave/cloud/coders.py
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 ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L73-L125
[ "def", "decode_qp", "(", "msg", ")", ":", "# Decode the simple buffers", "result", "=", "msg", "[", "'answer'", "]", "result", "[", "'active_variables'", "]", "=", "_decode_ints", "(", "result", "[", "'active_variables'", "]", ")", "active_variables", "=", "resu...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
_decode_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
dwave/cloud/coders.py
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
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L128-L141
[ "def", "_decode_byte", "(", "byte", ")", ":", "bits", "=", "[", "]", "for", "_", "in", "range", "(", "8", ")", ":", "bits", ".", "append", "(", "byte", "&", "1", ")", "byte", ">>=", "1", "return", "bits" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
_decode_ints
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.
dwave/cloud/coders.py
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('<' + (...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L144-L152
[ "def", "_decode_ints", "(", "message", ")", ":", "binary", "=", "base64", ".", "b64decode", "(", "message", ")", "return", "struct", ".", "unpack", "(", "'<'", "+", "(", "'i'", "*", "(", "len", "(", "binary", ")", "//", "4", ")", ")", ",", "binary"...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
_decode_doubles
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
dwave/cloud/coders.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L155-L169
[ "def", "_decode_doubles", "(", "message", ")", ":", "binary", "=", "base64", ".", "b64decode", "(", "message", ")", "return", "struct", ".", "unpack", "(", "'<'", "+", "(", "'d'", "*", "(", "len", "(", "binary", ")", "//", "8", ")", ")", ",", "bina...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
decode_qp_numpy
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`.
dwave/cloud/coders.py
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 ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L172-L240
[ "def", "decode_qp_numpy", "(", "msg", ",", "return_matrix", "=", "True", ")", ":", "import", "numpy", "as", "np", "result", "=", "msg", "[", "'answer'", "]", "# Build some little endian type encodings", "double_type", "=", "np", ".", "dtype", "(", "np", ".", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
evaluate_ising
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.
dwave/cloud/utils.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L49-L71
[ "def", "evaluate_ising", "(", "linear", ",", "quad", ",", "state", ")", ":", "# If we were given a numpy array cast to list", "if", "_numpy", "and", "isinstance", "(", "state", ",", "np", ".", "ndarray", ")", ":", "return", "evaluate_ising", "(", "linear", ",", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
active_qubits
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: ...
dwave/cloud/utils.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L74-L93
[ "def", "active_qubits", "(", "linear", ",", "quadratic", ")", ":", "active", "=", "{", "idx", "for", "idx", ",", "bias", "in", "uniform_iterator", "(", "linear", ")", "}", "for", "edge", ",", "_", "in", "six", ".", "iteritems", "(", "quadratic", ")", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
generate_random_ising_problem
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`.
dwave/cloud/utils.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L96-L110
[ "def", "generate_random_ising_problem", "(", "solver", ",", "h_range", "=", "None", ",", "j_range", "=", "None", ")", ":", "if", "h_range", "is", "None", ":", "h_range", "=", "solver", ".", "properties", ".", "get", "(", "'h_range'", ",", "[", "-", "1", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
uniform_iterator
Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.
dwave/cloud/utils.py
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)
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L113-L120
[ "def", "uniform_iterator", "(", "sequence", ")", ":", "if", "isinstance", "(", "sequence", ",", "abc", ".", "Mapping", ")", ":", "return", "six", ".", "iteritems", "(", "sequence", ")", "else", ":", "return", "enumerate", "(", "sequence", ")" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
uniform_get
Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.
dwave/cloud/utils.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L123-L130
[ "def", "uniform_get", "(", "sequence", ",", "index", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "sequence", ",", "abc", ".", "Mapping", ")", ":", "return", "sequence", ".", "get", "(", "index", ",", "default", ")", "else", ":", "...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
strip_head
Strips elements of `values` from the beginning of `sequence`.
dwave/cloud/utils.py
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))
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L133-L136
[ "def", "strip_head", "(", "sequence", ",", "values", ")", ":", "values", "=", "set", "(", "values", ")", "return", "list", "(", "itertools", ".", "dropwhile", "(", "lambda", "x", ":", "x", "in", "values", ",", "sequence", ")", ")" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
strip_tail
Strip `values` from the end of `sequence`.
dwave/cloud/utils.py
def strip_tail(sequence, values): """Strip `values` from the end of `sequence`.""" return list(reversed(list(strip_head(reversed(sequence), values))))
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L139-L141
[ "def", "strip_tail", "(", "sequence", ",", "values", ")", ":", "return", "list", "(", "reversed", "(", "list", "(", "strip_head", "(", "reversed", "(", "sequence", ")", ",", "values", ")", ")", ")", ")" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
click_info_switch
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, ...
dwave/cloud/utils.py
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...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L165-L190
[ "def", "click_info_switch", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "f", "(", ")", "ctx", ".", ...
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
datetime_to_timestamp
Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+.
dwave/cloud/utils.py
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()
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L193-L201
[ "def", "datetime_to_timestamp", "(", "dt", ")", ":", "epoch", "=", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ".", "replace", "(", "tzinfo", "=", "UTC", ")", "return", "(", "dt", "-", "epoch", ")", ".", "total_seconds", "(", ")" ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
train
user_agent
Return User-Agent ~ "name/version language/version interpreter/version os/version".
dwave/cloud/utils.py
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': ...
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", "." ]
dwavesystems/dwave-cloud-client
python
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L252-L275
[ "def", "user_agent", "(", "name", ",", "version", ")", ":", "def", "_interpreter", "(", ")", ":", "name", "=", "platform", ".", "python_implementation", "(", ")", "version", "=", "platform", ".", "python_version", "(", ")", "bitness", "=", "platform", ".",...
df3221a8385dc0c04d7b4d84f740bf3ad6706230