code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('Given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_lab... | def predict(self, X) | r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector. | 2.989619 | 3.067501 | 0.97461 |
r
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_lab... | def predict_real(self, X) | r"""Predict the probability of being 1 for each label.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted probability of each label. | 3.206027 | 3.299707 | 0.971609 |
# TODO check if data in dataset are all correct
X, Y = testing_dataset.format_sklearn()
if criterion == 'hamming':
return np.mean(np.abs(self.predict(X) - Y).mean(axis=1))
elif criterion == 'f1':
Z = self.predict(X)
Z = Z.astype(int)
... | def score(self, testing_dataset, criterion='hamming') | Return the mean accuracy on the test dataset
Parameters
----------
testing_dataset : Dataset object
The testing dataset used to measure the perforance of the trained
model.
criterion : ['hamming', 'f1']
instance-wise criterion.
Returns
... | 3.06123 | 3.053513 | 1.002527 |
if self.w_ is not None:
sigmoid = lambda t: 1. / (1. + np.exp(-t))
return sigmoid(np.dot(self.centers, self.w_[:-1]) + self.w_[-1])
else:
# TODO the model is not trained
pass | def predict(self) | Returns
-------
proba : ndarray, shape=(n_clusters, )
The probability of given cluster being label 1. | 4.484375 | 4.057502 | 1.105206 |
def fit(self, X, y=None, init=None):
self.fit_transform(X, init=init)
return self | Computes the position of the points in the embedding space
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
init : {None or ndarray, shape (n_samples,)}, optional
... | null | null | null | |
def fit_transform(self, X, y=None, init=None):
X = check_array(X)
if X.shape[0] == X.shape[1] and self.dissimilarity != "precomputed":
warnings.warn("The MDS API has changed. ``fit`` now constructs an"
" dissimilarity matrix from data. To use a custom ... | Fit the data from X, and returns the embedded coordinates
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
init : {None or ndarray, shape (n_samples,)}, optional
... | null | null | null | |
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed) | def seed_random_state(seed) | Turn seed into np.random.RandomState instance | 2.603577 | 2.217435 | 1.174139 |
return np.mean(cost_matrix[list(y), list(yhat)]) | def calc_cost(y, yhat, cost_matrix) | Calculate the cost with given cost matrix
y : ground truth
yhat : estimation
cost_matrix : array-like, shape=(n_classes, n_classes)
The ith row, jth column represents the cost of the ground truth being
ith class and prediction as jth class. | 3.98221 | 7.614255 | 0.522994 |
dataset = self.dataset
self.model.train(dataset)
unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries())
if isinstance(self.model, ProbabilisticModel):
dvalue = self.model.predict_proba(X_pool)
elif isinstance(self.model, ContinuousModel):
... | def make_query(self, return_score=False) | Return the index of the sample to be queried and labeled and
selection score of each sample. Read-only.
No modification to the internal states.
Returns
-------
ask_id : int
The index of the next unlabeled sample to be queried and labeled.
score : list of (i... | 3.164944 | 3.061051 | 1.03394 |
ret = []
for candidate in votes:
ret.append(0.0)
lab_count = {}
for lab in candidate:
lab_count[lab] = lab_count.setdefault(lab, 0) + 1
# Using vote entropy to measure disagreement
for lab in lab_count.keys():
... | def _vote_disagreement(self, votes) | Return the disagreement measurement of the given number of votes.
It uses the vote vote to measure the disagreement.
Parameters
----------
votes : list of int, shape==(n_samples, n_students)
The predictions that each student gives to each sample.
Returns
---... | 3.567094 | 3.194644 | 1.116586 |
n_students = np.shape(proba)[1]
consensus = np.mean(proba, axis=1) # shape=(n_samples, n_class)
# average probability of each class across all students
consensus = np.tile(consensus, (n_students, 1, 1)).transpose(1, 0, 2)
kl = np.sum(proba * np.log(proba / consensus), ax... | def _kl_divergence_disagreement(self, proba) | Calculate the Kullback-Leibler (KL) divergence disaagreement measure.
Parameters
----------
proba : array-like, shape=(n_samples, n_students, n_class)
Returns
-------
disagreement : list of float, shape=(n_samples)
The kl_divergence of the given probability. | 3.172951 | 3.093796 | 1.025585 |
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples)) | def _labeled_uniform_sample(self, sample_size) | sample labeled entries uniformly | 4.984657 | 4.410181 | 1.130261 |
dataset = self.dataset
for student in self.students:
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
while bag.get_num_of_labels() != dataset.get_num_of_labels():
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
... | def teach_students(self) | Train each model (student) with the labeled data using bootstrap
aggregating (bagging). | 6.706908 | 6.032181 | 1.111855 |
model = copy.copy(self.model)
model.train(self.dataset)
# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)
reward = 0.
for i in range(len(self.queried_hist_)):
reward += self.W[i] * (
model.predict(
self.dat... | def calc_reward_fn(self) | Calculate the reward value | 5.289376 | 5.345384 | 0.989522 |
# initial query
if self.query_dist is None:
self.query_dist = self.exp4p_.next(-1, None, None)
else:
self.query_dist = self.exp4p_.next(
self.calc_reward_fn(),
self.queried_hist_[-1],
self.dataset.data[self.queried_... | def calc_query(self) | Calculate the sampling query distribution | 7.247103 | 6.785662 | 1.068002 |
# first run don't have reward, TODO exception on reward == -1 only once
if reward == -1:
return next(self.exp4p_gen)
else:
# TODO exception on reward in [0, 1]
return self.exp4p_gen.send((reward, ask_id, lbl)) | def next(self, reward, ask_id, lbl) | Taking the label and the reward value of last question and returns
the next question to ask. | 9.57969 | 10.186291 | 0.940449 |
while True:
# TODO probabilistic active learning algorithm
# len(self.unlabeled_invert_id_idx) is the number of unlabeled data
query = np.zeros((self.N, len(self.unlabeled_invert_id_idx)))
if self.uniform_sampler:
query[-1, :] = 1. / len(s... | def exp4p(self) | The generator which implements the main part of Exp4.P.
Parameters
----------
reward: float
The reward value calculated from ALBL.
ask_id: integer
The entry_id of the sample point ALBL asked.
lbl: integer
The answer received from asking the ... | 6.138509 | 5.350557 | 1.147265 |
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist()) | def import_libsvm_sparse(filename) | Imports dataset file in libsvm sparse format | 2.291934 | 2.381439 | 0.962415 |
self.data.append((feature, label))
self.modified = True
return len(self.data) - 1 | def append(self, feature, label=None) | Add a (feature, label) entry into the dataset.
A None label indicates an unlabeled entry.
Parameters
----------
feature : {array-like}, shape = (n_features)
Feature of the sample to append to dataset.
label : {int, None}
Label of the sample to append to ... | 3.81519 | 5.6489 | 0.675386 |
self.data[entry_id] = (self.data[entry_id][0], new_label)
self.modified = True
for callback in self._update_callback:
callback(entry_id, new_label) | def update(self, entry_id, new_label) | Updates an entry with entry_id with the given label
Parameters
----------
entry_id : int
entry id of the sample to update.
label : {int, None}
Label of the sample to be update. | 2.896252 | 3.566644 | 0.812039 |
X, y = zip(*self.get_labeled_entries())
return np.array(X), np.array(y) | def format_sklearn(self) | Returns dataset in (X, y) format for use in scikit-learn.
Unlabeled entries are ignored.
Returns
-------
X : numpy array, shape = (n_samples, n_features)
Sample feature set.
y : numpy array, shape = (n_samples)
Sample labels. | 6.053194 | 4.777668 | 1.266977 |
return [
(idx, entry[0]) for idx, entry in enumerate(self.data)
if entry[1] is None
] | def get_unlabeled_entries(self) | Returns list of unlabeled features, along with their entry_ids
Returns
-------
unlabeled_entries : list of (entry_id, feature) tuple
Labeled entries | 4.681275 | 5.753983 | 0.813571 |
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)
return Dataset(*zip(*samples)) | def labeled_uniform_sample(self, sample_size, replace=True) | Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size | 2.9887 | 3.332221 | 0.896909 |
''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
'''
num_consumed_args = _num_consumed_args.get(action, 0)
if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
return True
if action.nargs == ONE_OR_MORE:
return num... | def action_is_satisfied(action) | Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise. | 5.037715 | 3.92449 | 1.283661 |
''' Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -).
'''
num_consumed_args = _num_consumed_args.get(action, 0)
if action.option_strings:
if not isoptional and not action_is_satisfied(action):
... | def action_is_greedy(action, isoptional=False) | Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -). | 6.678809 | 3.698914 | 1.805613 |
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok) | def push_token(self, tok) | Push a token onto the stack popped by the get_token method | 7.660406 | 5.763319 | 1.329166 |
"Pop the input source stack."
self.instream.close()
(self.infile, self.instream, self.lineno) = self.filestack.popleft()
if self.debug:
print('shlex: popping to %s, line %d' \
% (self.instream, self.lineno))
self.state = ' ' | def pop_source(self) | Pop the input source stack. | 7.297515 | 6.707995 | 1.087883 |
self.active_parsers = []
self.visited_positionals = []
completer = self
def patch(parser):
completer.visited_positionals.append(parser)
completer.active_parsers.append(parser)
if isinstance(parser, IntrospectiveArgumentParser):
... | def _patch_argument_parser(self) | Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and
all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser
figure out which subparsers need to be activated (then recursively monkey-patc... | 3.237893 | 3.142784 | 1.030263 |
completions = []
debug("all active parsers:", active_parsers)
active_parser = active_parsers[-1]
debug("active_parser:", active_parser)
if self.always_complete_options or (len(cword_prefix) > 0 and cword_prefix[0] in active_parser.prefix_chars):
completions ... | def collect_completions(self, active_parsers, parsed_args, cword_prefix, debug) | Visits the active parsers and their actions, executes their completers or introspects them to collect their
option strings. Returns the resulting completions as a list of strings.
This method is exposed for overriding in subclasses; there is no need to use it directly. | 3.063665 | 3.114636 | 0.983635 |
active_parser = self.active_parsers[-1]
last_positional = self.visited_positionals[-1]
all_positionals = active_parser._get_positional_actions()
if not all_positionals:
return None
if active_parser == last_positional:
return all_positionals[0]
... | def _get_next_positional(self) | Get the next positional action if it exists. | 2.707493 | 2.518297 | 1.075129 |
# On Python 2, we have to make sure all completions are unicode objects before we continue and output them.
# Otherwise, because python disobeys the system locale encoding and uses ascii as the default encoding, it will
# try to implicitly decode string objects using ascii, and fail.
... | def filter_completions(self, completions) | Ensures collected completions are Unicode text, de-duplicates them, and excludes those specified by ``exclude``.
Returns the filtered completions as an iterable.
This method is exposed for overriding in subclasses; there is no need to use it directly. | 7.140364 | 6.090218 | 1.172432 |
special_chars = "\\"
# If the word under the cursor was quoted, escape the quote char.
# Otherwise, escape all special characters and specially handle all COMP_WORDBREAKS chars.
if cword_prequote == "":
# Bash mangles completions which contain characters in COMP_WORD... | def quote_completions(self, completions, cword_prequote, last_wordbreak_pos) | If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each completion.
Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), an... | 6.748539 | 6.134274 | 1.100137 |
if state == 0:
cword_prequote, cword_prefix, cword_suffix, comp_words, first_colon_pos = split_line(text)
comp_words.insert(0, sys.argv[0])
matches = self._get_completions(comp_words, cword_prefix, cword_prequote, first_colon_pos)
self._rl_matches = [text... | def rl_complete(self, text, state) | Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
`rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_.
Usage:
.. code-block:: python
import argcomplete, argparse, readline
parser = argparse.Arg... | 3.980925 | 4.014974 | 0.991519 |
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.... | def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None) | Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param ... | 4.454965 | 1.984803 | 2.244538 |
params = {
'V': SMSPUBLI_API_VERSION,
'UN': SMSPUBLI_USERNAME,
'PWD': SMSPUBLI_PASSWORD,
'R': SMSPUBLI_ROUTE,
'SA': message.from_phone,
'DA': ','.join(message.to),
'M': message.body.encode('latin-1'),
'D... | def _send(self, message) | Private method for send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sended else False
:rtype: bool | 3.963265 | 3.904989 | 1.014924 |
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname | def _get_filename(self) | Return a unique file name. | 2.765625 | 2.405198 | 1.149853 |
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' : self.get_password(),
'country' : SMSGLOBAL_CHECK_BALANCE_COUN... | def get_balance(self) | Get balance with provider. | 4.27358 | 4.188765 | 1.020248 |
if not sms_messages:
return
num_sent = 0
for message in sms_messages:
if self._send(message):
num_sent += 1
return num_sent | def send_messages(self, sms_messages) | Sends one or more SmsMessage objects and returns the number of sms
messages sent. | 2.728685 | 2.894152 | 0.942827 |
charset='UTF-8'
params = {
'action' : 'sendsms',
'user' : self.get_username(),
'password' : self.get_password(),
'from' : message.from_phone,
'to' : ",".join(message.to),
'text' : message.body,
'clientcharset' : charset,
... | def _send(self, message) | A helper method that does the actual sending. | 3.468219 | 3.41533 | 1.015486 |
# Sample result_page, single line -> "OK: 0; Sent queued message ID: 2063619577732703 SMSGlobalMsgID:6171799108850954"
resultline = result_page.splitlines()[0] # get result line
if resultline.startswith('ERROR:'):
raise Exception(resultline.replace('ERROR: ', ''))
pa... | def _parse_response(self, result_page) | Takes a result page of sending the sms, returns an extracted tuple:
('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>')
Returns None if unable to extract info from result_page, it should be
safe to assume that it was either a failed result or worse, the interface
con... | 5.803047 | 4.592879 | 1.263488 |
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
return SmsMessage(body=body, from_phone=from_phone, to=to, \
flash=flash, connection=connection).send() | def send_sms(body, from_phone, to, flash=False, fail_silently=False,
auth_user=None, auth_password=None, connection=None) | Easy wrapper for send a single SMS to a recipient list.
:returns: the number of SMSs sent. | 2.625983 | 3.826575 | 0.686249 |
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
messages = [SmsMessage(message=message, from_phone=from_phone, to=to, flash=flash)
for message, ... | def send_mass_sms(datatuple, fail_silently=False,
auth_user=None, auth_password=None, connection=None) | Given a datatuple of (message, from_phone, to, flash), sends each message to each
recipient list.
:returns: the number of SMSs sent. | 2.78578 | 2.563744 | 1.086606 |
path = path or getattr(settings, 'SENDSMS_BACKEND', 'sendsms.backends.locmem.SmsBackend')
try:
mod_name, klass_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except AttributeError as e:
raise ImproperlyConfigured(u'Error importing sms backend module %s: "%s"' % (mod_n... | def get_connection(path=None, fail_silently=False, **kwargs) | Load an sms backend and return an instance of it.
:param string path: backend python path. Default: sendsms.backends.console.SmsBackend
:param bool fail_silently: Flag to not throw exceptions on error. Default: False
:returns: backend class instance.
:rtype: :py:class:`~sendsms.backends.base.BaseSmsBac... | 2.058221 | 1.894062 | 1.086671 |
self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''),
getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''),
getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2),
getattr(settings, 'SMS_SLUZBA_API_... | def open(self) | Initializes sms.sluzba.cz API library. | 3.942961 | 2.687036 | 1.467402 |
count = 0
for message in messages:
message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore')
for tel_number in message.to:
try:
self.client.send(tel_number, message_body, getattr(settings, 'SMS_SLUZB... | def send_messages(self, messages) | Sending SMS messages via sms.sluzba.cz API.
Note:
This method returns number of actually sent sms messages
not number of SmsMessage instances processed.
:param messages: list of sms messages
:type messages: list of sendsms.message.SmsMessage instances
:returns: numb... | 4.29078 | 3.35094 | 1.280471 |
if not messages:
return
self._lock.acquire()
try:
# The try-except is nested to allow for
# Python 2.4 support (Refs #12147)
try:
stream_created = self.open()
for message in messages:
sel... | def send_messages(self, messages) | Write all messages to the stream in a thread-safe way. | 3.975415 | 3.682756 | 1.079467 |
response_dict = {}
for line in response.splitlines():
key, value = response.split("=", 1)
response_dict[key] = value
return response_dict | def _parse_response(self, response) | Parse http raw respone into python
dictionary object.
:param str response: http response
:returns: response dict
:rtype: dict | 3.687561 | 3.264046 | 1.129751 |
params = {
'EsendexUsername': self.get_username(),
'EsendexPassword': self.get_password(),
'EsendexAccount': self.get_account(),
'EsendexOriginator': message.from_phone,
'EsendexRecipient': ",".join(message.to),
'EsendexBody': m... | def _send(self, message) | Private method to send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool | 3.046465 | 2.959503 | 1.029384 |
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'load_object' must "
"contain at least one dot."
)
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | def load_object(import_path) | Shamelessly stolen from https://github.com/ojii/django-load
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
fro... | 2.226087 | 2.403814 | 0.926065 |
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=self.body)
return res | def send(self, fail_silently=False) | Sends the sms message | 4.40159 | 4.280941 | 1.028183 |
params = {
'from': message.from_phone,
'to': ",".join(message.to),
'text': message.body,
'api_key': self.get_api_key(),
'api_secret': self.get_api_secret(),
}
print(params)
logger.debug("POST to %r with body: %r", ... | def _send(self, message) | A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool | 3.884158 | 3.704304 | 1.048553 |
counter = 0
for message in messages:
res, _ = self._send(message)
if res:
counter += 1
return counter | def send_messages(self, messages) | Send messages.
:param list messages: List of SmsMessage instances.
:returns: number of messages sended successful.
:rtype: int | 4.285751 | 4.568785 | 0.938051 |
if not options:
options = {}
if self.api_version not in path_dict:
raise Exception('method call not available under API version {}'.format(self.api_version))
request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1
request_url = r... | def _api_query(self, protection=None, path_dict=None, options=None) | Queries Bittrex
:param request_url: fully-formed URL to request
:type options: dict
:return: JSON response from Bittrex
:rtype : dict | 2.751312 | 2.729433 | 1.008016 |
return self._api_query(path_dict={
API_V1_1: '/public/getmarketsummary',
API_V2_0: '/pub/Market/GetMarketSummary'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | def get_market_summary(self, market) | Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchang... | 7.111793 | 5.811693 | 1.223704 |
return self._api_query(path_dict={
API_V1_1: '/public/getorderbook',
API_V2_0: '/pub/Market/GetMarketOrderBook'
}, options={'market': market, 'marketname': market, 'type': depth_type}, protection=PROTECTION_PUB) | def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK) | Used to get retrieve the orderbook for a given market.
The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned
Endpoint:
1.1 /public/getorderbook
2.0 /pub/Market/GetMarketOrderBook
:param market: String literal for the market (ex: BTC-LTC)
... | 6.947748 | 5.091065 | 1.364694 |
return self._api_query(path_dict={
API_V1_1: '/public/getmarkethistory',
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | def get_market_history(self, market) | Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'result': [ {'Id': 5625015,
'TimeStamp'... | 10.875722 | 11.527325 | 0.943473 |
return self._api_query(path_dict={
API_V1_1: '/market/buylimit',
}, options={'market': market,
'quantity': quantity,
'rate': rate}, protection=PROTECTION_PRV) | def buy_limit(self, market, quantity, rate) | Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
Endpoint:
1.1 /market/buylimit
2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys
:par... | 8.950755 | 8.139032 | 1.099732 |
return self._api_query(path_dict={
API_V1_1: '/market/getopenorders',
API_V2_0: '/key/market/getopenorders'
}, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV) | def get_open_orders(self, market=None) | Get all orders that you currently have opened.
A specific market can be requested.
Endpoint:
1.1 /market/getopenorders
2.0 /key/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
... | 7.812674 | 6.093313 | 1.282172 |
return self._api_query(path_dict={
API_V1_1: '/account/getdepositaddress',
API_V2_0: '/key/balance/getdepositaddress'
}, options={'currency': currency, 'currencyname': currency}, protection=PROTECTION_PRV) | def get_deposit_address(self, currency) | Used to generate or retrieve an address for a specific currency
Endpoint:
1.1 /account/getdepositaddress
2.0 /key/balance/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict | 8.807233 | 6.165888 | 1.42838 |
options = {
'currency': currency,
'quantity': quantity,
'address': address
}
if paymentid:
options['paymentid'] = paymentid
return self._api_query(path_dict={
API_V1_1: '/account/withdraw',
API_V2_0: '/key/b... | def withdraw(self, currency, quantity, address, paymentid=None) | Used to withdraw funds from your account
Endpoint:
1.1 /account/withdraw
2.0 /key/balance/withdrawcurrency
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
... | 4.610993 | 3.579692 | 1.288098 |
if market:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/market/GetOrderHistory'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PRV)
else:
return self._api_... | def get_order_history(self, market=None) | Used to retrieve order trade history of account
Endpoint:
1.1 /account/getorderhistory
2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory
:param market: optional a string literal for the market (ie. BTC-LTC).
If omitted, will return for all markets
:type... | 3.677668 | 2.714046 | 1.35505 |
return self._api_query(path_dict={
API_V1_1: '/account/getorder',
API_V2_0: '/key/orders/getorder'
}, options={'uuid': uuid, 'orderid': uuid}, protection=PROTECTION_PRV) | def get_order(self, uuid) | Used to get details of buy or sell order
Endpoint:
1.1 /account/getorder
2.0 /key/orders/getorder
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict | 9.532585 | 6.282418 | 1.517343 |
return [market['MarketName'] for market in self.get_markets()['result']
if market['MarketName'].lower().endswith(currency.lower())] | def list_markets_by_currency(self, currency) | Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type curren... | 4.329244 | 4.870522 | 0.888866 |
return self._api_query(path_dict={
API_V2_0: '/key/balance/getpendingwithdrawals'
}, options={'currencyname': currency} if currency else None,
protection=PROTECTION_PRV) | def get_pending_withdrawals(self, currency=None) | Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending withdrawals in JSON
:rtype : list | 16.775038 | 13.029964 | 1.28742 |
return self._api_query(path_dict={
API_V2_0: '/key/market/tradesell'
}, options={
'marketname': market,
'ordertype': order_type,
'quantity': quantity,
'rate': rate,
'timeInEffect': time_in_effect,
'conditiontype... | def trade_sell(self, market=None, order_type=None, quantity=None, rate=None, time_in_effect=None,
condition_type=None, target=0.0) | Enter a sell order into the book
Endpoint
1.1 NO EQUIVALENT -- see sell_market or sell_limit
2.0 /key/market/tradesell
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param order_type: ORDERTYPE_LIMIT = 'LIMIT' or ORDERTYPE_MARKET = 'MARKET'... | 4.191787 | 3.779781 | 1.109003 |
return self._api_query(path_dict={
API_V2_0: '/pub/market/GetTicks'
}, options={
'marketName': market, 'tickInterval': tick_interval
}, protection=PROTECTION_PUB) | def get_candles(self, market, tick_interval) | Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20... | 10.371889 | 7.970278 | 1.301321 |
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
... | def changelist_view(self, request, extra_context=None) | Add advanced_filters form to changelist context | 3.826398 | 3.405147 | 1.12371 |
return self.filter(Q(users=user) | Q(groups__in=user.groups.all())) | def filter_by_user(self, user) | All filters that should be displayed to a user (by users/group) | 4.14145 | 3.841561 | 1.078064 |
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query) | def query(self) | De-serialize, decode and return an ORM query stored in b64_query. | 6.761565 | 3.81443 | 1.772628 |
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value) | def query(self, value) | Serialize an ORM query, Base-64 encode it and set it to
the b64_query field | 11.627123 | 7.660866 | 1.51773 |
children = []
for child in q.children:
if isinstance(child, Q):
children.append(self.serialize(child))
else:
children.append(child)
serialized = q.__dict__
serialized['children'] = children
return serialized | def serialize(self, q) | Serialize a Q object into a (possibly nested) dict. | 2.602676 | 2.163932 | 1.202753 |
children = []
for child in d.pop('children'):
if isinstance(child, dict):
children.append(self.deserialize(child))
else:
children.append(self.prepare_value(child))
query = Q()
query.children = children
query.connect... | def deserialize(self, d) | De-serialize a Q object from a (possibly nested) dict. | 3.022664 | 2.68916 | 1.124018 |
fields = []
children = d.get('children', [])
for child in children:
if isinstance(child, dict):
fields.extend(self.get_field_values_list(child))
else:
f = {'field': child[0], 'value': child[1]}
if self._is_range(chi... | def get_field_values_list(self, d) | Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',
'value_to': 'optional_range_val2',
... | 3.147017 | 2.457589 | 1.28053 |
res = super(VaryingTypeCharField, self).to_python(value)
split_res = res.split(self._default_separator)
if not res or len(split_res) < 2:
return res.strip()
# create a regex string out of the list of choices passed, i.e: (a|b)
res = r"({pattern})".format(pat... | def to_python(self, value) | Split a string value by separator (default to ",") into a
list; then, returns a regex pattern string that ORs the values
in the resulting list.
>>> field = VaryingTypeCharField()
>>> assert field.to_python('') == ''
>>> assert field.to_python('test') == 'test'
>>> assert... | 5.838772 | 5.085393 | 1.148146 |
cleaned_data = super(CleanWhiteSpacesMixin, self).clean()
for k in self.cleaned_data:
if isinstance(self.cleaned_data[k], six.string_types):
cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
self.cleaned_data[k] or '').strip... | def clean(self) | >>> import django.forms
>>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
... some_field = django.forms.CharField()
>>>
>>> form = MyForm({'some_field': ' a weird value '})
>>> assert form.is_valid()
>>> assert form.cleaned_data == {'some_field': 'a weird... | 3.395335 | 3.263943 | 1.040256 |
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES | def _build_field_choices(self, fields) | Iterate over passed model fields tuple and update initial choices. | 7.958596 | 7.121741 | 1.117507 |
if self.is_valid() and formdata is None:
formdata = self.cleaned_data
key = "{field}__{operator}".format(**formdata)
if formdata['operator'] == "isnull":
return {key: None}
elif formdata['operator'] == "istrue":
return {formdata['field']: True... | def _build_query_dict(self, formdata=None) | Take submitted data from form and create a query dict to be
used in a Q object (or filter) | 2.622666 | 2.57996 | 1.016553 |
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if parts[-1] in dict(AdvancedFilter... | def _parse_query_dict(query_data, model) | Take a list of query field dict and return data for form initialization | 2.734641 | 2.698817 | 1.013274 |
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto) | def set_range_value(self, data) | Validates date range by parsing into 2 datetime objects and
validating them both. | 5.920473 | 5.061445 | 1.16972 |
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**query_dict)
return query | def make_query(self, *args, **kwargs) | Returns a Q object from the submitted form | 3.406197 | 3.037163 | 1.121506 |
model_fields = {}
for field in fields:
if isinstance(field, tuple) and len(field) == 2:
field, verbose_name = field[0], field[1]
else:
try:
model_field = get_fields_from_path(model, field)[-1]
... | def get_fields_from_model(self, model, fields) | Iterate over given <field> names (in "orm query" notation) and find
the actual field given the initial <model>.
If <field> is a tuple of the format ('field_name', 'Verbose name'),
overwrite the field's verbose name with the given name for display
purposes. | 3.263205 | 3.382766 | 0.964656 |
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
quer... | def generate_query(self) | Reduces multiple queries into a single usable query | 4.206623 | 3.860088 | 1.089774 |
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse_query_dict(
field_data, model))
... | def initialize_form(self, instance, model, data=None, extra=None) | Takes a "finalized" query and generate it's form data | 6.210246 | 6.111759 | 1.016114 |
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))
... | def login() | This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
ro... | 2.38968 | 2.273954 | 1.050892 |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session... | def logout() | When the user accesses this route they are logged out. | 1.831227 | 1.808865 | 1.012363 |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERV... | def validate(ticket) | Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTE... | 2.528654 | 2.359308 | 1.071778 |
url = base
# Add the path to the url if it's not None.
if path is not None:
url = urljoin(url, quote(path))
# Remove key/value pairs with None values.
query = filter(lambda pair: pair[1] is not None, query)
# Add the query string to the url
url = urljoin(url, '?{0}'.format(urlen... | def create_url(base, path=None, *query) | Create a url.
Creates a url by combining base, path, and the query's list of
key/value pairs. Escaping is handled automatically. Any
key/value pair with a value that is None is ignored.
Keyword arguments:
base -- The left most part of the url (ex. http://localhost:5000).
path -- The path after... | 2.841681 | 3.041847 | 0.934196 |
return create_url(
cas_url,
cas_route,
('service', service),
('renew', renew),
('gateway', gateway),
) | def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None) | Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
renew -- "true" or "false"
gateway -- "true" or "false"
Example usage:
>>> cr... | 2.783418 | 4.432482 | 0.627959 |
return create_url(
cas_url,
cas_route,
('service', service),
('ticket', ticket),
('renew', renew),
) | def create_cas_validate_url(cas_url, cas_route, service, ticket,
renew=None) | Create a CAS validate URL.
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)
service -- (ex. http://localhost:5000/login)
ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')
renew -- "tr... | 2.75591 | 4.376113 | 0.629762 |
if isinstance(obj, (argparse.Namespace, optparse.Values)):
return vars(obj)
return obj | def namespace_to_dict(obj) | If obj is argparse.Namespace or optparse.Values we'll return
a dict representation of it, else return the original object.
Redefine this method if using other parsers.
:param obj: *
:return:
:rtype: dict or * | 4.659722 | 3.818286 | 1.22037 |
loader = pkgutil.get_loader(name)
if loader is None or name == '__main__':
return None
if hasattr(loader, 'get_filename'):
filepath = loader.get_filename(name)
else:
# Fall back to importing the specified module.
__import__(name)
filepath = sys.modules[name]... | def _package_path(name) | Returns the path to the package containing the named module or
None if the path could not be identified (e.g., if
``name == "__main__"``). | 2.432666 | 2.464092 | 0.987247 |
paths = []
if 'XDG_CONFIG_HOME' in os.environ:
paths.append(os.environ['XDG_CONFIG_HOME'])
if 'XDG_CONFIG_DIRS' in os.environ:
paths.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
else:
paths.append('/etc/xdg')
paths.append('/etc')
return paths | def xdg_config_dirs() | Returns a list of paths taken from the XDG_CONFIG_DIRS
and XDG_CONFIG_HOME environment varibables if they exist | 1.623557 | 1.619261 | 1.002653 |
paths = []
if platform.system() == 'Darwin':
paths.append(MAC_DIR)
paths.append(UNIX_DIR_FALLBACK)
paths.extend(xdg_config_dirs())
elif platform.system() == 'Windows':
paths.append(WINDOWS_DIR_FALLBACK)
if WINDOWS_DIR_VAR in os.environ:
paths.append... | def config_dirs() | Return a platform-specific list of candidates for user
configuration directories on the system.
The candidates are in order of priority, from highest to lowest. The
last element is the "fallback" location to be used when no
higher-priority config file exists. | 2.31421 | 2.293405 | 1.009072 |
try:
with open(filename, 'rb') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError(filename, exc) | def load_yaml(filename) | Read a YAML document from a file. If the file cannot be read or
parsed, a ConfigReadError is raised. | 2.488879 | 2.164902 | 1.14965 |
comment_map = dict()
default_lines = iter(default_data.splitlines())
for line in default_lines:
if not line:
comment = "\n"
elif line.startswith("#"):
comment = "{0}\n".format(line)
else:
continue
while True:
line = next(de... | def restore_yaml_comments(data, default_data) | Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping. | 2.088846 | 2.063268 | 1.012397 |
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, abc.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
elif value is int:
return Integer()
elif isinstance(value, int):
... | def as_template(value) | Convert a simple "shorthand" Python value to a `Template`. | 3.257457 | 3.128807 | 1.041118 |
if isinstance(value, ConfigSource):
return value
elif isinstance(value, dict):
return ConfigSource(value)
else:
raise TypeError(u'source value must be a dict') | def of(cls, value) | Given either a dictionary or a `ConfigSource` object, return
a `ConfigSource` object. This lets a function accept either type
of object as an argument. | 3.953833 | 3.277092 | 1.206507 |
pairs = self.resolve()
try:
return iter_first(pairs)
except ValueError:
raise NotFoundError(u"{0} not found".format(self.name)) | def first(self) | Return a (value, source) pair for the first object found for
this view. This amounts to the first element returned by
`resolve`. If no values are available, a NotFoundError is
raised. | 7.744495 | 5.187266 | 1.492982 |
# We expect our root object to be a dict, but it may come in as
# a namespace
obj = namespace_to_dict(obj)
# We only deal with dictionaries
if not isinstance(obj, dict):
return obj
# Get keys iterator
keys = obj.keys() if PY3 else obj.iterkey... | def _build_namespace_dict(cls, obj, dots=False) | Recursively replaces all argparse.Namespace and optparse.Values
with dicts and drops any keys with None values.
Additionally, if dots is True, will expand any dot delimited
keys.
:param obj: Namespace, Values, or dict to iterate over. Other
values will simply be returned.
... | 4.056947 | 4.0222 | 1.008639 |
self.set(self._build_namespace_dict(namespace, dots)) | def set_args(self, namespace, dots=False) | Overlay parsed command-line arguments, generated by a library
like argparse or optparse, onto this view's value.
:param namespace: Dictionary or Namespace to overlay this config with.
Supports nested Dictionaries and Namespaces.
:type namespace: dict or Namespace
:param dots... | 11.572721 | 10.288807 | 1.124787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.