code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
sign = (value & 0x8000000000000000) and -1 or 0
if value >> 64 != sign:
raise errors.EncodeError('SFixed64 out of range: %d' % value)
self._stream.append_little_endian64(value & 0xffffffffffffffff) | def append_sfixed64(self, value) | Appends a signed 64-bit integer to our buffer, in little-endian
byte-order. | 3.438329 | 3.596287 | 0.956077 |
self._stream.append_var_uint32(len(value))
self._stream.append_raw_bytes(value) | def append_string(self, value) | Appends a length-prefixed string to our buffer, with the
length varint-encoded. | 5.720402 | 4.642909 | 1.232073 |
from hashlib import sha1
if PY3 and isinstance(word, str):
word = word.encode('utf-8')
hash_s = sha1()
hash_s.update(word)
return bin(int(hash_s.hexdigest(), 16))[2:].zfill(160) | def get_SHA1_bin(word) | Return SHA1 hash of any string
:param word:
:return: | 2.745857 | 2.91639 | 0.941526 |
res = -1
try:
res = binstr.index('1') + 1
except ValueError:
res = end_index
return res | def get_index(binstr, end_index=160) | Return the position of the first 1 bit
from the left in the word until end_index
:param binstr:
:param end_index:
:return: | 3.609271 | 3.79813 | 0.950276 |
m = self._bucket_number
raw_e = self._alpha * pow(m, 2) / sum([pow(2, -x) for x in buffer])
if raw_e <= 5 / 2.0 * m:
v = buffer.count(0)
if v != 0:
return m * log(m / float(v), 2)
else:
return raw_e
elif raw_e <... | def _estimate(self, buffer) | Return the estimate of the cardinality
:return: esitimate of the cardinality | 4.511511 | 4.591061 | 0.982673 |
for i in range(len(buffer)):
buffer[i] = max(buffer[i], other_hyper_log_log[i]) | def merge(self, buffer, other_hyper_log_log) | Merge the HyperLogLog
:param other_hyper_log_log:
:return: | 2.766435 | 2.811025 | 0.984137 |
length = self._stream.read_var_uint32()
return self._stream.read_string(length) | def read_string(self) | Reads and returns a length-delimited string. | 4.668257 | 4.113593 | 1.134837 |
if isinstance(seq, set):
fmt = u("set([%s])")
else:
fmt = u("[%s]") if hasattr(seq, '__setitem__') else u("(%s)")
if max_seq_items is False:
nitems = len(seq)
else:
nitems = max_seq_items or options.display.max_seq_items or len(seq)
s = iter(seq)
r = []
... | def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds) | internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
bounds length of printed sequence, depending on options | 3.304834 | 3.133281 | 1.054752 |
fmt = u("{%s}")
pairs = []
pfmt = u("%s: %s")
if max_seq_items is False:
nitems = len(seq)
else:
nitems = max_seq_items or options.display.max_seq_items or len(seq)
for k, v in list(seq.items())[:nitems]:
pairs.append(pfmt % (pprint_thing(k, _nest_lvl + 1, max_seq... | def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds) | internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly. | 2.485589 | 2.390524 | 1.039768 |
def as_escaped_unicode(thing, escape_chars=escape_chars):
# Unicode is fine, else we try to decode using utf-8 and 'replace'
# if that's not it either, we have no way of knowing and the user
# should deal with it himself.
try:
result = six.text_type(thing) # we sho... | def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None) | This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(object) does not)
Parameters
----------
thing : anything to be formatted
_nest_lvl : internal use only. pprint_thing() is mutually-re... | 2.830046 | 2.827711 | 1.000826 |
if mode == 'left':
return [x.ljust(max_len) for x in texts]
elif mode == 'center':
return [x.center(max_len) for x in texts]
else:
return [x.rjust(max_len) for x in texts] | def _justify(texts, max_len, mode='right') | Perform ljust, center, rjust against string or list-like | 1.56425 | 1.534595 | 1.019324 |
trimmed = str_floats
def _cond(values):
non_na = [x for x in values if x != na_rep]
return (len(non_na) > 0 and all([x.endswith('0') for x in non_na]) and
not(any([('e' in x) or ('E' in x) for x in non_na])))
while _cond(trimmed):
trimmed = [x[:-1] if x != na_r... | def _trim_zeros(str_floats, na_rep='NaN') | Trims zeros and decimal points. | 2.92916 | 2.795936 | 1.047649 |
'''
Checks whether the frame should be truncated. If so, slices
the frame up.
'''
# Column of which first element is used to determine width of a dot col
self.tr_size_col = -1
# Cut the data to the information actually printed
max_cols = self.max_cols
... | def _chk_truncate(self) | Checks whether the frame should be truncated. If so, slices
the frame up. | 2.974247 | 2.794315 | 1.064392 |
frame = self.tr_frame
# may include levels names also
str_index = self._get_formatted_index(frame)
str_columns = self._get_formatted_column_labels(frame)
if self.header:
stringified = []
for i, c in enumerate(frame.columns):
che... | def _to_str_columns(self) | Render a DataFrame to a list of columns (as lists of strings). | 3.227205 | 3.186993 | 1.012618 |
frame = self.frame
if len(frame.columns) == 0 or len(frame.index) == 0:
info_line = (u('Empty %s\nColumns: %s\nIndex: %s')
% (type(self.frame).__name__,
pprint_thing(frame.columns),
pprint_thing(frame.... | def to_string(self) | Render a DataFrame to a console-friendly tabular output. | 4.412228 | 4.245162 | 1.039354 |
html_renderer = HTMLFormatter(self, classes=classes,
max_rows=self.max_rows,
max_cols=self.max_cols,
notebook=notebook)
if hasattr(self.buf, 'write'):
html_renderer.writ... | def to_html(self, classes=None, notebook=False) | Render a DataFrame to a html table.
Parameters
----------
notebook : {True, False}, optional, default False
Whether the generated HTML is for IPython Notebook. | 3.101988 | 3.517326 | 0.881916 |
values = self.values
return [val.strftime('%Y-%m-%d %H:%M:%S') if val is not None else self.nat_rep for val in values] | def _format_strings(self) | we by definition have DO NOT have a TZ | 7.268811 | 5.879227 | 1.236355 |
obj = cls(name)
obj.exporter = 'get_input_table_name'
obj.input_name = input_name
return obj | def build_input_table(cls, name='inputTableName', input_name='input') | Build an input table parameter
:param name: parameter name
:type name: str
:param input_name: bind input port name
:param input_name: str
:return: input description
:rtype: ParamDef | 5.758311 | 7.677396 | 0.750034 |
obj = cls(name)
obj.exporter = 'get_input_partitions'
obj.input_name = input_name
return obj | def build_input_partitions(cls, name='inputTablePartitions', input_name='input') | Build an input table partition parameter
:param name: parameter name
:type name: str
:param input_name: bind input port name
:param input_name: str
:return: input description
:rtype: ParamDef | 5.754719 | 7.327983 | 0.785307 |
obj = cls(name)
obj.exporter = 'get_output_table_name'
obj.output_name = output_name
return obj | def build_output_table(cls, name='inputTableName', output_name='output') | Build an output table parameter
:param name: parameter name
:type name: str
:param output_name: bind input port name
:type output_name: str
:return: output description
:rtype: ParamDef | 5.517224 | 8.044626 | 0.685827 |
obj = cls(name)
obj.exporter = 'get_output_table_partition'
obj.output_name = output_name
return obj | def build_output_partitions(cls, name='inputTablePartitions', output_name='output') | Build an output table partition parameter
:param name: parameter name
:type name: str
:param output_name: bind input port name
:type output_name: str
:return: output description
:rtype: ParamDef | 5.936753 | 7.467345 | 0.795029 |
obj = cls(name)
obj.exporter = 'generate_model_name'
obj.output_name = output_name
return obj | def build_model_name(cls, name='modelName', output_name='output') | Build an output model name parameter.
:param name: model name
:type name: str
:param output_name: bind output port name
:type output_name: str
:return: output description
:rtype: ParamDef | 5.950135 | 9.113585 | 0.652886 |
return cls(name, PortDirection.INPUT, type=PortType.DATA) | def build_data_input(cls, name='input') | Build a data input port.
:param name: port name
:type name: str
:return: port object
:rtype: PortDef | 14.616529 | 12.508473 | 1.16853 |
return cls(name, PortDirection.OUTPUT, type=PortType.DATA, copy_input=copy_input, schema=schema) | def build_data_output(cls, name='output', copy_input=None, schema=None) | Build a data output port.
:param name: port name
:type name: str
:return: port object
:param copy_input: input name where the schema is copied from.
:type copy_input: str
:param schema: k1:v1,k2:v2 string describing the schema to be appended
:type schema: str
... | 5.166586 | 4.911163 | 1.052009 |
return cls(name, PortDirection.INPUT, type=PortType.MODEL) | def build_model_input(cls, name='input') | Build a model input port.
:param name: port name
:type name: str
:return: port object
:rtype: PortDef | 16.353695 | 13.77844 | 1.186905 |
return cls(name, PortDirection.OUTPUT, type=PortType.MODEL) | def build_model_output(cls, name='output') | Build a model output port.
:param name: port name
:type name: str
:return: port object
:rtype: PortDef | 19.872166 | 15.874507 | 1.251829 |
self.ports.append(port)
if port.io_type not in self.port_seqs:
self.port_seqs[port.io_type] = 0
self.port_seqs[port.io_type] += 1
port.sequence = self.port_seqs[port.io_type]
return self | def add_port(self, port) | Add a port object to the definition
:param port: port definition
:type port: PortDef | 2.351657 | 2.425837 | 0.969421 |
for mt in self.metas:
if mt.name == name:
mt.value = value
return self
self.metas.append(MetaDef(name, value))
return self | def add_meta(self, name, value) | Add a pair of meta data to the definition
:param name: name of the meta
:type name: str
:param value: value of the meta
:type value: str | 3.080448 | 3.449439 | 0.893029 |
# fill sequences
for keys, groups in groupby(self.ports, lambda x: x.io_type):
for seq, port in enumerate(groups):
port.sequence = seq
return super(AlgorithmDef, self).serialize() | def serialize(self) | Serialize the algorithm definition | 10.457909 | 8.59722 | 1.216429 |
if regex and isinstance(pat, six.string_types):
import re
try:
re.compile(pat, flags=flags)
except:
raise ValueError('Failed to compile regular expression, '
'please check re.compile("{0}")'.format(pat))
return _string_op(expr, ... | def _contains(expr, pat, case=True, flags=0, regex=True) | Return boolean sequence whether given pattern/regex is contained in each string in the sequence
:param expr: sequence or scalar
:param pat: Character sequence or regular expression
:param case: If True, case sensitive
:type case: bool
:param flags: re module flags, e.g. re.IGNORECASE
:param reg... | 4.382498 | 4.61542 | 0.949534 |
return _string_op(expr, Count, output_type=types.int64,
_pat=pat, _flags=flags) | def _count(expr, pat, flags=0) | Count occurrences of pattern in each string of the sequence or scalar
:param expr: sequence or scalar
:param pat: valid regular expression
:param flags: re module flags, e.g. re.IGNORECASE
:return: | 8.195355 | 12.684113 | 0.646112 |
return _string_op(expr, Endswith, output_type=types.boolean, _pat=pat) | def _endswith(expr, pat) | Return boolean sequence or scalar indicating whether each string in the sequence or scalar
ends with passed pattern. Equivalent to str.endswith().
:param expr:
:param pat: Character sequence
:return: sequence or scalar | 16.404676 | 16.608 | 0.987758 |
return _string_op(expr, Startswith, output_type=types.boolean, _pat=pat) | def _startswith(expr, pat) | Return boolean sequence or scalar indicating whether each string in the sequence or scalar
starts with passed pattern. Equivalent to str.startswith().
:param expr:
:param pat: Character sequence
:return: sequence or scalar | 16.577776 | 17.363415 | 0.954753 |
return _string_op(expr, Extract, _pat=pat, _flags=flags, _group=group) | def _extract(expr, pat, flags=0, group=0) | Find group in each string in the Series using passed regular expression.
:param expr:
:param pat: Pattern or regular expression
:param flags: re module, e.g. re.IGNORECASE
:param group: if None as group 0
:return: sequence or scalar | 7.48719 | 9.161588 | 0.817237 |
return _string_op(expr, Find, output_type=types.int64,
_sub=sub, _start=start, _end=end) | def _find(expr, sub, start=0, end=None) | Return lowest indexes in each strings in the sequence or scalar
where the substring is fully contained between [start:end]. Return -1 on failure.
Equivalent to standard str.find().
:param expr:
:param sub: substring being searched
:param start: left edge index
:param end: right edge index
:... | 8.1717 | 8.223191 | 0.993738 |
return _string_op(expr, RFind, output_type=types.int64,
_sub=sub, _start=start, _end=end) | def _rfind(expr, sub, start=0, end=None) | Return highest indexes in each strings in the sequence or scalar
where the substring is fully contained between [start:end]. Return -1 on failure.
Equivalent to standard str.rfind().
:param expr:
:param sub:
:param start:
:param end:
:return: sequence or scalar | 7.453642 | 7.648519 | 0.974521 |
return _string_op(expr, Replace, _pat=pat, _repl=repl,
_n=n, _case=case, _flags=flags, _regex=regex) | def _replace(expr, pat, repl, n=-1, case=True, flags=0, regex=True) | Replace occurrence of pattern/regex in the sequence or scalar with some other string.
Equivalent to str.replace()
:param expr:
:param pat: Character sequence or regular expression
:param repl: Replacement
:param n: Number of replacements to make from start
:param case: if True, case sensitive
... | 3.832718 | 4.817955 | 0.795507 |
return _string_op(expr, Ljust, _width=width, _fillchar=fillchar) | def _ljust(expr, width, fillchar=' ') | Filling right side of strings in the sequence or scalar with an additional character.
Equivalent to str.ljust().
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with `fillchar`
:param fillchar: Additional character for filling, default is whitespace.
... | 6.573603 | 10.286916 | 0.639026 |
return _string_op(expr, Rjust, _width=width, _fillchar=fillchar) | def _rjust(expr, width, fillchar=' ') | Filling left side of strings in the sequence or scalar with an additional character.
Equivalent to str.rjust().
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with `fillchar`
:param fillchar: Additional character for filling, default is whitespace.
... | 8.296474 | 8.384538 | 0.989497 |
return _string_op(expr, Split, output_type=types.List(types.string),
_pat=pat, _n=n) | def _split(expr, pat=None, n=-1) | Split each string (a la re.split) in the Series/Index by given pattern, propagating NA values.
Equivalent to str.split().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: not supported right now
:return: list sequence or scalar | 9.614055 | 9.966789 | 0.964609 |
return _string_op(expr, RSplit, output_type=types.List(types.string),
_pat=pat, _n=n) | def _rsplit(expr, pat=None, n=-1) | Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0 and -1 will be interpreted as return all split... | 9.899557 | 10.726748 | 0.922885 |
if not isinstance(fillchar, six.string_types):
msg = 'fillchar must be a character, not {0}'
raise TypeError(msg.format(type(fillchar).__name__))
if len(fillchar) != 1:
raise TypeError('fillchar must be a character, not str')
if side not in ('left', 'right', 'both'):
... | def _pad(expr, width, side='left', fillchar=' ') | Pad strings in the sequence or scalar with an additional character to specified side.
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with spaces
:param side: {‘left’, ‘right’, ‘both’}, default ‘left’
:param fillchar: Additional character for filling, ... | 2.639976 | 2.572779 | 1.026118 |
return _string_op(expr, Slice, _start=start, _end=stop, _step=step) | def _slice(expr, start=None, stop=None, step=None) | Slice substrings from each element in the sequence or scalar
:param expr:
:param start: int or None
:param stop: int or None
:param step: int or None
:return: sliced | 10.745261 | 11.597875 | 0.926485 |
return _string_op(expr, Strptime, _date_format=date_format,
output_type=types.datetime) | def _strptime(expr, date_format) | Return datetimes specified by date_format,
which supports the same string format as the python standard library.
Details of the string format can be found in python string format doc
:param expr:
:param date_format: date format string (e.g. “%Y-%m-%d”)
:type date_format: str
:return: | 16.369942 | 22.522926 | 0.726812 |
return _string_op(expr, StringToDict, _item_delim=item_delim, _kv_delim=kv_delim,
output_type=types.Dict(types.string, types.string)) | def _todict(expr, item_delim=',', kv_delim='=') | Convert the string sequence / expr into a string dict given item and key-value delimiters.
:param expr:
:param item_delim: delimiter between data items
:param kv_delim: delimiter between keys and values
:return: dict sequence or scalar | 5.260211 | 7.509885 | 0.700438 |
tset = set()
if prefix.startswith(TEMP_TABLE_PREFIX):
prefix = TEMP_TABLE_MODEL_PREFIX + prefix[len(TEMP_TABLE_PREFIX):]
it = self.list_tables(project=project, prefix=prefix)
else:
it = self.list_tables(project=project, prefix=TABLE_MODEL_PREFIX + prefix)
if TEMP_TABLE_... | def _list_tables_model(self, prefix='', project=None) | List all TablesModel in the given project.
:param prefix: model prefix
:param str project: project name, if you want to look up in another project
:rtype: list[str] | 2.280167 | 2.327105 | 0.97983 |
tunnel = self._create_volume_tunnel(endpoint=endpoint)
download_id = self._download_id if not reopen else None
download_session = tunnel.create_download_session(volume=self.volume.name, partition_spec=self.name,
file_name=file_na... | def open_reader(self, file_name, reopen=False, endpoint=None, start=None, length=None, **kwargs) | Open a volume file for read. A file-like object will be returned which can be used to read contents from
volume files.
:param str file_name: name of the file
:param bool reopen: whether we need to open an existing read session
:param str endpoint: tunnel service URL
:param start... | 3.192375 | 3.333667 | 0.957616 |
tunnel = self._create_volume_tunnel(endpoint=endpoint)
upload_id = self._upload_id if not reopen else None
upload_session = tunnel.create_upload_session(volume=self.volume.name, partition_spec=self.name,
upload_id=upload_id, **kwargs... | def open_writer(self, reopen=False, endpoint=None, **kwargs) | Open a volume partition to write to. You can use `open` method to open a file inside the volume and write to it,
or use `write` method to write to specific files.
:param bool reopen: whether we need to open an existing write session
:param str endpoint: tunnel service URL
:param compres... | 2.620043 | 2.497369 | 1.049121 |
from .delay import Delay
if 'async' in kwargs:
kwargs['async_'] = kwargs['async']
execute_keys = ('ui', 'async_', 'n_parallel', 'timeout', 'close_and_notify')
execute_kw = dict((k, v) for k, v in six.iteritems(kwargs) if k in execute_keys)
persist_kw = dict(... | def batch_persist(dfs, tables, *args, **kwargs) | Persist multiple DataFrames into ODPS.
:param dfs: DataFrames to persist.
:param tables: Table names to persist to. Use (table, partition) tuple to store to a table partition.
:param args: args for Expr.persist
:param kwargs: kwargs for Expr.persist
:Examples:
>>> DataF... | 3.569469 | 3.634478 | 0.982113 |
if not self._iter_local:
params = dict()
if name is not None:
params['name'] = name
url = self.resource()
resp = self._client.get(url, params=params)
Roles.parse(self._client, resp, obj=self)
for role in self.roles:
... | def iterate(self, name=None) | :return: | 4.864944 | 4.825038 | 1.008271 |
width, height = get_console_size()
max_columns = options.display.max_columns
nb_columns = len(self.columns)
# exceed max columns
if ((max_columns and nb_columns > max_columns) or
((not ignore_width) and width and nb_columns > (width // 2))):
... | def _repr_fits_horizontal_(self, ignore_width=False) | Check if full repr fits in horizontal boundaries imposed by the display
options width and max_columns. In case off non-interactive session, no
boundaries apply.
ignore_width is here so ipnb+HTML output can behave the way
users expect. display.max_columns remains in effect.
GH354... | 8.720835 | 7.632183 | 1.14264 |
# qtconsole doesn't report its line width, and also
# behaves badly when outputting an HTML table
# that doesn't fit the window, so disable it.
# XXX: In IPython 3.x and above, the Qt console will not attempt to
# display HTML, so this check can be removed when support f... | def _repr_html_(self) | Return a html representation for a particular DataFrame.
Mainly for IPython notebook. | 6.003615 | 5.462416 | 1.099077 |
formatter = fmt.ResultFrameFormatter(self, buf=buf, columns=columns,
col_space=col_space, na_rep=na_rep,
formatters=formatters,
float_format=float_format,
... | def to_html(self, buf=None, columns=None, col_space=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=None, index_names=True,
justify=None, bold_rows=True, classes=None, escape=True,
max_rows=None, max_cols=None, sho... | Render a DataFrame as an HTML table.
`to_html`-specific options:
bold_rows : boolean, default True
Make the row labels bold in the output
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table
escape : boolean, default Tr... | 1.980684 | 2.522295 | 0.78527 |
dict = {}
size = winreg.QueryInfoKey(key)[1]
for i in range(size):
data = winreg.EnumValue(key, i)
dict[data[0]] = data[1]
return dict | def valuestodict(key) | Convert a registry key's values to a dictionary. | 2.422196 | 2.116371 | 1.144504 |
global _cache_tz
if _cache_tz is None:
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz | def get_localzone() | Returns the zoneinfo-based tzinfo object that matches the Windows-configured timezone. | 4.123689 | 4.005364 | 1.029542 |
global _cache_tz
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz | def reload_localzone() | Reload the cached localzone. You need to call this if the timezone has changed. | 5.692283 | 5.207062 | 1.093185 |
async_ = kw.get('async', async_)
headers = {'Content-Type': 'application/xml'}
new_kw = dict()
if self.offline_model_name:
upload_keys = ('_parent', 'name', 'offline_model_name', 'offline_model_project', 'qos', 'instance_num')
else:
upload_keys =... | def update(self, async_=False, **kw) | Update online model parameters to server. | 4.64481 | 4.362303 | 1.064761 |
while self.status in (OnlineModel.Status.DEPLOYING, OnlineModel.Status.UPDATING):
time.sleep(interval)
if self.status == OnlineModel.Status.DEPLOY_FAILED:
raise OnlineModelError(self.last_fail_msg, self)
elif self.status != OnlineModel.Status.SERVING:
... | def wait_for_service(self, interval=1) | Wait for the online model to be ready for service.
:param interval: check interval | 3.738654 | 3.65589 | 1.022639 |
deleted = False
while True:
try:
if self.status != OnlineModel.Status.DELETING:
break
except errors.NoSuchObject:
deleted = True
break
time.sleep(interval)
if not deleted:
... | def wait_for_deletion(self, interval=1) | Wait for the online model to be deleted.
:param interval: check interval | 4.221592 | 4.080294 | 1.034629 |
from .. import Projects
if endpoint is not None:
self._endpoint = endpoint
if self._predict_rest is None:
# do not add project option
self._predict_rest = RestClient(self._client.account, self._endpoint, proxy=options.data_proxy)
json_data =... | def predict(self, data, schema=None, endpoint=None) | Predict data labels with current online model.
:param data: data to be predicted
:param schema: schema of input data
:param endpoint: endpoint of predict service
:return: prediction result | 5.803469 | 5.982747 | 0.970034 |
if not new_path.startswith('/'):
new_path = self._normpath(self.dirname + '/' + new_path)
else:
new_path = self._normpath(new_path)
if new_path == self.path:
raise ValueError('New path should be different from the original one.')
update_def = ... | def move(self, new_path, replication=None) | Move current path to a new location.
:param new_path: target location of current file / directory
:param replication: number of replication | 3.799335 | 4.190096 | 0.906742 |
proto = udf.get_annotation(udf_class)
in_types, out_types = parse_proto(proto)
stdin = stdin or sys.stdin
arg_parser = ArgParser(in_types, stdin, input_col_delim, null_indicator)
stdin_feed = make_feed(arg_parser)
collector = StdoutCollector(out_types)
ctor = _get_runner_class(udf_class... | def get_default_runner(udf_class, input_col_delim=',', null_indicator='NULL', stdin=None) | Create a default runner with specified udf class. | 4.463936 | 4.473771 | 0.997802 |
if not isinstance(algo_defs, Iterable):
algo_defs = [algo_defs, ]
load_algorithms(algo_defs, 'BaseTrainingAlgorithm', env) | def load_classifiers(algo_defs, env) | Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class.
:param algo_defs: algorithm definitions
:type algo_defs: AlgorithmDef | list[AlgorithmDef]
:param env: environment
:Example:
>>> import sys
>>> from odps.ml.algolib.loader import *
>>> a = XflowAlgorit... | 5.52151 | 6.712668 | 0.822551 |
if not isinstance(algo_defs, Iterable):
algo_defs = [algo_defs, ]
load_algorithms(algo_defs, 'BaseProcessAlgorithm', env) | def load_process_algorithm(algo_defs, env) | Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class.
:param algo_defs: algorithm definitions
:type algo_defs: AlgorithmDef | list[AlgorithmDef]
:param env: environment
:Example:
>>> import sys
>>> from odps.ml.algolib.loader import *
>>> a = XflowAlgorit... | 4.733404 | 6.039608 | 0.783727 |
import time
if time.daylight and time.localtime().tm_isdst > 0:
return -time.altzone
else:
return -time.timezone | def get_system_offset() | Get system's timezone offset using built-in library time.
For the Timezone constants (altzone, daylight, timezone, and tzname), the
value is determined by the timezone rules in effect at module load time or
the last time tzset() is called and may be incorrect for times in the past.
To keep compatibili... | 3.186609 | 2.466305 | 1.292058 |
tz_offset = get_tz_offset(tz)
system_offset = get_system_offset()
if tz_offset != system_offset:
msg = ('Timezone offset does not match system offset: {0} != {1}. '
'Please, check your config files.').format(
tz_offset, system_offset
)
ra... | def assert_tz_offset(tz) | Assert that system's timezone offset equals to the timezone offset found.
If they don't match, we probably have a misconfiguration, for example, an
incorrect timezone set in /etc/timezone file in systemd distributions. | 3.256306 | 3.400874 | 0.957491 |
if self._resources_objects is not None:
return self._resources_objects
resources = self.parent.parent.resources
resources = [resources[name] for name in self._resources]
self._resources_objects = resources
return resources | def resources(self) | Return all the resources which this function refer to.
:return: resources
:rtype: list
.. seealso:: :class:`odps.models.Resource` | 4.30266 | 4.438388 | 0.969419 |
if self._owner_changed:
self.update_owner(self.owner)
self._resources = [res.name for res in self.resources]
return self.parent.update(self) | def update(self) | Update this function.
:return: None | 7.26413 | 7.939363 | 0.914951 |
def method(self, table_name, **kwargs):
if self.odps.exist_table(table_name):
return
if kwargs.get('project', self.odps.project) != self.odps.project:
tunnel = TableTunnel(self.odps, project=kwargs['project'])
else:
tunnel = self.tunnel
func(s... | def table_creator(func) | Decorator for table creating method | 3.370181 | 3.335281 | 1.010464 |
parts = fullmodname.split('.')
submodname = parts[-1]
for f in self._files:
for prefix in self._prefixes[id(f)]:
for suffix, is_package in _SEARCH_ORDER:
l = [prefix] + parts[:-1] + [submodname + suffix.replace('/', os.sep)]
... | def _get_info(self, fullmodname) | Internal helper for find_module() and load_module().
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
A tuple (submodname, is_package, relpath, fileobj) where:
submodname: The final component of the module name, e.g. 'mail'.
... | 3.394261 | 3.091486 | 1.097938 |
submodname, is_package, relpath, fileobj = self._get_info(fullmodname)
fullpath = '%s%s%s' % (fileobj, os.sep, relpath)
if isinstance(fileobj, zipfile.ZipFile):
source = fileobj.read(relpath.replace(os.sep, '/'))
elif isinstance(fileobj, tarfile.TarFile):
... | def _get_source(self, fullmodname) | Internal helper for load_module().
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
A tuple (submodname, is_package, fullpath, source) where:
submodname: The final component of the module name, e.g. 'mail'.
is_package:... | 2.155138 | 1.973208 | 1.0922 |
submodname, is_package, fullpath, source = self._get_source(fullmodname)
code = compile(source, fullpath, 'exec')
mod = sys.modules.get(fullmodname)
try:
if mod is None:
mod = sys.modules[fullmodname] = types.ModuleType(fullmodname)
mod.__... | def load_module(self, fullmodname) | PEP-302-compliant load_module() method.
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
The module object constructed from the source code.
Raises:
SyntaxError if the module's source code is syntactically incorrect.
... | 2.050682 | 2.260216 | 0.907295 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
return _run_cm_node(df, col_true, col_pred)[0] | def confusion_matrix(df, col_true=None, col_pred=None) | Compute confusion matrix of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true label
:type col_true: str
:param col_true: column name of predicted label, 'prediction_res... | 5.318471 | 6.708462 | 0.7928 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
mat, _ = _run_cm_node(df, col_true, col_pred)
if np is not None:
acc_count = np.sum(np.diag(mat))
if not normalize:
return acc_count
else:
return acc_count * 1.0 / n... | def accuracy_score(df, col_true=None, col_pred=None, normalize=True) | Compute accuracy of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true label
:type col_true: str
:param col_true: column name of predicted label, 'prediction_result' by ... | 2.890656 | 2.899482 | 0.996956 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
mat, label_list = _run_cm_node(df, col_true, col_pred)
class_dict = dict((label, idx) for idx, label in enumerate(label_list))
tps = np.diag(mat)
pred_count = np.sum(mat, axis=0)
if average is None:
... | def precision_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None) | r"""
Compute precision of a predicted DataFrame. Precision is defined as :math:`\frac{TP}{TP + TN}`
:Parameters:
- **df** - predicted data frame
- **col_true** - column name of true label
- **col_pred** - column name of predicted label, 'prediction_result' by default.
- **pos_la... | 2.423801 | 2.585496 | 0.937461 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
mat, label_list = _run_cm_node(df, col_true, col_pred)
class_dict = dict((label, idx) for idx, label in enumerate(label_list))
tps = np.diag(mat)
supp_count = np.sum(mat, axis=1)
if average is None:
... | def recall_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None) | r"""
Compute recall of a predicted DataFrame. Precision is defined as :math:`\frac{TP}{TP + FP}`
:Parameters:
- **df* - predicted data frame
- **col_true** - column name of true label
- **col_pred** - column name of predicted label, 'prediction_result' by default.
- **pos_label*... | 2.843996 | 3.121058 | 0.911228 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
mat, label_list = _run_cm_node(df, col_true, col_pred)
class_dict = dict((label, idx) for idx, label in enumerate(label_list))
tps = np.diag(mat)
pred_count = np.sum(mat, axis=0)
supp_count = np.sum(m... | def fbeta_score(df, col_true=None, col_pred='precision_result', beta=1.0, pos_label=1, average=None) | r"""
Compute f-beta score of a predicted DataFrame. f-beta is defined as
.. math::
\frac{1 + \beta^2 \cdot precision \cdot recall}{\beta^2 \cdot precision + recall}
F-beta score is a generalization of f-1 score.
:Parameters:
- **df** - predicted data frame
- **col_true** - co... | 2.44031 | 2.530478 | 0.964367 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
return fbeta_score(df, col_true, col_pred, pos_label=pos_label, average=average) | def f1_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None) | r"""
Compute f-1 score of a predicted DataFrame. f-1 is defined as
.. math::
\frac{2 \cdot precision \cdot recall}{precision + recall}
:Parameters:
- **df** - predicted data frame
- **col_true** - column name of true label
- **col_pred** - column name of predicted label, ... | 3.753279 | 5.834029 | 0.643343 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node(df, pos_label, col_true, col_pred, col_scores)
if np is not None:
... | def roc_curve(df, col_true=None, col_pred=None, col_scores=None, pos_label=1) | r"""
Compute true positive rate (TPR), false positive rate (FPR) and threshold from predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive label
:type pos_label: str
:param col_true... | 2.107997 | 2.348341 | 0.897654 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node(df, pos_label, col_true, col_pred, col_scores)
depth = (tp + fp) * 1.0 / (... | def gain_chart(df, col_true=None, col_pred=None, col_scores=None, pos_label=1) | r"""
Compute positive proportion, true positive rate (TPR) and threshold from predicted DataFrame. The trace can be plotted as a cumulative gain chart
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive labe... | 2.957242 | 3.150108 | 0.938775 |
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node(df, pos_label, col_true, col_pred, col_scores)
depth = (tp + fp) * 1.0 / (... | def lift_chart(df, col_true=None, col_pred=None, col_scores=None, pos_label=1) | r"""
Compute life value, true positive rate (TPR) and threshold from predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive label
:type pos_label: str
:param col_true: true column
... | 3.193465 | 3.323787 | 0.960791 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node(df, pos_label, col_true, col_pred, col_scores)
tpr = tp * 1.0 / (tp + fn)
... | def roc_auc_score(df, col_true=None, col_pred=None, col_scores=None, pos_label=1) | Compute Area Under the Curve (AUC) from prediction scores with trapezoidal rule.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive label
:type pos_label: str
:param col_true: true column
:type col_... | 2.404794 | 2.425546 | 0.991445 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node(df, pos_label, col_true, col_pred, col_scores)
precisions = np.squeeze(np.a... | def average_precision_score(df, col_true=None, col_pred=None, col_scores=None, pos_label=1) | Compute average precision score, i.e., the area under precision-recall curve.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive label
:type pos_label: str
:param col_true: true column
:type col... | 2.502132 | 2.443087 | 1.024168 |
if not 0 <= wire_type <= _WIRETYPE_MAX:
raise errors.EncodeError('Unknown wire type: %d' % wire_type)
return (field_number << TAG_TYPE_BITS) | wire_type | def pack_tag(field_number, wire_type) | Returns an unsigned 32-bit integer that encodes the field number and
wire type information in standard protocol message wire format.
Args:
field_number: Expected to be an integer in the range [1, 1 << 29)
wire_type: One of the WIRETYPE_* constants. | 3.659138 | 4.820497 | 0.759079 |
if uint64 > UINT64_MAX:
raise errors.EncodeError('Value out of range: %d' % uint64)
bytes = 1
while uint64 > 0x7f:
bytes += 1
uint64 >>= 7
return bytes | def _var_uint64_byte_size_no_tag(uint64) | Returns the bytes required to serialize a single varint.
uint64 must be unsigned. | 2.970389 | 2.621172 | 1.133229 |
objs = self._do_transform(*args, **kwargs)
obj_list = [objs, ] if not isinstance(objs, Iterable) else objs
for obj in obj_list:
if not isinstance(obj, ODPSModelExpr):
continue
for meta in ['predictor', 'recommender']:
if meta not i... | def train(self, *args, **kwargs) | Perform training on a DataFrame.
The label field is specified by the ``label_field`` method.
:param train_data: DataFrame to be trained. Label field must be specified.
:type train_data: DataFrame
:return: Trained model
:rtype: MLModel | 5.459229 | 5.741541 | 0.95083 |
cases = kwargs.pop('_cases', [])
if not isinstance(cases, Iterable):
cases = [cases, ]
result_callback = kwargs.pop('_result_callback', None)
execute_now = kwargs.pop('execute_now', True)
exec_id = self._get_exec_id()
params = dict((k, v.value) for k... | def calc(self, *args, **kwargs) | :type args: list[DataFrame] | 3.444748 | 3.458836 | 0.995927 |
if timeout is not None:
end_time = timeout + time.time()
fs = set(fs)
with _AcquireFutures(fs):
finished = set(
f for f in fs
if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
pending = fs - finished
waiter = _create_and_install_waiters(... | def as_completed(fs, timeout=None) | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | 3.126752 | 3.216891 | 0.97198 |
with _AcquireFutures(fs):
done = set(f for f in fs
if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
not_done = set(fs) - done
if (return_when == FIRST_COMPLETED) and done:
return DoneAndNotDoneFutures(done, not_done)
elif (return_when == FIRST_E... | def wait(fs, timeout=None, return_when=ALL_COMPLETED) | Wait for the futures in the given sequence to complete.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
wait upon.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
return_when: Indicates ... | 2.870337 | 2.998004 | 0.957416 |
with self._condition:
if self._state in [RUNNING, FINISHED]:
return False
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
return True
self._state = CANCELLED
self._condition.notify_all()
self._invoke_callb... | def cancel(self) | Cancel the future if possible.
Returns True if the future was cancelled, False otherwise. A future
cannot be cancelled if it is running or has already completed. | 3.455864 | 2.783859 | 1.241393 |
with self._condition:
if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
self._done_callbacks.append(fn)
return
fn(self) | def add_done_callback(self, fn) | Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called by a thread in the same process in which
... | 3.933539 | 3.480331 | 1.13022 |
with self._condition:
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self.__get_result()
self._condition.wait(timeout)
if self._state in [CANCELLED, CANC... | def result(self, timeout=None) | Return the result of the call that the future represents.
Args:
timeout: The number of seconds to wait for the result if the future
isn't done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
... | 2.201235 | 2.052779 | 1.072319 |
with self._condition:
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self._exception, self._traceback
self._condition.wait(timeout)
if self._state in [CA... | def exception_info(self, timeout=None) | Return a tuple of (exception, traceback) raised by the call that the
future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
Th... | 2.110089 | 1.904857 | 1.107741 |
with self._condition:
self._exception = exception
self._traceback = traceback
self._state = FINISHED
for waiter in self._waiters:
waiter.add_exception(self)
self._condition.notify_all()
self._invoke_callbacks() | def set_exception_info(self, exception, traceback) | Sets the result of the future as being the given exception
and traceback.
Should only be used by Executor implementations and unit tests. | 3.514227 | 3.556428 | 0.988134 |
timeout = kwargs.get('timeout')
if timeout is not None:
end_time = timeout + time.time()
fs = [self.submit(fn, *args) for args in itertools.izip(*iterables)]
# Yield must be hidden in closure so that the futures are submitted
# before the first iterator val... | def map(self, fn, *iterables, **kwargs) | Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | 3.477436 | 3.496275 | 0.994612 |
CloudPickler(file, protocol=protocol, dump_code=dump_code).dump(obj) | def dump(obj, file, protocol=None, dump_code=False) | Serialize obj as bytes streamed into file
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensur... | 3.950635 | 5.442881 | 0.725835 |
if base_globals is None:
base_globals = {}
elif isinstance(base_globals, string_types):
base_globals_name = base_globals
try:
# First try to reuse the globals from the module containing the
# function. If it is not possible to retrieve it, fallback to an
... | def _make_skel_func(code, cell_count, base_globals=None) | Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty. | 2.861865 | 2.889843 | 0.990319 |
self.modules.add(obj)
if _is_dynamic(obj):
self.save_reduce(dynamic_subimport, (obj.__name__, vars(obj)),
obj=obj)
else:
self.save_reduce(subimport, (obj.__name__,), obj=obj) | def save_module(self, obj) | Save a module as an import | 5.429737 | 4.966143 | 1.093351 |
if self.dump_code:
print(obj.co_name)
dis.dis(obj.co_code)
self.save_reduce(types.CodeType, self._extract_code_args(obj), obj=obj) | def save_codeobject(self, obj) | Save a code object | 5.995791 | 5.783269 | 1.036748 |
code = func.__code__
# extract all global ref's
func_global_refs = self.extract_code_globals(code)
# process all variables referenced by global environment
f_globals = {}
for var in func_global_refs:
if var in func.__globals__:
f_glo... | def extract_func_data(self, func) | Turn the function into a tuple of data necessary to recreate it:
code, globals, defaults, closure_values, dict | 4.236668 | 3.931935 | 1.077502 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.