code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for index, field in enumerate(schema.fields):
value = row[index]
if index in fallbacks:
value = _uncast_value(value, field=field)
else:
value = field.cast_value(value)
row[index] = value
return row | def convert_row(self, row, schema, fallbacks) | Convert row to BigQuery | 3.746933 | 3.991046 | 0.938835 |
# Mapping
mapping = {
'any': 'STRING',
'array': None,
'boolean': 'BOOLEAN',
'date': 'DATE',
'datetime': 'DATETIME',
'duration': None,
'geojson': None,
'geopoint': None,
'integer': 'INTEG... | def convert_type(self, type) | Convert type to BigQuery | 2.712502 | 2.548155 | 1.064496 |
# Convert
fields = []
for field in converted_descriptor['fields']:
field_type = self.restore_type(field['type'])
resfield = {
'name': field['name'],
'type': field_type,
}
if field.get('mode', 'NULLABLE') !=... | def restore_descriptor(self, converted_descriptor) | Restore descriptor rom BigQuery | 3.039842 | 2.930946 | 1.037154 |
for index, field in enumerate(schema.fields):
if field.type == 'datetime':
row[index] = parse(row[index])
if field.type == 'date':
row[index] = parse(row[index]).date()
if field.type == 'time':
row[index] = parse(row[in... | def restore_row(self, row, schema) | Restore row from BigQuery | 2.16934 | 2.361604 | 0.918588 |
# Mapping
mapping = {
'BOOLEAN': 'boolean',
'DATE': 'date',
'DATETIME': 'datetime',
'INTEGER': 'integer',
'FLOAT': 'number',
'STRING': 'string',
'TIME': 'time',
}
# Not supported type
i... | def restore_type(self, type) | Restore type from BigQuery | 3.228496 | 2.996478 | 1.07743 |
# No cached value
if self.__buckets is None:
# Get response
response = self.__service.tables().list(
projectId=self.__project,
datasetId=self.__dataset).execute()
# Extract buckets
self.__buckets = []
... | def buckets(self) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 3.345652 | 3.04015 | 1.100489 |
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
descriptors = descriptor
if isinstance(descriptor, dict):
descriptors = [descriptor]
# Iterate over buckets/descriptors
for bucket, descrip... | def create(self, bucket, descriptor, force=False) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 3.078968 | 2.823258 | 1.090573 |
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
elif bucket is None:
buckets = reversed(self.buckets)
# Iterater over buckets
for bucket in buckets:
# Non-existent bucket
... | def delete(self, bucket=None, ignore=False) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 3.611372 | 3.342597 | 1.080409 |
# Set descriptor
if descriptor is not None:
self.__descriptors[bucket] = descriptor
# Get descriptor
else:
descriptor = self.__descriptors.get(bucket)
if descriptor is None:
table_name = self.__mapper.convert_bucket(bucket)
... | def describe(self, bucket, descriptor=None) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 3.19244 | 2.990978 | 1.067357 |
# Get schema/data
schema = tableschema.Schema(self.describe(bucket))
table_name = self.__mapper.convert_bucket(bucket)
response = self.__service.tabledata().list(
projectId=self.__project,
datasetId=self.__dataset,
tableId=table_name).execute... | def iter(self, bucket) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 3.615767 | 3.330331 | 1.085708 |
# Write buffer
BUFFER_SIZE = 10000
# Prepare schema, fallbacks
schema = tableschema.Schema(self.describe(bucket))
fallbacks = self.__fallbacks.get(bucket, [])
# Write data
rows_buffer = []
for row in rows:
row = self.__mapper.conver... | def write(self, bucket, rows) | https://github.com/frictionlessdata/tableschema-bigquery-py#storage | 2.8665 | 2.640435 | 1.085617 |
url_path = self._build_url_path(None, None)
params = {'page': page}
# the endpoints respond just fine to invaliid query params,
# they just ignore them, but the the real value of the endpoints
# is only revealed when using the filters, so let's not waste
# reques... | def get_securities(self, page=1, **filter_param) | Queries /<security_type> endpoint to return a paged
list of securities. | 5.923554 | 5.857448 | 1.011286 |
security_symbols = self._str_or_list(security_symbols)
calculation_codes = self._str_or_list(calculation_codes)
url_path = self._build_url_path(security_symbols,
'points', calculation_codes)
if query_date:
params = {'date': self._format_query_date_for_u... | def get_points(self, security_symbols, calculation_codes, query_date=None) | Queries data from a /<security_type>/points endpoint.
Args:
security_symbols (list): List of string symbols
calculation_codes (list): List og string calculation codes
query_date
(datetime): datetime object on or before which the endpoint will query data for.
... | 2.464332 | 2.971927 | 0.829203 |
security_symbols = self._str_or_list(security_symbols)
calculation_codes = self._str_or_list(calculation_codes)
url_path = self._build_url_path(security_symbols,
'series', calculation_codes)
params = {}
if query_start_date:
params['start_date']... | def get_series(self, security_symbols, calculation_codes, query_start_date=None, query_end_date=None,
resample_frequency=None, resample_function=None, fill_method=None, aggregate_function=None) | Queries data from a /<security_type>/series endpoint.
Args:
security_symbols (list): List of string symbols
calculation_codes (list): List og string calculation codes
query_start_date
(datetime): date after which the endpoint will query data for.
... | 1.545135 | 1.712553 | 0.902241 |
security_symbols = self._str_or_list(security_symbols)
info_field_codes = self._str_or_list(info_field_codes)
url_path = self._build_url_path(security_symbols,
'info', info_field_codes)
return self._get_data(url_path, None) | def get_info(self, security_symbols, info_field_codes) | Queries data from a /<security_type>/info endpoint.
Args:
security_symbols (list): List of string symbols
info_field_codes (list): List of string info field codes
Returns:
dict of the decoded json from server response.
Notes:
The max length of a... | 2.648259 | 3.178628 | 0.833145 |
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol | def definition(self) | Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol) | 9.890502 | 2.339594 | 4.227443 |
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
... | def _start_operation(self, ast, operation, precedence) | Returns an AST where all operations of lower precedence are finalized. | 2.651078 | 2.642523 | 1.003238 |
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer i... | def tokenize(self, expr) | Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some sim... | 2.988982 | 2.74308 | 1.089645 |
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
... | def _rdistributive(self, expr, op_example) | Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple. | 3.727303 | 3.574939 | 1.04262 |
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self... | def normalize(self, expr, operation) | Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is... | 9.632101 | 8.929248 | 1.078714 |
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args)) | def get_literals(self) | Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates. | 2.978503 | 2.588423 | 1.150702 |
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args) | def literalize(self) | Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions. | 3.533291 | 3.125023 | 1.130645 |
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()] | def get_symbols(self) | Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates. | 7.154902 | 5.733095 | 1.248 |
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._s... | def subs(self, substitutions, default=None, simplify=False) | Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to t... | 8.321824 | 8.071216 | 1.03105 |
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expressio... | def _subs(self, substitutions, default, simplify) | Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.} | 5.138162 | 5.124712 | 1.002625 |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
return (' ' * indent) + ('%s(%s%s)' % (self.__class__.__name__, debug_... | def pretty(self, indent=0, debug=False) | Return a pretty formatted representation of self. | 4.237561 | 4.103012 | 1.032793 |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r' % (self.isliteral, self.iscanonical)
identity = getattr(self, 'identity', None)
if identity is not None:
debug_details += ', identity=%r' % (identity)
a... | def pretty(self, indent=0, debug=False) | Return a pretty formatted representation of self as an indented tree.
If debug is True, also prints debug information for each expression arg.
For example:
>>> print Expression().parse(u'not a and not b and not (a and ba and c) and c or c').pretty()
OR(
AND(
NOT(S... | 2.732235 | 2.728591 | 1.001335 |
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize() | def literalize(self) | Return an expression where NOTs are only occurring as literals. | 8.355355 | 6.822792 | 1.224624 |
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify(... | def simplify(self) | Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form. | 5.018033 | 4.299608 | 1.167091 |
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr | def cancel(self) | Cancel itself and following NOTs as far as possible.
Returns the simplified expression. | 3.206923 | 2.67667 | 1.198102 |
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args)) | def demorgan(self) | Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws. | 9.109399 | 6.845663 | 1.330682 |
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__n... | def pretty(self, indent=1, debug=False) | Return a pretty formatted representation of self.
Include additional debug details if `debug` is True. | 3.746595 | 3.45711 | 1.083736 |
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new in... | def simplify(self) | Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Ide... | 3.160579 | 2.932886 | 1.077634 |
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args) | def flatten(self) | Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C. | 2.399376 | 2.258081 | 1.062573 |
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
targe... | def absorb(self, args) | Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B | 2.588475 | 2.456692 | 1.053642 |
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if ... | def subtract(self, expr, simplify) | Return a new expression where the `expr` expression has been removed
from this expression if it exists. | 2.185965 | 2.088437 | 1.046699 |
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify(... | def distributive(self) | Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C) | 3.361194 | 3.305963 | 1.016707 |
match = self._ages_re.match(self.raw_fields.get('ages'))
if not match:
match = self._ages_re2.match(self.raw_fields.get('ages'))
return self.Ages(int(match.group(1)),int(match.group(1)))
return self.Ages(int(match.group(1)), int(match.group(2))) | def ages(self) | The age range that the user is interested in. | 3.107283 | 2.901063 | 1.071084 |
return 'display: none;' not in self._looking_for_xpb.li(id='ajax_single').\
one_(self._profile.profile_tree).attrib['style'] | def single(self) | Whether or not the user is only interested in people that are single. | 74.275719 | 63.208847 | 1.175084 |
ages = ages or self.ages
single = single if single is not None else self.single
near_me = near_me if near_me is not None else self.near_me
kinds = kinds or self.kinds
gentation = gentation or self.gentation
data = {
'okc_api': '1',
'search... | def update(self, ages=None, single=None, near_me=None, kinds=None,
gentation=None) | Update the looking for attributes of the logged in user.
:param ages: The ages that the logged in user is interested in.
:type ages: tuple
:param single: Whether or not the user is only interested in people that
are single.
:type single: bool
:param near_m... | 5.583082 | 5.590142 | 0.998737 |
response_dict = self.upload(incoming)
if 'error' in response_dict:
log.warning('Failed to upload photo')
return response_dict
if isinstance(incoming, Info):
kwargs.setdefault('thumb_nail_left', incoming.thumb_nail_left)
kwargs.setdefault('... | def upload_and_confirm(self, incoming, **kwargs) | Upload the file to okcupid and confirm, among other things, its
thumbnail position.
:param incoming: A filepath string, :class:`.Info` object or
a file like object to upload to okcupid.com.
If an info object is provided, its thumbnail
... | 2.497981 | 2.041738 | 1.223458 |
if isinstance(photo_id, Info):
photo_id = photo_id.id
return self._session.okc_post('photoupload', data={
'albumid': album_id,
'picid': photo_id,
'authcode': self._authcode,
'picture.delete_ajax': 1
}) | def delete(self, photo_id, album_id=0) | Delete a photo from the logged in users account.
:param photo_id: The okcupid id of the photo to delete.
:param album_id: The album from which to delete the photo. | 6.41677 | 6.071766 | 1.056821 |
logger_args = ("--enable-logger",)
credentials_args = ("--credentials",)
if use_short_options:
logger_args += ('-l',)
credentials_args += ('-c',)
add_argument(*logger_args, dest='enabled_loggers',
action="append", default=[],
help="Enable the specif... | def add_command_line_options(add_argument, use_short_options=True) | :param add_argument: The add_argument method of an ArgParser.
:param use_short_options: Whether or not to add short options. | 4.053797 | 4.396912 | 0.921965 |
for enabled_log in args.enabled_loggers:
enable_logger(enabled_log)
for credential_file in args.credential_files:
settings.load_credentials_from_filepath(credential_file)
if args.echo:
from okcupyd import db
db.echo = True
db.Session.kw['bind'].echo = True
re... | def handle_command_line_options(args) | :param args: The args returned from an ArgParser | 6.045428 | 6.036451 | 1.001487 |
default = kwargs.get('default', 0)
offset = kwargs.get('offset', 1)
string_index_pairs = []
for index, string_or_tuple in enumerate(re_strings, offset):
if isinstance(string_or_tuple, six.string_types):
string_or_tuple = (string_or_tuple,)
for re_string in string_or_tupl... | def IndexedREMap(*re_strings, **kwargs) | Build a :class:`~.REMap` from the provided regular expression string.
Each string will be associated with the index corresponding to its position
in the argument list.
:param re_strings: The re_strings that will serve as keys in the map.
:param default: The value to return if none of the regular expres... | 2.545881 | 2.462867 | 1.033706 |
if self.func.__name__ in obj.__dict__:
delattr(obj, self.func.__name__) | def bust_self(self, obj) | Remove the value that is being stored on `obj` for this
:class:`.cached_property`
object.
:param obj: The instance on which to bust the cache. | 4.58798 | 6.125323 | 0.749018 |
for name, _ in cls.get_cached_properties(obj):
if name in obj.__dict__ and not name in excludes:
delattr(obj, name) | def bust_caches(cls, obj, excludes=()) | Bust the cache for all :class:`.cached_property` objects on `obj`
:param obj: The instance on which to bust the caches. | 4.151166 | 4.610443 | 0.900383 |
return cls(re_value_pairs=[(re.compile(s), v)
for s, v in string_value_pairs],
**kwargs) | def from_string_pairs(cls, string_value_pairs, **kwargs) | Build an :class:`~.REMap` from str, value pairs by applying
`re.compile` to each string and calling the __init__ of :class:`~.REMap` | 4.695197 | 3.757657 | 1.249501 |
if not self.connection and make_connection:
self.connect()
with self.connection.cursor() as cursor:
cursor.execute("SELECT SERVERPROPERTY('productversion')")
return cursor.fetchone()[0] | def __get_dbms_version(self, make_connection=True) | Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True. | 2.847013 | 2.655237 | 1.072226 |
return (self._message_thread.user_profile
if 'from_me' in self._message_element.attrib['class']
else self._message_thread.correspondent_profile) | def sender(self) | :returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the sender of this message. | 10.856174 | 9.242133 | 1.174639 |
return (self._message_thread.correspondent_profile
if 'from_me' in self._message_element.attrib['class']
else self._message_thread.user_profile) | def recipient(self) | :returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the recipient of this message. | 11.35982 | 9.918077 | 1.145365 |
# The code that follows is obviously pretty disgusting.
# It seems like it might be impossible to completely replicate
# the text of the original message if it has trailing whitespace
message = self._content_xpb.one_(self._message_element)
first_line = message.text
... | def content(self) | :returns: The text body of the message. | 5.513114 | 5.208776 | 1.058428 |
thread_ids = [thread.id if isinstance(thread, cls) else thread
for thread in thread_ids_or_threads]
if not authcode:
authcode = helpers.get_authcode(html.fromstring(
session.okc_get('messages').content
))
data = {'access_toke... | def delete_threads(cls, session, thread_ids_or_threads, authcode=None) | :param session: A logged in :class:`~okcupyd.session.Session`.
:param thread_ids_or_threads: A list whose members are either
:class:`~.MessageThread` instances
or okc_ids of message threads.
:param authcode: Authcode to use for ... | 4.814611 | 4.834368 | 0.995913 |
try:
return int(self._thread_element.attrib['data-personid'])
except (ValueError, KeyError):
try:
return int(self.correspondent_profile.id)
except:
pass | def correspondent_id(self) | :returns: The id assigned to the correspondent of this message. | 8.12044 | 6.64874 | 1.22135 |
try:
return self._correspondent_xpb.one_(self._thread_element).strip()
except IndexError:
raise errors.NoCorrespondentError() | def correspondent(self) | :returns: The username of the user with whom the logged in user is
conversing in this :class:`~.MessageThread`. | 19.027983 | 16.198317 | 1.174689 |
return any(message.sender != self.initiator
for message in self.messages) | def got_response(self) | :returns: Whether or not the :class:`~.MessageThread`. has received a
response. | 21.813038 | 17.039385 | 1.280154 |
assert question.id == self.id
for answer_option in self.answer_options:
if answer_option.text == question.their_answer:
return answer_option.id | def get_answer_id_for_question(self, question) | Get the answer_id corresponding to the answer given for question
by looking at this :class:`~.UserQuestion`'s answer_options.
The given :class:`~.Question` instance must have the same id as this
:class:`~.UserQuestion`.
That this method exists is admittedly somewhat weird. Unfortunately... | 4.423206 | 3.471003 | 1.274331 |
return [
AnswerOption(element)
for element in self._answer_option_xpb.apply_(
self._question_element
)
] | def answer_options(self) | :returns: A list of :class:`~.AnswerOption` instances representing the
available answers to this question. | 17.192593 | 14.425336 | 1.191833 |
user_response_ids = [option.id
for option in user_question.answer_options
if option.is_users]
match_response_ids = [option.id
for option in user_question.answer_options
if optio... | def respond_from_user_question(self, user_question, importance) | Respond to a question in exactly the way that is described by
the given user_question.
:param user_question: The user question to respond with.
:type user_question: :class:`.UserQuestion`
:param importance: The importance that should be used in responding to
t... | 3.408614 | 3.580551 | 0.95198 |
option_index = user_question.answer_text_to_option[
question.their_answer
].id
self.respond(question.id, [option_index], [option_index], importance) | def respond_from_question(self, question, user_question, importance) | Copy the answer given in `question` to the logged in user's
profile.
:param question: A :class:`~.Question` instance to copy.
:param user_question: An instance of :class:`~.UserQuestion` that
corresponds to the same question as `question`.
... | 9.312165 | 11.420028 | 0.815424 |
form_data = {
'ajax': 1,
'submit': 1,
'answer_question': 1,
'skip': 0,
'show_all': 0,
'targetid': self._user_id,
'qid': question_id,
'answers': user_response_ids,
'matchanswers': match_response_i... | def respond(self, question_id, user_response_ids, match_response_ids,
importance, note='', is_public=1, is_new=1) | Respond to an okcupid.com question.
:param question_id: The okcupid id used to identify this question.
:param user_response_ids: The answer id(s) to provide to this question.
:param match_response_ids: The answer id(s) that the user considers
acceptable.
... | 3.391452 | 3.537396 | 0.958742 |
# Try to reply to an existing thread.
if not isinstance(username, six.string_types):
username = username.username
for mailbox in (self.inbox, self.outbox):
for thread in mailbox:
if thread.correspondent.lower() == username.lower():
... | def message(self, username, message_text) | Message an okcupid user. If an existing conversation between the
logged in user and the target user can be found, reply to that thread
instead of starting a new one.
:param username: The username of the user to which the message should
be sent.
:type username: s... | 4.30547 | 4.21221 | 1.02214 |
kwargs.setdefault('gender', self.profile.gender[0])
gentation = helpers.get_default_gentation(self.profile.gender,
self.profile.orientation)
kwargs.setdefault('gentation', gentation)
# We are no longer setting location by defaul... | def search(self, **kwargs) | Call :func:`~okcupyd.json_search.SearchFetchable` to get a
:class:`~okcupyd.util.fetchable.Fetchable` object that will lazily
perform okcupid searches to provide :class:`~okcupyd.profile.Profile`
objects matching the search criteria.
Defaults for `gender`, `gentation`, `location` and `r... | 8.088255 | 5.630011 | 1.436632 |
if bust_questions_cache:
self.profile.questions()
user_question = None if fast else self.profile.find_question(
question.id
)
if user_question is None:
self.questions.respond(question.id, [1], [1], 3)
# Give okcupid some time to up... | def get_user_question(self, question, fast=False,
bust_questions_cache=False) | Get a :class:`~okcupyd.question.UserQuestion` corresponding to the
given :class:`~okcupyd.question.Question`.
HUGE CAVEATS: If the logged in user has not answered the relevant
question, it will automatically be answered with whatever the first
answer to the question is.
For the... | 4.141448 | 3.859548 | 1.07304 |
if hasattr(question, 'answer_id'):
# Guard to handle incoming user_question.
return question.answer_id
user_question = self.get_user_question(
question, fast=fast, bust_questions_cache=bust_questions_cache
)
# Look at recently answered questi... | def get_question_answer_id(self, question, fast=False,
bust_questions_cache=False) | Get the index of the answer that was given to `question`
See the documentation for :meth:`~.get_user_question` for important
caveats about the use of this function.
:param question: The question whose `answer_id` should be retrieved.
:type question: :class:`~okcupyd.question.BaseQuesti... | 4.834907 | 4.581683 | 1.055269 |
response = self._session.okc_get('quickmatch', params={'okc_api': 1})
return Profile(self._session, response.json()['sn']) | def quickmatch(self) | Return a :class:`~okcupyd.profile.Profile` obtained by visiting the
quickmatch page. | 15.802628 | 8.835365 | 1.788565 |
session = session or Session.login()
return util.Fetchable(
SearchManager(
SearchJSONFetcher(session, **kwargs),
ProfileBuilder(session)
)
) | def SearchFetchable(session=None, **kwargs) | Search okcupid.com with the given parameters. Parameters are
registered to this function through
:meth:`~okcupyd.filter.Filters.register_filter_builder` of
:data:`~okcupyd.json_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetchable` of
:class:`~okcupyd.profile.Profi... | 12.393254 | 13.588711 | 0.912026 |
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
# No real good reason to hold on to this. DONT TOUCH.
self._original_iterable = self._fetcher.fetch(**kwargs)
self.exhausted = False
if nice_repr:
self._accumulated = []
... | def refresh(self, nice_repr=True, **kwargs) | :param nice_repr: Append the repr of a list containing the items that
have been fetched to this point by the fetcher.
:type nice_repr: bool
:param kwargs: kwargs that should be passed to the fetcher when its
fetch method is called. These are merged with t... | 5.3152 | 4.592962 | 1.157249 |
return [
line_string for key in sorted(self.keys)
for line_string in self.build_paramter_string(key)
] | def build_documentation_lines(self) | Build a parameter documentation string that can appended to the
docstring of a function that uses this :class:`~.Filters` instance
to build filters. | 10.414465 | 8.343857 | 1.24816 |
kwargs['transform'] = function
if kwargs.get('decider'):
kwargs['decide'] = kwargs.get('decider')
return type('filter', (self.filter_class,), kwargs) | def register_filter_builder(self, function, **kwargs) | Register a filter function with this :class:`~.Filters` instance.
This function is curried with :class:`~okcupyd.util.currying.curry`
-- that is, it can be invoked partially before it is fully evaluated.
This allows us to pass kwargs to this function when it is used as a
decorator:
... | 6.007467 | 8.656326 | 0.693997 |
locid = 0
query_parameters = {
'func': 'query',
'query': location,
}
loc_query = session.get('http://www.okcupid.com/locquery',
params=query_parameters)
p = html.fromstring(loc_query.content.decode('utf8'))
js = loads(p.text)
if 'results' in j... | def get_locid(session, location) | Make a request to locquery resource to translate a string location
search into an int locid.
Returns
----------
int
An int that OKCupid maps to a particular geographical location. | 3.796894 | 3.400135 | 1.116689 |
if isinstance(last_online, str):
if last_online.lower() in ('day', 'today'):
last_online_int = 86400 # 3600 * 24
elif last_online.lower() == 'week':
last_online_int = 604800 # 3600 * 24 * 7
elif last_online.lower() == 'month':
last_online_int = 2678... | def format_last_online(last_online) | Return the upper limit in seconds that a profile may have been
online. If last_online is an int, return that int. Otherwise if
last_online is a str, convert the string into an int.
Returns
----------
int | 1.719153 | 1.713792 | 1.003128 |
div = profile_tree.xpath("//div[@id = 'what_i_want']")[0]
looking_for['gentation'] = div.xpath(".//li[@id = 'ajax_gentation']/text()")[0].strip()
looking_for['ages'] = replace_chars(div.xpath(".//li[@id = 'ajax_ages']/text()")[0].strip())
looking_for['near'] = div.xpath(".//li[@id = 'ajax_near']/te... | def update_looking_for(profile_tree, looking_for) | Update looking_for attribute of a Profile. | 2.835577 | 2.826991 | 1.003037 |
div = profile_tree.xpath("//div[@id = 'profile_details']")[0]
for dl in div.iter('dl'):
title = dl.find('dt').text
item = dl.find('dd')
if title == 'Last Online' and item.find('span') is not None:
details[title.lower()] = item.find('span').text.strip()
elif title... | def update_details(profile_tree, details) | Update details attribute of a Profile. | 3.011592 | 3.004218 | 1.002455 |
gender = gender.lower()[0]
orientation = orientation.lower()
return gender_to_orientation_to_gentation[gender][orientation] | def get_default_gentation(gender, orientation) | Return the default gentation for the given gender and orientation. | 4.66707 | 3.578015 | 1.304374 |
for k, v in CHAR_REPLACE.items():
astring = astring.replace(k, v)
return astring | def replace_chars(astring) | Replace certain unicode characters to avoid errors when trying
to read various strings.
Returns
----------
str | 2.722485 | 4.308354 | 0.631908 |
for br in tree.xpath("*//br"):
br.tail = u"\n" + br.tail if br.tail else u"\n" | def add_newlines(tree) | Add a newline character to the end of each <br> element. | 3.915556 | 2.98151 | 1.31328 |
average = (_higher + _lower)//2
if _higher - _lower <= accuracy:
return average
results = search(self._session,
count=9,
gentation='everybody',
keywords=username,
attractiven... | def find_attractiveness(self, username, accuracy=1000,
_lower=0, _higher=10000) | :param username: The username to lookup attractiveness for.
:param accuracy: The accuracy required to return a result.
:param _lower: The lower bound of the search.
:param _higher: The upper bound of the search. | 3.98583 | 4.172668 | 0.955223 |
with txn() as session:
last_updated_name = '{0}_last_updated'.format(mailbox_name)
okcupyd_user = session.query(model.OKCupydUser).join(model.User).filter(
model.User.okc_id == self._user.profile.id
).with_for_update().one()
log.info(simpl... | def update_mailbox(self, mailbox_name='inbox') | Update the mailbox associated with the given mailbox name. | 3.860482 | 3.807442 | 1.013931 |
# Reverse because pictures appear in inverse chronological order.
for photo_info in self.dest_user.profile.photo_infos:
self.dest_user.photo.delete(photo_info)
return [self.dest_user.photo.upload_and_confirm(info)
for info in reversed(self.source_profile.phot... | def photos(self) | Copy photos to the destination user. | 8.130765 | 6.509861 | 1.248992 |
for essay_name in self.dest_user.profile.essays.essay_names:
setattr(self.dest_user.profile.essays, essay_name,
getattr(self.source_profile.essays, essay_name)) | def essays(self) | Copy essays from the source profile to the destination profile. | 4.567642 | 2.948073 | 1.549365 |
looking_for = self.source_profile.looking_for
return self.dest_user.profile.looking_for.update(
gentation=looking_for.gentation,
single=looking_for.single,
near_me=looking_for.near_me,
kinds=looking_for.kinds,
ages=looking_for.ages
... | def looking_for(self) | Copy looking for attributes from the source profile to the
destination profile. | 6.145079 | 5.23866 | 1.173025 |
return self.dest_user.profile.details.convert_and_update(
self.source_profile.details.as_dict
) | def details(self) | Copy details from the source profile to the destination profile. | 17.45405 | 9.740152 | 1.791969 |
session = session or Session.login()
return util.Fetchable.fetch_marshall(
SearchHTMLFetcher(session, **kwargs),
util.SimpleProcessor(
session,
lambda match_card_div: Profile(
session=session,
**MatchCardExtractor(match_card_div).as_di... | def SearchFetchable(session=None, **kwargs) | Search okcupid.com with the given parameters. Parameters are registered
to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder`
of :data:`~okcupyd.html_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetchable` of
:class:`~okcupyd.profile.Profile` ... | 13.347357 | 14.327762 | 0.931573 |
util.cached_property.bust_caches(self, excludes=('authcode'))
self.questions = self.question_fetchable()
if reload:
return self.profile_tree | def refresh(self, reload=False) | :param reload: Make the request to return a new profile tree. This will
result in the caching of the profile_tree attribute. The
new profile_tree will be returned. | 26.139561 | 19.972839 | 1.308755 |
from . import photo
pics_request = self._session.okc_get(
u'profile/{0}/album/0'.format(self.username),
)
pics_tree = html.fromstring(u'{0}{1}{2}'.format(
u'<div>', pics_request.json()['fulls'], u'</div>'
))
return [photo.Info.from_cdn_uri... | def photo_infos(self) | :returns: list of :class:`~okcupyd.photo.Info` instances for each photo
displayed on okcupid. | 9.403686 | 8.096772 | 1.161412 |
if self.is_logged_in_user: return False
classes = self._liked_xpb.one_(self.profile_tree).attrib['class'].split()
return 'liked' in classes | def liked(self) | :returns: Whether or not the logged in user liked this profile | 14.94435 | 12.173906 | 1.227572 |
try:
contacted_span = self._contacted_xpb.one_(self.profile_tree)
except:
return False
else:
timestamp = contacted_span.replace('Last contacted ', '')
return helpers.parse_date_updated(timestamp) | def contacted(self) | :retuns: A boolean indicating whether the logged in user has contacted
the owner of this profile. | 12.748544 | 11.982315 | 1.063947 |
contacted_text = self._contacted_xpb.\
get_text_(self.profile_tree).lower()
if 'contacted' not in contacted_text:
return contacted_text.strip().replace('replies ', '') | def responds(self) | :returns: The frequency with which the user associated with this profile
responds to messages. | 17.268871 | 17.103769 | 1.009653 |
if self.is_logged_in_user: return self._current_user_id
return int(self._id_xpb.one_(self.profile_tree)) | def id(self) | :returns: The id that okcupid.com associates with this profile. | 21.962578 | 17.417826 | 1.260925 |
if self.is_logged_in_user:
# Retrieve the logged-in user's profile age
return int(self._user_age_xpb.get_text_(self.profile_tree).strip())
else:
# Retrieve a non logged-in user's profile age
return int(self._age_xpb.get_text_(self.profile_tree)) | def age(self) | :returns: The age of the user associated with this profile. | 6.596518 | 5.787087 | 1.139868 |
return int(self._percentages_and_ratings_xpb.
div.with_class('matchgraph--match').
div.with_class('matchgraph-graph').
canvas.select_attribute_('data-pct').
one_(self.profile_tree)) | def match_percentage(self) | :returns: The match percentage of the logged in user and the user
associated with this object. | 42.596714 | 39.714123 | 1.072584 |
if self.is_logged_in_user:
# Retrieve the logged-in user's profile location
return self._user_location_xpb.get_text_(self.profile_tree)
else:
# Retrieve a non logged-in user's profile location
return self._location_xpb.get_text_(self.profile_tree... | def location(self) | :returns: The location of the user associated with this profile. | 6.399 | 5.337824 | 1.198803 |
return_value = helpers.Messager(self._session).send(
self.username, message, self.authcode, thread_id
)
self.refresh(reload=False)
return return_value | def message(self, message, thread_id=None) | Message the user associated with this profile.
:param message: The message to send to this user.
:param thread_id: The id of the thread to respond to, if any. | 9.704966 | 14.232599 | 0.681883 |
parameters = {
'voterid': self._current_user_id,
'target_userid': self.id,
'type': 'vote',
'cf': 'profile2',
'target_objectid': 0,
'vote_type': 'personality',
'score': rating,
}
response = self._session.... | def rate(self, rating) | Rate this profile as the user that was logged in with the session
that this object was instantiated with.
:param rating: The rating to give this user. | 6.230966 | 6.627761 | 0.940131 |
question_fetchable = question_fetchable or self.questions
for question in question_fetchable:
if int(question.id) == int(question_id):
return question | def find_question(self, question_id, question_fetchable=None) | :param question_id: The id of the question to search for
:param question_fetchable: The question fetchable to iterate through
if none is provided `self.questions`
will be used. | 2.404767 | 2.264155 | 1.062104 |
return util.Fetchable(QuestionFetcher(
self._session, self.username,
is_user=self.is_logged_in_user, **kwargs
)) | def question_fetchable(self, **kwargs) | :returns: A :class:`~okcupyd.util.fetchable.Fetchable` instance that
contains objects representing the answers that the user
associated with this profile has given to okcupid.com match
questions. | 10.763181 | 8.709166 | 1.235845 |
kwargs.setdefault('params', {})['authcode'] = self.authcode
return self._session.okc_get(path, **kwargs) | def authcode_get(self, path, **kwargs) | Perform an HTTP GET to okcupid.com using this profiles session
where the authcode is automatically added as a query parameter. | 6.337011 | 4.610571 | 1.374452 |
kwargs.setdefault('data', {})['authcode'] = self.authcode
return self._session.okc_post(path, **kwargs) | def authcode_post(self, path, **kwargs) | Perform an HTTP POST to okcupid.com using this profiles session
where the authcode is automatically added as a form item. | 6.027083 | 4.357849 | 1.383041 |
is_class = inspect.isclass(function)
if is_class:
function = function.__init__
function_info = inspect.getargspec(function)
function_args = function_info.args
if is_class:
# This is to handle the fact that self will get passed in
# aut... | def arity_evaluation_checker(function) | Build an evaluation checker that will return True when it is
guaranteed that all positional arguments have been accounted for. | 2.92362 | 2.86755 | 1.019553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.