_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12600 | Client._select_next_server | train | def _select_next_server(self):
"""
Looks up in the server pool for an available server
and attempts to connect.
"""
# Continue trying to connect until there is an available server
# or bail in case there are no more available servers.
while True:
if len(self._server_pool) == 0:
self._current_server = None
raise ErrNoServers
now = time.time()
s = self._server_pool.pop(0)
if self.options["max_reconnect_attempts"] > 0:
if s.reconnects > self.options["max_reconnect_attempts"]:
# Discard server since already tried to reconnect too many times.
continue
# Not yet exceeded max_reconnect_attempts so can still use
# this server in the future.
self._server_pool.append(s)
if s.last_attempt is not None and now < s.last_attempt + self.options["reconnect_time_wait"]:
# Backoff connecting to server if | python | {
"resource": ""
} |
q12601 | Client._close | train | def _close(self, status, do_callbacks=True):
"""
Takes the status on which it should leave the connection
and an optional boolean parameter to dispatch the disconnected
and close callbacks if there are any.
"""
if self.is_closed:
self._status = status
return
self._status = Client.CLOSED
# Stop background tasks
yield self._end_flusher_loop()
if self._ping_timer is not None and self._ping_timer.is_running():
self._ping_timer.stop()
if not self.io.closed():
self.io.close()
# Cleanup subscriptions since not reconnecting so no need
| python | {
"resource": ""
} |
q12602 | Client.drain | train | def drain(self, sid=None):
"""
Drain will put a connection into a drain state. All subscriptions will
immediately be put into a drain state. Upon completion, the publishers
will be drained and can not publish any additional messages. Upon draining
of the publishers, the connection will be closed. Use the `closed_cb'
option to know when the connection has moved from draining to closed.
If a sid is passed, just the subscription with that sid will be drained
without closing the connection.
"""
if self.is_draining:
return
if self.is_closed:
raise ErrConnectionClosed
if self.is_connecting or self.is_reconnecting:
raise ErrConnectionReconnecting
# Drain a single subscription
if sid is not None:
raise tornado.gen.Return(self._drain_sub(sid))
# Start draining the subscriptions
self._status = Client.DRAINING_SUBS
drain_tasks = []
for ssid, sub in self._subs.items():
task = self._drain_sub(ssid)
drain_tasks.append(task) | python | {
"resource": ""
} |
q12603 | Client._process_err | train | def _process_err(self, err=None):
"""
Stores the last received error from the server and dispatches the error callback.
"""
self.stats['errors_received'] += 1
if err == "'Authorization Violation'":
self._err = ErrAuthorization
elif err == "'Slow Consumer'":
| python | {
"resource": ""
} |
q12604 | Client._read_loop | train | def _read_loop(self, data=''):
"""
Read loop for gathering bytes from the server in a buffer
of maximum MAX_CONTROL_LINE_SIZE, then received bytes are streamed
to the parsing callback for processing.
"""
while True:
if not self.is_connected or self.is_connecting or self.io.closed():
break
try:
yield self.io.read_bytes(
DEFAULT_READ_CHUNK_SIZE,
| python | {
"resource": ""
} |
q12605 | Client._flusher_loop | train | def _flusher_loop(self):
"""
Coroutine which continuously tries to consume pending commands
and then flushes them to the socket.
"""
while True:
pending = []
pending_size = 0
try:
# Block and wait for the flusher to be kicked
yield self._flush_queue.get()
# Check whether we should bail first
if not self.is_connected or self.is_connecting or self.io.closed():
break
# Flush only when we actually have something in buffer...
if self._pending_size > 0:
cmds = b''.join(self._pending)
# Reset pending queue and store tmp in case write fails
self._pending, pending = [], self._pending
self._pending_size, pending_size = 0, self._pending_size
| python | {
"resource": ""
} |
q12606 | Client._end_flusher_loop | train | def _end_flusher_loop(self):
"""
Let flusher_loop coroutine quit - useful when disconnecting.
"""
if not self.is_connected or self.is_connecting or self.io.closed():
if self._flush_queue | python | {
"resource": ""
} |
q12607 | yaml_load | train | def yaml_load(source, defaultdata=NO_DEFAULT):
"""merge YAML data from files found in source
Always returns a dict. The YAML files are expected to contain some kind of
key:value structures, possibly deeply nested. When merging, lists are
appended and dict keys are replaced. The YAML files are read with the
yaml.safe_load function.
source can be a file, a dir, a list/tuple of files or a string containing
a glob expression (with ?*[]).
For a directory, all *.yaml files will be read in alphabetical order.
defaultdata can be used to initialize the data.
"""
logger = logging.getLogger(__name__)
logger.debug("initialized with source=%s, defaultdata=%s", source, defaultdata)
if defaultdata is NO_DEFAULT:
data = None
else:
data = defaultdata
files = []
if type(source) is not str and len(source) == 1:
# when called from __main source is always a list, even if it contains only one item.
# turn into a string if it contains only one item to support our different call modes
source = source[0]
if type(source) is list or type(source) is tuple:
# got a list, assume to be files
files = source
elif os.path.isdir(source):
# got a dir, read all *.yaml files
files = sorted(glob.glob(os.path.join(source, "*.yaml")))
elif os.path.isfile(source):
# got a single file, turn it into list to use the | python | {
"resource": ""
} |
q12608 | BusinessTime.iterdays | train | def iterdays(self, d1, d2):
"""
Date iterator returning dates in d1 <= x < d2
"""
curr = datetime.datetime.combine(d1, datetime.time())
end = datetime.datetime.combine(d2, datetime.time())
if d1.date() == d2.date():
| python | {
"resource": ""
} |
q12609 | BusinessTime.iterweekdays | train | def iterweekdays(self, d1, d2):
"""
Date iterator returning dates in d1 <= x < d2, excluding weekends
"""
| python | {
"resource": ""
} |
q12610 | BusinessTime.iterbusinessdays | train | def iterbusinessdays(self, d1, d2):
"""
Date iterator returning dates in d1 <= x < d2, excluding weekends and holidays
"""
assert d2 >= d1
if d1.date() == d2.date() and d2.time() < self.business_hours[0]:
return
first = True
for dt in self.iterdays(d1, | python | {
"resource": ""
} |
q12611 | BusinessTime.businesstimedelta | train | def businesstimedelta(self, d1, d2):
"""
Returns a datetime.timedelta with the number of full business days
and business time between d1 and d2
"""
if d1 > d2:
d1, d2, timedelta_direction = d2, d1, -1
else:
timedelta_direction = 1
businessdays = self._build_spanning_datetimes(d1, d2)
time = datetime.timedelta()
if len(businessdays) == 0:
# HACK: manually handle the case when d1 is after business hours while d2 is during
if self.isduringbusinesshours(d2):
time += d2 - datetime.datetime.combine(d2,
self.business_hours[0])
# HACK: manually handle the case where d1 is on an earlier non-business day and d2 is after hours on a business day
elif not self.isbusinessday(d1) and self.isbusinessday(d2):
if d2.time() > self.business_hours[1]:
time += datetime.datetime.combine(
d2,
self.business_hours[1]) - datetime.datetime.combine(
d2, self.business_hours[0])
elif d2.time() > self.business_hours[0]:
time += d2 - datetime.datetime.combine(
d2, self.business_hours[0])
else:
prev = None
current = None
count = 0
for d in businessdays:
if current is None:
| python | {
"resource": ""
} |
q12612 | BusinessTime.businesstime_hours | train | def businesstime_hours(self, d1, d2):
"""
Returns a datetime.timedelta of business hours between d1 and d2,
based on the length of the businessday | python | {
"resource": ""
} |
q12613 | USFederalHolidays._day_rule_matches | train | def _day_rule_matches(self, rule, dt):
"""
Day-of-month-specific US federal holidays that fall on Sat or Sun are
observed on Fri or Mon respectively. Note that this method considers
both the actual holiday and the day of observance to be holidays.
"""
if dt.weekday() == 4:
sat = dt + datetime.timedelta(days=1)
if super(USFederalHolidays, self)._day_rule_matches(rule, sat):
return True
elif dt.weekday() == 0:
| python | {
"resource": ""
} |
q12614 | PickleShareDB.hcompress | train | def hcompress(self, hashroot):
""" Compress category 'hashroot', so hset is fast again
hget will fail if fast_only is True for compressed items (that were
hset before hcompress).
"""
hfiles = self.keys(hashroot + "/*") | python | {
"resource": ""
} |
q12615 | PickleShareDB.keys | train | def keys(self, globpat = None):
""" All keys in DB, or all keys matching a glob"""
if globpat is None:
files = self.root.rglob('*')
else:
| python | {
"resource": ""
} |
q12616 | PickleShareDB.uncache | train | def uncache(self,*items):
""" Removes all, or specified items from cache
Use this after reading a large amount of large objects
to free up memory, when you won't be needing the objects
for a while.
| python | {
"resource": ""
} |
q12617 | hacking_has_only_comments | train | def hacking_has_only_comments(physical_line, filename, lines, line_number):
"""Check for empty files with only comments
H104 empty file with only comments
"""
| python | {
"resource": ""
} |
q12618 | _project_is_apache | train | def _project_is_apache():
"""Determine if a project is Apache.
Look for a key string in a set of possible license files to figure out
if a project looks to be Apache. This is used as a precondition for
enforcing license headers.
"""
global _is_apache_cache
if _is_apache_cache is not None:
return _is_apache_cache
license_files = ["LICENSE"]
for filename in license_files:
try:
with open(filename, "r") as file:
for line in | python | {
"resource": ""
} |
q12619 | _check_for_exact_apache | train | def _check_for_exact_apache(start, lines):
"""Check for the Apache 2.0 license header.
We strip all the newlines and extra spaces so this license string
should work regardless of indentation in the file.
"""
APACHE2 = """
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License."""
# out of all the formatting I've seen, a 12 line version seems to be the
# longest in the source tree. So just take the 12 lines starting with where
| python | {
"resource": ""
} |
q12620 | hacking_no_author_tags | train | def hacking_no_author_tags(physical_line):
"""Check that no author tags are used.
H105 don't use author tags
"""
for regex in AUTHOR_TAG_RE:
if regex.match(physical_line):
| python | {
"resource": ""
} |
q12621 | hacking_python3x_except_compatible | train | def hacking_python3x_except_compatible(logical_line, noqa):
r"""Check for except statements to be Python 3.x compatible
As of Python 3.x, the construct 'except x,y:' has been removed.
Use 'except x as y:' instead.
Okay: try:\n pass\nexcept Exception:\n pass
Okay: try:\n pass\nexcept (Exception, AttributeError):\n pass
H231: try:\n pass\nexcept AttributeError, e:\n pass
Okay: try:\n pass\nexcept AttributeError, e: # noqa\n pass
"""
if noqa:
return
def is_old_style_except(logical_line):
return (',' in | python | {
"resource": ""
} |
q12622 | hacking_python3x_octal_literals | train | def hacking_python3x_octal_literals(logical_line, tokens, noqa):
r"""Check for octal literals in Python 3.x compatible form.
As of Python 3.x, the construct "0755" has been removed.
Use "0o755" instead".
Okay: f(0o755)
Okay: 'f(0755)'
Okay: f(755)
Okay: f(0)
Okay: f(000)
Okay: MiB = 1.0415
H232: f(0755)
Okay: f(0755) # noqa
"""
if noqa:
return
for token_type, text, _, _, _ in tokens:
if token_type == tokenize.NUMBER:
| python | {
"resource": ""
} |
q12623 | hacking_python3x_print_function | train | def hacking_python3x_print_function(logical_line, noqa):
r"""Check that all print occurrences look like print functions.
Check that all occurrences of print look like functions, not
print operator. As of Python 3.x, the print operator has
been removed.
Okay: print(msg)
Okay: print (msg)
Okay: print msg # noqa
Okay: print()
| python | {
"resource": ""
} |
q12624 | hacking_python3x_metaclass | train | def hacking_python3x_metaclass(logical_line, noqa):
r"""Check for metaclass to be Python 3.x compatible.
Okay: @six.add_metaclass(Meta)\nclass Foo(object):\n pass
Okay: @six.with_metaclass(Meta)\nclass Foo(object):\n pass
Okay: class Foo(object):\n '''docstring\n\n __metaclass__ = Meta\n'''
H236: class Foo(object):\n __metaclass__ = Meta
H236: class Foo(object):\n foo=bar\n __metaclass__ = Meta
H236: class Foo(object):\n '''docstr.'''\n __metaclass__ = Meta
H236: class Foo(object):\n __metaclass__ = \\\n Meta
Okay: class Foo(object):\n __metaclass__ = Meta # noqa
"""
| python | {
"resource": ""
} |
q12625 | hacking_no_removed_module | train | def hacking_no_removed_module(logical_line, noqa):
r"""Check for removed modules in Python 3.
Examples:
Okay: from os import path
Okay: from os import path as p
Okay: from os import (path as p)
Okay: import os.path
H237: import thread
Okay: import thread # noqa
H237: import commands
H237: import md5 as std_md5
"""
if noqa:
| python | {
"resource": ""
} |
q12626 | hacking_no_old_style_class | train | def hacking_no_old_style_class(logical_line, noqa):
r"""Check for old style classes.
Examples:
Okay: class Foo(object):\n pass
Okay: class Foo(Bar, Baz):\n pass
Okay: class Foo(object, Baz):\n pass
Okay: class Foo(somefunc()):\n pass
H238: class Bar:\n pass
H238: class Bar():\n pass
"""
if | python | {
"resource": ""
} |
q12627 | no_vim_headers | train | def no_vim_headers(physical_line, line_number, lines):
r"""Check for vim editor configuration in source files.
By default vim modelines can only appear in the first or
last 5 lines of a source file.
Examples:
H106: # vim: set tabstop=4 shiftwidth=4\n#\n#\n#\n#\n#
H106: # Lic\n# vim: set tabstop=4 shiftwidth=4\n#\n#\n#\n#\n#
H106: # Lic\n#\n#\n#\n#\n#\n#\n#\n#\n# vim: set tabstop=4 shiftwidth=4
Okay: # Lic\n#\n#\n#\n#\n#\n#\n#
Okay: # viminal hill is located in Rome | python | {
"resource": ""
} |
q12628 | hacking_import_rules | train | def hacking_import_rules(logical_line, filename, noqa):
r"""Check for imports.
OpenStack HACKING guide recommends one import per line:
Do not import more than one module per line
Examples:
Okay: from nova.compute import api
H301: from nova.compute import api, utils
Do not use wildcard import
Do not make relative imports
Examples:
Okay: from os import path
Okay: from os import path as p
Okay: from os import (path as p)
Okay: import os.path
Okay: from nova.compute import rpcapi
Okay: from six.moves.urllib import parse
H303: from os.path import *
H304: from .compute import rpcapi
"""
# TODO(jogo): make the following doctests pass:
# H301: import os, sys
# TODO(mordred: We need to split this into different checks so that they
# can be disabled by command line switches properly
if noqa:
return
split_line = logical_line.split()
split_line_len = len(split_line)
if (split_line_len > 1 and split_line[0] in ('import', 'from') and
not core.is_import_exception(split_line[1])):
pos = logical_line.find(',')
if pos != -1:
if split_line[0] == 'from':
yield pos, "H301: one import per line"
| python | {
"resource": ""
} |
q12629 | hacking_import_alphabetical | train | def hacking_import_alphabetical(logical_line, blank_before, previous_logical,
indent_level, previous_indent_level):
r"""Check for imports in alphabetical order.
OpenStack HACKING guide recommendation for imports:
imports in human alphabetical order
Okay: import os\nimport sys\n\nimport nova\nfrom nova import test
Okay: import os\nimport sys
H306: import sys\nimport os
Okay: import sys\n\n# foo\nimport six
"""
# handle import x
# use .lower since capitalization shouldn't | python | {
"resource": ""
} |
q12630 | is_import_exception | train | def is_import_exception(mod):
"""Check module name to see if import has been whitelisted.
Import based rules should not run on any whitelisted module
"""
| python | {
"resource": ""
} |
q12631 | hacking_docstring_start_space | train | def hacking_docstring_start_space(physical_line, previous_logical, tokens):
r"""Check for docstring not starting with space.
OpenStack HACKING guide recommendation for docstring:
Docstring should not start with space
Okay: def foo():\n '''This is good.'''
Okay: def foo():\n r'''This is good.'''
Okay: def foo():\n a = ''' This is not a docstring.'''
Okay: def foo():\n pass\n ''' This is not.'''
H401: def foo():\n ''' This is not.'''
H401: def foo():\n r''' This is not.'''
"""
docstring = is_docstring(tokens, previous_logical)
if docstring:
| python | {
"resource": ""
} |
q12632 | hacking_docstring_multiline_end | train | def hacking_docstring_multiline_end(physical_line, previous_logical, tokens):
r"""Check multi line docstring end.
OpenStack HACKING guide recommendation for docstring:
Docstring should end on a new line
Okay: '''foobar\nfoo\nbar\n'''
Okay: def foo():\n '''foobar\n\nfoo\nbar\n'''
Okay: class Foo(object):\n '''foobar\n\nfoo\nbar\n'''
Okay: def foo():\n a = '''not\na\ndocstring'''
Okay: def foo():\n a = '''not\na\ndocstring''' # blah
Okay: def foo():\n pass\n'''foobar\nfoo\nbar\n d'''
H403: def foo():\n '''foobar\nfoo\nbar\ndocstring'''
H403: def foo():\n '''foobar\nfoo\nbar\npretend raw: r'''
H403: class Foo(object):\n '''foobar\nfoo\nbar\ndocstring'''\n\n
"""
docstring = is_docstring(tokens, previous_logical)
if docstring:
if '\n' not | python | {
"resource": ""
} |
q12633 | hacking_docstring_multiline_start | train | def hacking_docstring_multiline_start(physical_line, previous_logical, tokens):
r"""Check multi line docstring starts immediately with summary.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: '''foobar\n\nfoo\nbar\n'''
Okay: def foo():\n a = '''\nnot\na docstring\n'''
H404: def foo():\n '''\nfoo\nbar\n'''\n\n
H404: def foo():\n r'''\nfoo\nbar\n'''\n\n
"""
docstring = is_docstring(tokens, previous_logical)
if docstring:
if '\n' not in docstring:
# single line docstring
return
| python | {
"resource": ""
} |
q12634 | hacking_docstring_summary | train | def hacking_docstring_summary(physical_line, previous_logical, tokens):
r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot\na docstring\n'''
Okay: '''foobar\n\nfoo\nbar\n'''
H405: def foo():\n '''foobar\nfoo\nbar\n'''
H405: def foo():\n r'''foobar\nfoo\nbar\n'''
H405: def foo():\n '''foobar\n'''
"""
docstring = is_docstring(tokens, previous_logical)
if docstring:
if '\n' not in docstring:
# not a multi line docstring
| python | {
"resource": ""
} |
q12635 | is_docstring | train | def is_docstring(tokens, previous_logical):
"""Return found docstring
'A docstring is a string literal that occurs as the first statement in a
module, function, class,'
http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
"""
for token_type, text, start, _, _ in tokens:
if token_type == tokenize.STRING:
break
elif token_type != tokenize.INDENT:
return False
else:
return False
| python | {
"resource": ""
} |
q12636 | _find_first_of | train | def _find_first_of(line, substrings):
"""Find earliest occurrence of one of substrings in line.
Returns pair of index and found substring, or (-1, None)
if no | python | {
"resource": ""
} |
q12637 | check_i18n | train | def check_i18n():
"""Generator that checks token stream for localization errors.
Expects tokens to be ``send``ed one by one.
Raises LocalizationError if some error is found.
"""
while True:
try:
token_type, text, _, _, line = yield
except GeneratorExit:
return
if text == "def" and token_type == tokenize.NAME:
# explicitly ignore function definitions, as oslo defines these
return
if (token_type == tokenize.NAME and
text in ["_", "_LI", "_LW", "_LE", "_LC"]):
while True:
token_type, text, start, _, _ = yield
if token_type != tokenize.NL:
break
if token_type != tokenize.OP or text != "(":
continue # not a localization call
format_string = ''
while True:
token_type, text, start, _, _ = yield
if token_type == tokenize.STRING:
format_string += eval(text)
elif token_type == tokenize.NL:
pass
else:
break
if not format_string:
raise LocalizationError(
start, "H701: Empty localization string")
if token_type != tokenize.OP:
raise LocalizationError(
start, "H701: Invalid localization call")
if text != ")":
if text == "%":
raise LocalizationError(
| python | {
"resource": ""
} |
q12638 | hacking_localization_strings | train | def hacking_localization_strings(logical_line, tokens, noqa):
r"""Check localization in line.
Okay: _("This is fine")
Okay: _LI("This is fine")
Okay: _LW("This is fine")
Okay: _LE("This is fine")
Okay: _LC("This is fine")
Okay: _("This is also fine %s")
Okay: _("So is this %s, %(foo)s") % {foo: 'foo'}
H701: _('')
Okay: def _(msg):\n pass
Okay: def _LE(msg):\n pass
H701: _LI('')
H701: _LW('')
H701: _LE('')
H701: _LC('')
Okay: _('') # noqa
H702: _("Bob" + " foo")
H702: _LI("Bob" + " foo")
H702: _LW("Bob" + " foo")
H702: _LE("Bob" + " foo")
H702: _LC("Bob" + " foo")
Okay: _("Bob" | python | {
"resource": ""
} |
q12639 | is_none | train | def is_none(node):
'''Check whether an AST node corresponds to None.
In Python 2 None uses the same ast.Name class that variables etc. use,
| python | {
"resource": ""
} |
q12640 | hacking_assert_equal | train | def hacking_assert_equal(logical_line, noqa):
r"""Check that self.assertEqual and self.assertNotEqual are used.
Okay: self.assertEqual(x, y)
Okay: self.assertNotEqual(x, y)
H204: self.assertTrue(x == y)
H204: self.assertTrue(x != y)
H204: self.assertFalse(x == y)
H204: self.assertFalse(x != y)
"""
if noqa:
return
methods = ['assertTrue', 'assertFalse']
for method in methods:
start = logical_line.find('.%s' % method) + 1
if start != 0:
| python | {
"resource": ""
} |
q12641 | hacking_no_cr | train | def hacking_no_cr(physical_line):
r"""Check that we only use newlines not carriage returns.
Okay: import os\nimport sys
# pep8 doesn't yet replace \r in strings, will work | python | {
"resource": ""
} |
q12642 | PaginatedDatasetResults.count | train | def count(self, count):
"""
Sets the count of this PaginatedDatasetResults.
:param count: The count of this PaginatedDatasetResults.
:type: int
"""
if count is None:
raise ValueError("Invalid value for `count`, must not be `None`")
| python | {
"resource": ""
} |
q12643 | WebAuthorization.type | train | def type(self, type):
"""
Sets the type of this WebAuthorization.
The authorization scheme. Usually this is \"Bearer\" but it could be other values like \"Token\" or \"Basic\" etc.
:param type: The type of this WebAuthorization.
:type: str
"""
if type is None:
| python | {
"resource": ""
} |
q12644 | LocalDataset.describe | train | def describe(self, resource=None):
"""Describe dataset or resource within dataset
:param resource: The name of a specific resource (i.e. file or table)
contained in the dataset. If ``resource`` is None, this method
will describe the dataset itself. (Default value = None)
:type resource: str, optional
:returns: The descriptor of the dataset or of a specific resource, if
``resource`` is specified in the call.
:rtype: dict
"""
if resource is None:
# Show simpler | python | {
"resource": ""
} |
q12645 | LocalDataset._load_raw_data | train | def _load_raw_data(self, resource_name):
"""Extract raw data from resource
:param resource_name:
"""
# Instantiating the resource again as a simple `Resource` ensures that
# ``data`` will be returned as bytes.
upcast_resource = datapackage.Resource(
| python | {
"resource": ""
} |
q12646 | LocalDataset._load_table | train | def _load_table(self, resource_name):
"""Build table structure from resource data
:param resource_name:
"""
tabular_resource = self.__tabular_resources[resource_name]
try:
# Sorting fields in the same order as they appear in the schema
# is necessary for tables to be converted into pandas.DataFrame
fields = []
if 'schema' in tabular_resource.descriptor:
fields = [f['name'] for f in
tabular_resource.descriptor['schema']['fields']]
elif len(tabular_resource.data) > 0:
fields = tabular_resource.data[0].keys()
return [order_columns_in_row(fields, row) for row in
tabular_resource.data]
except (SchemaValidationError, ValueError, TypeError) as e:
warnings.warn(
'Unable to set column types automatically using {} schema. '
'Data types may need to be adjusted manually. '
| python | {
"resource": ""
} |
q12647 | LocalDataset._load_dataframe | train | def _load_dataframe(self, resource_name):
"""Build pandas.DataFrame from resource data
Lazy load any optional dependencies in order to allow users to
use package without installing pandas if so they wish.
:param resource_name:
"""
try:
import pandas
except ImportError:
raise RuntimeError('To enable dataframe support, '
'run \'pip install datadotworld[pandas]\'')
tabular_resource = self.__tabular_resources[resource_name]
field_dtypes = fields_to_dtypes(tabular_resource.descriptor['schema'])
try:
return pandas.read_csv(
path.join(
self.__base_path,
tabular_resource.descriptor['path']),
dtype=field_dtypes['other'],
parse_dates=list(field_dtypes['dates'].keys()),
infer_datetime_format=True)
| python | {
"resource": ""
} |
q12648 | DatasetPatchRequest.visibility | train | def visibility(self, visibility):
"""
Sets the visibility of this DatasetPatchRequest.
Dataset visibility. `OPEN` if the dataset can be seen by any member of data.world. `PRIVATE` if the dataset can be seen by its owner and authorized collaborators.
| python | {
"resource": ""
} |
q12649 | ProjectPutRequest.objective | train | def objective(self, objective):
"""
Sets the objective of this ProjectPutRequest.
Short project objective.
:param objective: The objective of this ProjectPutRequest.
:type: str
"""
if objective is not None and len(objective) > 120:
raise ValueError("Invalid value for `objective`, length must be less than or equal to `120`")
| python | {
"resource": ""
} |
q12650 | QueryResults.table | train | def table(self):
"""Build and cache a table from query results"""
if self._table is None:
| python | {
"resource": ""
} |
q12651 | QueryResults.dataframe | train | def dataframe(self):
"""Build and cache a dataframe from query results"""
if self._dataframe is None:
try:
import pandas as pd
except ImportError:
| python | {
"resource": ""
} |
q12652 | fields_to_dtypes | train | def fields_to_dtypes(schema):
"""Maps table schema fields types to dtypes separating date fields
:param schema:
"""
datetime_types = ['date', 'datetime']
datetime_fields = {
f['name']: _TABLE_SCHEMA_DTYPE_MAPPING.get(f['type'], 'object')
for f in schema['fields']
if f['type'] in datetime_types}
other_fields = {
| python | {
"resource": ""
} |
q12653 | sanitize_resource_schema | train | def sanitize_resource_schema(r):
"""Sanitize table schema for increased compatibility
Up to version 0.9.0 jsontableschema did not support
year, yearmonth and duration field types
https://github.com/frictionlessdata/jsontableschema-py/pull/152
:param r:
| python | {
"resource": ""
} |
q12654 | infer_table_schema | train | def infer_table_schema(sparql_results_json):
"""Infer Table Schema from SPARQL results JSON
SPARQL JSON Results Spec:
https://www.w3.org/TR/2013/REC-sparql11-results-json-20130321
:param sparql_results_json: SPARQL JSON results of a query
:returns: A schema descriptor for the inferred schema
:rtype: dict (json)
"""
if ('results' in sparql_results_json and
'bindings' in sparql_results_json['results'] and
len(sparql_results_json['results']['bindings']) > 0):
# SQL results include metadata, SPARQL results don't
result_metadata = sparql_results_json.get('metadata', [])
metadata_names = [item['name'] for item in result_metadata]
result_vars = sparql_results_json['head']['vars']
_verify_unique_names(result_vars, metadata_names)
# SQL results require var name mapping, SPARQL results vars don't
result_vars_mapping = dict(zip(
result_vars, (metadata_names
if metadata_names != []
else result_vars)))
homogeneous_types = _get_types_from_sample(
result_vars, sparql_results_json)
fields = []
if homogeneous_types is None:
for result_var in result_vars:
fields.append({
'name': result_vars_mapping.get(result_var),
'type': 'string'
})
else:
for index, var in enumerate(result_vars):
field = {
'name': result_vars_mapping.get(var),
'type': infer_table_schema_type_from_rdf_term(
| python | {
"resource": ""
} |
q12655 | order_columns_in_row | train | def order_columns_in_row(fields, unordered_row):
"""Ensure columns appear in the same order for every row in table
:param fields:
:param unordered_row:
"""
fields_idx = {f: | python | {
"resource": ""
} |
q12656 | _get_types_from_sample | train | def _get_types_from_sample(result_vars, sparql_results_json):
"""Return types if homogenous within sample
Compare up to 10 rows of results to determine homogeneity.
DESCRIBE and CONSTRUCT queries, for example,
:param result_vars:
:param sparql_results_json:
"""
total_bindings = len(sparql_results_json['results']['bindings'])
homogeneous_types = {}
for result_var in result_vars:
var_types = set()
var_datatypes = set()
for i in range(0, min(total_bindings, 10)):
binding = sparql_results_json['results']['bindings'][i]
rdf_term = binding.get(result_var)
if rdf_term is not None: # skip missing values
| python | {
"resource": ""
} |
q12657 | FileConfig.save | train | def save(self):
"""Persist config changes"""
with open(self._config_file_path, 'w') as | python | {
"resource": ""
} |
q12658 | ChainedConfig._first_not_none | train | def _first_not_none(seq, supplier_func):
"""Applies supplier_func to each element in seq, returns 1st not None
:param seq: Sequence of object
:type seq: iterable
:param supplier_func: Function that extracts the desired value from
elements in seq
| python | {
"resource": ""
} |
q12659 | cli | train | def cli(ctx, profile):
"""dw commands support working with multiple data.world accounts
\b
Use a different <profile> value for each account.
In the absence of a <profile>, 'default' will be used. | python | {
"resource": ""
} |
q12660 | configure | train | def configure(obj, token):
"""Use this command to configure API tokens
"""
config = | python | {
"resource": ""
} |
q12661 | FileSourceCreateOrUpdateRequest.request_entity | train | def request_entity(self, request_entity):
"""
Sets the request_entity of this FileSourceCreateOrUpdateRequest.
:param request_entity: The request_entity of this FileSourceCreateOrUpdateRequest.
:type: str
"""
if request_entity is not None and len(request_entity) > 10000: | python | {
"resource": ""
} |
q12662 | InsightPutRequest.title | train | def title(self, title):
"""
Sets the title of this InsightPutRequest.
Insight title.
:param title: The title of this InsightPutRequest.
:type: str
"""
if title is None:
raise ValueError("Invalid value for `title`, must not be `None`")
if title is not None and len(title) > 128:
| python | {
"resource": ""
} |
q12663 | RestApiClient.get_dataset | train | def get_dataset(self, dataset_key):
"""Retrieve an existing dataset definition
This method retrieves metadata about an existing
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:returns: Dataset definition, with all attributes
:rtype: dict
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> intro_dataset = api_client.get_dataset(
... 'jonloyens/an-intro-to-dataworld-dataset') # | python | {
"resource": ""
} |
q12664 | RestApiClient.create_dataset | train | def create_dataset(self, owner_id, **kwargs):
"""Create a new dataset
:param owner_id: Username of the owner of the new dataset
:type owner_id: str
:param title: Dataset title (will be used to generate dataset id on
creation)
:type title: str
:param description: Dataset description
:type description: str, optional
:param summary: Dataset summary markdown
:type summary: str, optional
:param tags: Dataset tags
:type tags: list, optional
:param license: Dataset license
:type license: {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',
'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}
:param visibility: Dataset visibility
:type visibility: {'OPEN', 'PRIVATE'}
:param files: File name as dict, source URLs, description and labels()
as properties
:type files: dict, optional
*Description and labels are optional*
:returns: Newly created dataset key
:rtype: str
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> url = 'http://www.acme.inc/example.csv'
>>> api_client.create_dataset(
... 'username', title='Test dataset', visibility='PRIVATE',
... license='Public Domain',
| python | {
"resource": ""
} |
q12665 | RestApiClient.replace_dataset | train | def replace_dataset(self, dataset_key, **kwargs):
"""Replace an existing dataset
*This method will completely overwrite an existing dataset.*
:param description: Dataset description
:type description: str, optional
:param summary: Dataset summary markdown
:type summary: str, optional
:param tags: Dataset tags
:type tags: list, optional
:param license: Dataset license
:type license: {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',
'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}
:param visibility: Dataset visibility
:type visibility: {'OPEN', 'PRIVATE'}
:param files: File names and source URLs to add or update
:type files: dict, optional
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.replace_dataset(
... 'username/test-dataset',
... visibility='PRIVATE', license='Public Domain',
... description='A better description') # doctest: +SKIP
"""
| python | {
"resource": ""
} |
q12666 | RestApiClient.delete_dataset | train | def delete_dataset(self, dataset_key):
"""Deletes a dataset and all associated data
:params dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:raises RestApiException: If a server error occurs
Examples
--------
| python | {
"resource": ""
} |
q12667 | RestApiClient.add_files_via_url | train | def add_files_via_url(self, dataset_key, files={}):
"""Add or update dataset files linked to source URLs
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param files: Dict containing the name of files and metadata
Uses file name as a dict containing File description, labels and
source URLs to add or update (Default value = {})
*description and labels are optional.*
:type files: dict
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> url = 'http://www.acme.inc/example.csv'
>>> api_client = dw.api_client()
>>> api_client.add_files_via_url(
... 'username/test-dataset',
... {'example.csv': {
... 'url': url,
... 'labels': ['raw data'],
... 'description': 'file description'}}) # doctest: +SKIP
"""
file_requests = [_swagger.FileCreateOrUpdateRequest(
name=file_name,
| python | {
"resource": ""
} |
q12668 | RestApiClient.sync_files | train | def sync_files(self, dataset_key):
"""Trigger synchronization process to update all dataset files linked to
source URLs.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as | python | {
"resource": ""
} |
q12669 | RestApiClient.upload_files | train | def upload_files(self, dataset_key, files, files_metadata={}, **kwargs):
"""Upload dataset files
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param files: The list of names/paths for files stored in the
local filesystem
:type files: list of str
:param expand_archives: Boolean value to indicate files should be
expanded upon upload
:type expand_archive: bool optional
:param files_metadata: Dict containing the name of files and metadata
Uses file name as a dict containing File description, | python | {
"resource": ""
} |
q12670 | RestApiClient.upload_file | train | def upload_file(self, dataset_key, name, file_metadata={}, **kwargs):
"""Upload one file to a dataset
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param name: Name/path for files stored in the local filesystem
:type name: str
:param expand_archives: Boolean value to indicate files should be
expanded upon upload
:type expand_archive: bool optional
:param files_metadata: Dict containing the name of files and metadata
Uses file | python | {
"resource": ""
} |
q12671 | RestApiClient.download_datapackage | train | def download_datapackage(self, dataset_key, dest_dir):
"""Download and unzip a dataset's datapackage
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param dest_dir: Directory under which datapackage should be saved
:type dest_dir: str or path
:returns: Location of the datapackage descriptor (datapackage.json) in
the local filesystem
:rtype: path
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> datapackage_descriptor = api_client.download_datapackage(
... 'jonloyens/an-intro-to-dataworld-dataset',
... '/tmp/test') # doctest: +SKIP
>>> datapackage_descriptor # doctest: +SKIP
'/tmp/test/datapackage.json'
"""
if path.isdir(dest_dir):
raise ValueError('dest_dir must be a new directory, '
'but {} already exists'.format(dest_dir))
owner_id, dataset_id = parse_dataset_key(dataset_key)
url = "{0}://{1}/datapackage/{2}/{3}".format(
self._protocol, self._download_host, owner_id, dataset_id)
headers = {
'User-Agent': _user_agent(),
'Authorization': 'Bearer {0}'.format(self._config.auth_token)
}
try:
response = | python | {
"resource": ""
} |
q12672 | RestApiClient.get_user_data | train | def get_user_data(self):
"""Retrieve data for authenticated user
:returns: User data, with all attributes
:rtype: dict
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> user_data = api_client.get_user_data() # doctest: +SKIP
| python | {
"resource": ""
} |
q12673 | RestApiClient.fetch_contributing_projects | train | def fetch_contributing_projects(self, **kwargs):
"""Fetch projects that the currently authenticated user has access to
:returns: Authenticated user projects
:rtype: dict
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> user_projects =
... | python | {
"resource": ""
} |
q12674 | RestApiClient.sql | train | def sql(self, dataset_key, query, desired_mimetype='application/json',
**kwargs):
"""Executes SQL queries against a dataset via POST
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param query: SQL query
:type query: str
:param include_table_schema: Flags indicating to include table schema
in the response
:type include_table_schema: bool
:returns: file object that can be used in file parsers and
data handling modules.
:rtype: file-like object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
| python | {
"resource": ""
} |
q12675 | RestApiClient.sparql | train | def sparql(self, dataset_key, query,
desired_mimetype='application/sparql-results+json', **kwargs):
"""Executes SPARQL queries against a dataset via POST
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param query: SPARQL query
:type query: str
:returns: file object that can be used in file parsers and
data handling modules.
:rtype: file object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.sparql_post('username/test-dataset',
... query) # doctest: +SKIP
| python | {
"resource": ""
} |
q12676 | RestApiClient.download_dataset | train | def download_dataset(self, dataset_key):
"""Return a .zip containing all files within the dataset as uploaded.
:param dataset_key : Dataset identifier, in the form of owner/id
:type dataset_key: str
:returns: .zip file contain files within dataset
:rtype: file object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.download_dataset(
... 'username/test-dataset') | python | {
"resource": ""
} |
q12677 | RestApiClient.append_records | train | def append_records(self, dataset_key, stream_id, body):
"""Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:param body: Object body
:type body: obj
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.append_records('username/test-dataset','streamId',
... {'content':'content'}) # doctest: +SKIP | python | {
"resource": ""
} |
q12678 | RestApiClient.get_project | train | def get_project(self, project_key):
"""Retrieve an existing project
This method retrieves metadata about an existing project
:param project_key: Project identifier, in the form of owner/id
:type project_key: str
:returns: Project definition, with all attributes
:rtype: dict
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> intro_project = api_client.get_project(
... 'jonloyens/'
... 'an-example-project-that-shows-what-to-put-in-data-world'
... ) # doctest: +SKIP
| python | {
"resource": ""
} |
q12679 | RestApiClient.update_project | train | def update_project(self, project_key, **kwargs):
"""Update an existing project
:param project_key: Username and unique identifier of the creator of a
project in the form of owner/id.
:type project_key: str
:param title: Project title
:type title: str
:param objective: Short project objective.
:type objective: str, optional
:param summary: Long-form project summary.
:type summary: str, optional
:param tags: Project tags. Letters numbers and spaces
:type tags: list, optional
:param license: Project license
:type license: {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',
'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}
:param visibility: Project visibility
:type visibility: {'OPEN', 'PRIVATE'}
:param files: File name as dict, source URLs, description and labels()
as properties
:type files: dict, optional
*Description and labels are optional*
:param linked_datasets: Initial set of linked datasets.
:type linked_datasets: list of object, optional
:returns: message object
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
| python | {
"resource": ""
} |
q12680 | RestApiClient.replace_project | train | def replace_project(self, project_key, **kwargs):
"""Replace an existing Project
*Create a project with a given id or completely rewrite the project,
including any previously added files or linked datasets, if one already
exists with the given id.*
:param project_key: Username and unique identifier of the creator of a
project in the form of owner/id.
:type project_key: str
:param title: Project title
:type title: str
:param objective: Short project objective.
:type objective: str, optional
:param summary: Long-form project summary.
:type summary: str, optional
:param tags: Project tags. Letters numbers and spaces
:type tags: list, optional
:param license: Project license
:type license: {'Public Domain', 'PDDL', 'CC-0', 'CC-BY', 'ODC-BY',
'CC-BY-SA', 'ODC-ODbL', 'CC BY-NC', 'CC BY-NC-SA', 'Other'}
:param visibility: Project visibility
:type visibility: {'OPEN', 'PRIVATE'}
:param files: File name as dict, source URLs, description and labels()
as properties
:type files: dict, optional
*Description and labels are optional*
:param linked_datasets: Initial set of linked datasets.
:type linked_datasets: list of object, optional
:returns: project object
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw | python | {
"resource": ""
} |
q12681 | RestApiClient.add_linked_dataset | train | def add_linked_dataset(self, project_key, dataset_key):
"""Link project to an existing dataset
This method links a dataset to project
:param project_key: Project identifier, in the form of owner/id
:type project_key: str
:param dataset_key: Dataset identifier, in the form of owner/id
:type project_key: str
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> linked_dataset = api_client.add_linked_dataset(
... 'username/test-project',
... 'username/test-dataset') # doctest: +SKIP
"""
| python | {
"resource": ""
} |
q12682 | RestApiClient.get_insight | train | def get_insight(self, project_key, insight_id, **kwargs):
"""Retrieve an insight
:param project_key: Project identifier, in the form of
projectOwner/projectid
:type project_key: str
:param insight_id: Insight unique identifier.
:type insight_id: str
:returns: Insight definition, with all attributes
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> insight = api_client.get_insight(
... 'jonloyens/'
... 'an-example-project-that-shows-what-to-put-in-data-world',
... 'c2538b0c-c200-474c-9631-5ff4f13026eb') # doctest: +SKIP
>>> insight['title'] # doctest: | python | {
"resource": ""
} |
q12683 | RestApiClient.get_insights_for_project | train | def get_insights_for_project(self, project_key, **kwargs):
"""Get insights for a project.
:param project_key: Project identifier, in the form of
projectOwner/projectid
:type project_key: str
:returns: Insight results
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> insights = api_client.get_insights_for_project(
... 'jonloyens/'
... 'an-example-project-that-shows-what-to-put-in-data-world'
... ) # doctest: +SKIP
"""
| python | {
"resource": ""
} |
q12684 | RestApiClient.create_insight | train | def create_insight(self, project_key, **kwargs):
"""Create a new insight
:param project_key: Project identifier, in the form of
projectOwner/projectid
:type project_key: str
:param title: Insight title
:type title: str
:param description: Insight description.
:type description: str, optional
:param image_url: If image-based, the URL of the image
:type image_url: str
:param embed_url: If embed-based, the embeddable URL
:type embed_url: str
:param source_link: Permalink to source code or platform this insight
was generated with. Allows others to replicate the steps originally
used to produce the insight.
:type source_link: str, optional
:param data_source_links: One or more permalinks to the data sources
used to generate this insight. Allows others to access the data
originally used to produce the insight.
:type data_source_links: array
:returns: Insight with message and uri object
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.create_insight(
... 'projectOwner/projectid', title='Test insight',
... | python | {
"resource": ""
} |
q12685 | RestApiClient.replace_insight | train | def replace_insight(self, project_key, insight_id, **kwargs):
"""Replace an insight.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
:type project_key: str
:param insight_id: Insight unique identifier.
:type insight_id: str
:param title: Insight title
:type title: str
:param description: Insight description.
:type description: str, optional
:param image_url: If image-based, the URL of the image
:type image_url: str
:param embed_url: If embed-based, the embeddable URL
:type embed_url: str
:param source_link: Permalink to source code or platform this insight
was generated with. Allows others to replicate the steps originally
used to produce the insight.
:type source_link: str, optional
:param data_source_links: One or more permalinks to the data sources
used to generate this insight. Allows others to access the data
originally used to produce the insight.
:type data_source_links: array
:returns: message object
:rtype: object
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> api_client.replace_insight(
... 'projectOwner/projectid',
| python | {
"resource": ""
} |
q12686 | RestApiClient.update_insight | train | def update_insight(self, project_key, insight_id, **kwargs):
"""Update an insight.
**Note that only elements included in the request will be updated. All
omitted elements will remain untouched.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
:type project_key: str
:param insight_id: Insight unique identifier.
:type insight_id: str
:param title: Insight title
:type title: str
:param description: Insight description.
:type description: str, optional
:param image_url: If image-based, the URL of the image
:type image_url: str
:param embed_url: If embed-based, the embeddable URL
:type embed_url: str
:param source_link: Permalink to source code or platform this insight
was generated with. Allows others to replicate the steps originally
used to produce the insight.
:type source_link: str, optional
:param data_source_links: One or more permalinks to the data sources
used to generate this insight. Allows others to access the data
originally used to produce the insight.
:type data_source_links: array
:returns: message object
:rtype: object
:raises RestApiException: If a server error occurs
| python | {
"resource": ""
} |
q12687 | RestApiClient.delete_insight | train | def delete_insight(self, project_key, insight_id):
"""Delete an existing insight.
:params project_key: Project identifier, in the form of
projectOwner/projectId
:type project_key: str
:params insight_id: Insight unique id
:type insight_id: str
:raises RestApiException: If a server error occurs
Examples
--------
>>> import datadotworld as dw
>>> api_client = dw.api_client()
>>> del_insight = api_client.delete_insight(
... 'username/project', 'insightid') # doctest: +SKIP
"""
| python | {
"resource": ""
} |
q12688 | parse_dataset_key | train | def parse_dataset_key(dataset_key):
"""Parse a dataset URL or path and return the owner and the dataset id
:param dataset_key: Dataset key (in the form of owner/id) or dataset URL
:type dataset_key: str
:returns: User name of the dataset owner and ID of the dataset
:rtype: dataset_owner, dataset_id
:raises ValueError: If the provided key does comply to the expected pattern
Examples
--------
>>> from datadotworld import util
>>> util.parse_dataset_key(
... 'https://data.world/jonloyens/an-intro-to-datadotworld-dataset')
('jonloyens', 'an-intro-to-datadotworld-dataset') | python | {
"resource": ""
} |
q12689 | LazyLoadedDict.from_keys | train | def from_keys(cls, keys, loader_func, type_hint=None):
"""Factory method for `LazyLoadedDict`
Accepts a ``loader_func`` that is to be applied to all ``keys``.
:param keys: List of keys to create the dictionary with
:type keys: iterable
:param loader_func: Function to be applied to | python | {
"resource": ""
} |
q12690 | FileCreateOrUpdateRequest.name | train | def name(self, name):
"""
Sets the name of this FileCreateOrUpdateRequest.
File name. Should include type extension always when possible. Must not include slashes.
:param name: The name of this FileCreateOrUpdateRequest.
:type: str
"""
if name is None:
raise ValueError("Invalid value for `name`, must not be `None`")
if name is not None and len(name) > 128:
raise ValueError("Invalid value for `name`, length must be less than or equal to `128`")
if name is not None and len(name) < 1:
| python | {
"resource": ""
} |
q12691 | FileCreateOrUpdateRequest.labels | train | def labels(self, labels):
"""
Sets the labels of this FileCreateOrUpdateRequest.
File labels.
:param labels: The labels of this FileCreateOrUpdateRequest.
:type: list[str]
"""
allowed_values = ["raw data", "documentation", "visualization", "clean data", "script", "report"]
if not set(labels).issubset(set(allowed_values)):
raise ValueError(
| python | {
"resource": ""
} |
q12692 | WebCredentials.user | train | def user(self, user):
"""
Sets the user of this WebCredentials.
The name of the account to login to.
:param user: The user of this WebCredentials.
:type: str
"""
if user is None:
raise ValueError("Invalid value | python | {
"resource": ""
} |
q12693 | OauthTokenReference.owner | train | def owner(self, owner):
"""
Sets the owner of this OauthTokenReference.
User name of the owner of the OAuth token within data.world.
:param owner: The owner of this OauthTokenReference.
:type: str
"""
if owner is None:
raise ValueError("Invalid value for `owner`, must not be `None`")
if owner is not None and len(owner) > 31:
raise ValueError("Invalid value for `owner`, length must be less than or equal to `31`")
if owner is not None and len(owner) < 3:
raise ValueError("Invalid value for `owner`, length must be greater than or | python | {
"resource": ""
} |
q12694 | OauthTokenReference.site | train | def site(self, site):
"""
Sets the site of this OauthTokenReference.
:param site: The site of this OauthTokenReference.
:type: str
"""
if site is None:
raise ValueError("Invalid value for `site`, must not be `None`")
if site is not None and len(site) > 255:
raise ValueError("Invalid value for `site`, length must be less than | python | {
"resource": ""
} |
q12695 | FileSourceCreateRequest.url | train | def url(self, url):
"""
Sets the url of this FileSourceCreateRequest.
Source URL of file. Must be an http, https.
:param url: The url of this FileSourceCreateRequest.
:type: str
"""
if url is None:
raise ValueError("Invalid value for `url`, must not be `None`")
if url is not None and len(url) > 4096:
raise ValueError("Invalid value for `url`, length must be less than or equal to `4096`")
if url is not None and len(url) < 1:
raise | python | {
"resource": ""
} |
q12696 | LinkedDatasetCreateOrUpdateRequest.owner | train | def owner(self, owner):
"""
Sets the owner of this LinkedDatasetCreateOrUpdateRequest.
User name and unique identifier of the creator of the dataset.
:param owner: The owner of this LinkedDatasetCreateOrUpdateRequest.
:type: str
"""
if owner is None:
raise | python | {
"resource": ""
} |
q12697 | RemoteFile.read | train | def read(self):
"""read the contents of the file that's been opened in read mode"""
if 'r' == self._mode:
| python | {
"resource": ""
} |
q12698 | RemoteFile._open_for_read | train | def _open_for_read(self):
"""open the file in read mode"""
ownerid, datasetid = parse_dataset_key(self._dataset_key)
response = requests.get(
'{}/file_download/{}/{}/{}'.format(
self._query_host, ownerid, datasetid, self._file_name),
| python | {
"resource": ""
} |
q12699 | RemoteFile._open_for_write | train | def _open_for_write(self):
"""open the file in write mode"""
def put_request(body):
"""
:param body:
"""
ownerid, datasetid = parse_dataset_key(self._dataset_key)
response = requests.put(
"{}/uploads/{}/{}/files/{}".format(
self._api_host, ownerid, datasetid, self._file_name),
data=body,
headers={
'User-Agent': self._user_agent,
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.