Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,100 | def create_order(self, order):
"""
See more:
http://developer.oanda.com/rest-live/orders/#createNewOrder
"""
url = "{0}/{1}/accounts/{2}/orders".format(
self.domain,
self.API_VERSION,
self.account_id
)
try:
r... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.create_order |
2,101 | def update_order(self, order_id, order):
"""
See more:
http://developer.oanda.com/rest-live/orders/#modifyExistingOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
orde... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.update_order |
2,102 | def close_order(self, order_id):
"""
See more:
http://developer.oanda.com/rest-live/orders/#closeOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
order_id
)
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.close_order |
2,103 | def get_trades(self, max_id=None, count=None, instrument=None, ids=None):
""" Get a list of open trades
Parameters
----------
max_id : int
The server will return trades with id less than or equal
to this, in descending order (for pagination)
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_trades |
2,104 | def get_trade(self, trade_id):
""" Get information on a specific trade.
Parameters
----------
trade_id : int
The id of the trade to get information on.
See more:
http://developer.oanda.com/rest-live/trades/#getInformationSpecificTrade... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_trade |
2,105 | def update_trade(
self,
trade_id,
stop_loss=None,
take_profit=None,
trailing_stop=None
):
""" Modify an existing trade.
Note: Only the specified parameters will be modified. All
other parameters will remain unchanged. To remove an
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.update_trade |
2,106 | def close_trade(self, trade_id):
""" Close an open trade.
Parameters
----------
trade_id : int
The id of the trade to close.
See more:
http://developer.oanda.com/rest-live/trades/#closeOpenTrade
"""
url = "{0}/{1}/acco... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.close_trade |
2,107 | def get_positions(self):
""" Get a list of all open positions.
See more:
http://developer.oanda.com/rest-live/positions/#getListAllOpenPositions
"""
url = "{0}/{1}/accounts/{2}/positions".format(
self.domain,
self.API_VERSION,
self.acc... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_positions |
2,108 | def get_position(self, instrument):
""" Get the position for an instrument.
Parameters
----------
instrument : string
The instrument to get the open position for.
See more:
http://developer.oanda.com/rest-live/positions/#getPositionFo... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_position |
2,109 | def close_position(self, instrument):
""" Close an existing position
Parameters
----------
instrument : string
The instrument to close the position for.
See more:
http://developer.oanda.com/rest-live/positions/#closeExistingPosition
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.close_position |
2,110 | def get_transactions(
self,
max_id=None,
count=None,
instrument="all",
ids=None
):
""" Get a list of transactions.
Parameters
----------
max_id : int
The server will return transactions with id less than or
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_transactions |
2,111 | def get_transaction(self, transaction_id):
""" Get information on a specific transaction.
Parameters
----------
transaction_id : int
The id of the transaction to get information on.
See more:
http://developer.oanda.com/rest-live/trans... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_transaction |
2,112 | def request_transaction_history(self):
""" Request full account history.
Submit a request for a full transaction history. A
successfully accepted submission results in a response
containing a URL in the Location header to a file that will
be available once the r... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.request_transaction_history |
2,113 | def create_account(self, currency=None):
""" Create a new account.
This call is only available on the sandbox system. Please
create accounts on fxtrade.oanda.com on our production
system.
See more:
http://developer.oanda.com/rest-sandbox/accounts/#-a... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.create_account |
2,114 | def get_accounts(self, username=None):
""" Get a list of accounts owned by the user.
Parameters
----------
username : string
The name of the user. Note: This is only required on the
sandbox, on production systems your access token will
... | AssertionError | dataset/ETHPy150Open toloco/pyoanda/pyoanda/client.py/Client.get_accounts |
2,115 | @staticmethod
def draw_spectrum_analyzer(all_frames, thresh_frames):
time.sleep(1) # Wait just one second
pw = pg.plot(title="Spectrum Analyzer") # Window title
pg.setConfigOptions(antialias=True) # Enable antialias for better resolution
pw.win.resize(800, 300) # Define window size
pw.win.move(540 * SCREEN_W... | IndexError | dataset/ETHPy150Open mertyildiran/Cerebrum/cerebrum/hearing/perception.py/HearingPerception.draw_spectrum_analyzer |
2,116 | def _get_model_from_node(self, node, attr):
"""
Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.
"""
model_identifier = node.getAttribute(attr)
if not model_identifier:
raise base.DeserializationError(
"<%s>... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/serializers/xml_serializer.py/Deserializer._get_model_from_node |
2,117 | def __init__(self, name, variable, options=None):
self.name = name
self.variable = template.Variable(variable)
self.options = options or {}
for name, value in self.options.items():
try:
self.options[name] = ast.literal_eval(value)
except __HOLE__:... | ValueError | dataset/ETHPy150Open mher/chartkick.py/chartkick/templatetags/chartkick.py/ChartNode.__init__ |
2,118 | def chart(name, parser, token):
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
'%r statement requires at least one argument' %
token.split_contents()[0])
options = None
if len(args) > 2:
if args[2] != 'with':
... | ValueError | dataset/ETHPy150Open mher/chartkick.py/chartkick/templatetags/chartkick.py/chart |
2,119 | def autorun_commands(cmds,my_globals=None,verb=0):
sv = conf.verb
import builtins
try:
try:
if my_globals is None:
my_globals = __import__("scapy.all").all.__dict__
conf.verb = verb
interp = ScapyAutorunInterpreter(my_globals)
cmd = ""
... | SystemExit | dataset/ETHPy150Open phaethon/scapy/scapy/autorun.py/autorun_commands |
2,120 | def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any ... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/mac_shadow.py/_get_account_policy |
2,121 | def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return date... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/modules/mac_shadow.py/_convert_to_datetime |
2,122 | def info(name):
'''
Return information for the specified user
:param str name: the username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/mac_shadow.py/info |
2,123 | def get_minion_data(minion, opts):
'''
Get the grains/pillar for a specific minion. If minion is None, it
will return the grains/pillar for the first minion it finds.
Return value is a tuple of the minion ID, grains, and pillar
'''
if opts.get('minion_data_cache', False):
serial = salt... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/get_minion_data |
2,124 | def _check_glob_minions(self, expr, greedy): # pylint: disable=unused-argument
'''
Return the minions found by looking via globs
'''
pki_dir = os.path.join(self.opts['pki_dir'], self.acc)
try:
files = []
for fn_ in salt.utils.isorted(os.listdir(pki_dir)):... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions._check_glob_minions |
2,125 | def _check_pcre_minions(self, expr, greedy): # pylint: disable=unused-argument
'''
Return the minions found by looking via regular expressions
'''
try:
minions = []
for fn_ in salt.utils.isorted(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))):
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions._check_pcre_minions |
2,126 | def _check_ipcidr_minions(self, expr, greedy):
'''
Return the minions found by looking via ipcidr
'''
cache_enabled = self.opts.get('minion_data_cache', False)
if greedy:
mlist = []
for fn_ in salt.utils.isorted(os.listdir(os.path.join(self.opts['pki_dir'... | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions._check_ipcidr_minions |
2,127 | def connected_ids(self, subset=None, show_ipv4=False, include_localhost=False):
'''
Return a set of all connected minion ids, optionally within a subset
'''
minions = set()
if self.opts.get('minion_data_cache', False):
cdir = os.path.join(self.opts['cachedir'], 'minio... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions.connected_ids |
2,128 | def auth_check_expanded(self,
auth_list,
funs,
args,
tgt,
tgt_type='glob',
groups=None,
publish_validate=False):
# ... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions.auth_check_expanded |
2,129 | def auth_check(self,
auth_list,
funs,
args,
tgt,
tgt_type='glob',
groups=None,
publish_validate=False):
'''
Returns a bool which defines if the requested function is autho... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/minions.py/CkMinions.auth_check |
2,130 | def test_add_placeholder(self):
# create page
page = create_page("Add Placeholder", "nav_playground.html", "en",
position="last-child", published=True, in_navigation=True)
page.template = 'add_placeholder.html'
page.save()
page.publish('en')
url... | IndexError | dataset/ETHPy150Open divio/django-cms/cms/tests/test_page.py/PagesTestCase.test_add_placeholder |
2,131 | def test_slug_url_overwrite_clash(self):
""" Tests if a URL-Override clashes with a normal page url
"""
with self.settings(CMS_PERMISSION=False):
create_page('home', 'nav_playground.html', 'en', published=True)
bar = create_page('bar', 'nav_playground.html', 'en', publish... | ValidationError | dataset/ETHPy150Open divio/django-cms/cms/tests/test_page.py/PagesTestCase.test_slug_url_overwrite_clash |
2,132 | def check(fn):
try:
checker = KivyStyleChecker(fn)
except __HOLE__:
# File couldn't be opened, so was deleted apparently.
# Don't check deleted files.
return 0
return checker.check_all() | IOError | dataset/ETHPy150Open kivy/kivy/kivy/tools/pep8checker/pep8kivy.py/check |
2,133 | def hash_or_str(obj):
try:
return hash((type(obj).__name__, obj))
except __HOLE__:
## Adds the type name to make sure two object of different type but
## identical string representation get distinguished.
return type(obj).__name__ + str(obj)
##
## All purpose object
## | TypeError | dataset/ETHPy150Open vaab/colour/colour.py/hash_or_str |
2,134 | def __getattr__(self, label):
if label.startswith("get_"):
raise AttributeError("'%s' not found" % label)
try:
return getattr(self, 'get_' + label)()
except __HOLE__:
raise AttributeError("'%s' not found" % label) | AttributeError | dataset/ETHPy150Open vaab/colour/colour.py/Color.__getattr__ |
2,135 | def run(self, action='primary', force_update=False, kill_only=False):
'''
@action
One of: primary, secondary
'''
self.raise_event(self, EventSource.ON_DART_RUN)
try:
view = self.window.active_view()
except TypeError:
return
if ... | TypeError | dataset/ETHPy150Open guillermooo/dart-sublime-bundle/run.py/DartSmartRunCommand.run |
2,136 | def run(self, file_name=None, action='primary', kill_only=False):
'''
@action
One of: [primary, secondary]
@kill_only
If `True`, simply kill any running processes we've started.
'''
assert kill_only or file_name, 'wrong call'
self._cleanup()
... | TypeError | dataset/ETHPy150Open guillermooo/dart-sublime-bundle/run.py/DartRunFileCommand.run |
2,137 | def el_iter(el):
"""
Go through all elements
"""
try:
for child in el.iter():
yield child
except __HOLE__:
# iter isn't available in < python 2.7
for child in el.getiterator():
yield child | AttributeError | dataset/ETHPy150Open CenterForOpenScience/pydocx/pydocx/util/xml.py/el_iter |
2,138 | def findroot(ctx, f, x0, solver=Secant, tol=None, verbose=False, verify=True, **kwargs):
r"""
Find a solution to `f(x) = 0`, using *x0* as starting point or
interval for *x*.
Multidimensional overdetermined systems are supported.
You can specify them using a function or a list of functions.
If... | TypeError | dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/calculus/optimization.py/findroot |
2,139 | def _rm_containers(cids):
rm_containers(cids)
for c in cids:
try:
models.node.delete_eru_instance(c)
except __HOLE__ as e:
logging.exception(e) | ValueError | dataset/ETHPy150Open HunanTV/redis-ctl/daemonutils/auto_balance.py/_rm_containers |
2,140 | def dialogRssWatchDBextender(dialog, frame, row, options, cntlr, openFileImage, openDatabaseImage):
from tkinter import PhotoImage, N, S, E, W
from tkinter.simpledialog import askstring
from arelle.CntlrWinTooltip import ToolTip
from arelle.UiUtil import gridCell, label
try:
from tkinter.ttk... | ImportError | dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/xbrlDB/DialogRssWatchExtender.py/dialogRssWatchDBextender |
2,141 | @csrf_exempt_m
def ipn(self, request):
OGONE = settings.OGONE
try:
parameters_repr = repr(request.POST.copy()).encode('utf-8')
logger.info('IPN: Processing request data %s' % parameters_repr)
try:
orderID = request.POST['orderID']
... | KeyError | dataset/ETHPy150Open matthiask/plata/plata/payment/modules/ogone.py/PaymentProcessor.ipn |
2,142 | def _spawn_n_impl(self, func, args, kwargs, coro):
try:
try:
func(*args, **kwargs)
except (__HOLE__, SystemExit, greenlet.GreenletExit):
raise
except:
if DEBUG:
traceback.print_exc()
finally:
... | KeyboardInterrupt | dataset/ETHPy150Open veegee/guv/guv/greenpool.py/GreenPool._spawn_n_impl |
2,143 | def main():
current_dir = os.path.dirname(__file__)
app_name = os.path.basename(current_dir)
sys.path.insert(0, os.path.join(current_dir, '..'))
if not settings.configured:
settings.configure(
INSTALLED_APPS=('django.contrib.auth', 'django.contrib.contenttypes', app_name),
... | ImportError | dataset/ETHPy150Open idlesign/django-siteblocks/siteblocks/runtests.py/main |
2,144 | def _translate_floating_ip_view(floating_ip):
result = {
'id': floating_ip['id'],
'ip': floating_ip['address'],
'pool': floating_ip['pool'],
}
try:
result['fixed_ip'] = floating_ip['fixed_ip']['address']
except (TypeError, KeyError, AttributeError):
result['fixed_... | AttributeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/floating_ips.py/_translate_floating_ip_view |
2,145 | @extensions.expected_errors((400, 403, 404))
@wsgi.action('addFloatingIp')
@validation.schema(floating_ips.add_floating_ip)
def _add_floating_ip(self, req, id, body):
"""Associate floating_ip to an instance."""
context = req.environ['nova.context']
authorize(context)
address... | StopIteration | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/floating_ips.py/FloatingIPActionController._add_floating_ip |
2,146 | def _route_choices():
# Only type='3' for buses at the moment
ids = []
for route in Route.objects.filter(type='3').only('name'):
try:
name = int(route.name)
except __HOLE__:
name = route.name
ids.append(name)
return [(str(x), str(x)) for x in sorted(ids)] | ValueError | dataset/ETHPy150Open shaunduncan/breezeminder/breezeminder/forms/marta.py/_route_choices |
2,147 | def ensure_dir_notexists(path):
"""
helper function, removes dir if it exists
:returns: True if dir does not exist after this function
:raises: OSError if dir exists and removal failed for non-trivial reasons
"""
try:
if os.path.exists(path):
os.rmdir(path)
return Tr... | OSError | dataset/ETHPy150Open vcstools/vcstools/src/vcstools/common.py/ensure_dir_notexists |
2,148 | def urlopen_netrc(uri, *args, **kwargs):
'''
wrapper to urlopen, using netrc on 401 as fallback
Since this wraps both python2 and python3 urlopen, accepted arguments vary
:returns: file-like object as urllib.urlopen
:raises: IOError and urlopen errors
'''
try:
return urlopen(uri, *a... | IOError | dataset/ETHPy150Open vcstools/vcstools/src/vcstools/common.py/urlopen_netrc |
2,149 | def _netrc_open(uri, filename=None):
'''
open uri using netrc credentials.
:param uri: uri to open
:param filename: optional, path to non-default netrc config file
:returns: file-like object from opening a socket to uri, or None
:raises IOError: if opening .netrc file fails (unless file not fou... | IOError | dataset/ETHPy150Open vcstools/vcstools/src/vcstools/common.py/_netrc_open |
2,150 | def run_shell_command(cmd, cwd=None, shell=False, us_env=True,
show_stdout=False, verbose=False, timeout=None,
no_warn=False, no_filter=False):
"""
executes a command and hides the stdout output, loggs stderr
output when command result is not zero. Make sure to sa... | OSError | dataset/ETHPy150Open vcstools/vcstools/src/vcstools/common.py/run_shell_command |
2,151 | def list_or_args(keys, args):
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, basestring):
keys = [keys]
except __HOLE__:
keys = [keys]
if args... | TypeError | dataset/ETHPy150Open zhihu/redis-shard/redis_shard/shard.py/list_or_args |
2,152 | def __contains__(self, key):
try:
self[key]
except __HOLE__:
return False
return True | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/test/utils.py/ContextList.__contains__ |
2,153 | def setup_test_template_loader(templates_dict, use_cached_loader=False):
"""
Changes Django to only find templates from within a dictionary (where each
key is the template name and each value is the corresponding template
content to return).
Use meth:`restore_template_loaders` to restore the origin... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/test/utils.py/setup_test_template_loader |
2,154 | def _sso_location(self, entityid=None, binding=BINDING_HTTP_REDIRECT):
if entityid:
# verify that it's in the metadata
srvs = self.metadata.single_sign_on_service(entityid, binding)
if srvs:
return destinations(srvs)[0]
else:
logger... | IndexError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base._sso_location |
2,155 | def add_vo_information_about_user(self, name_id):
""" Add information to the knowledge I have about the user. This is
for Virtual organizations.
:param name_id: The subject identifier
:return: A possibly extended knowledge.
"""
ava = {}
try:
(ava, _)... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.add_vo_information_about_user |
2,156 | def create_authn_request(self, destination, vorg="", scoping=None,
binding=saml2.BINDING_HTTP_POST,
nameid_format=None,
service_url_binding=None, message_id=0,
consent=None, extensions=None, sign=None,
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.create_authn_request |
2,157 | def create_attribute_query(self, destination, name_id=None,
attribute=None, message_id=0, consent=None,
extensions=None, sign=False, sign_prepare=False,
**kwargs):
""" Constructs an AttributeQuery
:param destin... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.create_attribute_query |
2,158 | def parse_authn_request_response(self, xmlstr, binding, outstanding=None,
outstanding_certs=None):
""" Deal with an AuthnResponse
:param xmlstr: The reply as a xml string
:param binding: Which binding that was used for the transport
:param outstandin... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.parse_authn_request_response |
2,159 | def create_ecp_authn_request(self, entityid=None, relay_state="",
sign=False, **kwargs):
""" Makes an authentication request.
:param entityid: The entity ID of the IdP to send the request to
:param relay_state: A token that can be used by the SP to know
... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.create_ecp_authn_request |
2,160 | @staticmethod
def can_handle_ecp_response(response):
try:
accept = response.headers["accept"]
except KeyError:
try:
accept = response.headers["Accept"]
except __HOLE__:
return False
if MIME_PAOS in accept:
retur... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.can_handle_ecp_response |
2,161 | @staticmethod
def create_discovery_service_request(url, entity_id, **kwargs):
"""
Created the HTTP redirect URL needed to send the user to the
discovery service.
:param url: The URL of the discovery service
:param entity_id: The unique identifier of the service provider
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.create_discovery_service_request |
2,162 | @staticmethod
def parse_discovery_service_response(url="", query="",
returnIDParam="entityID"):
"""
Deal with the response url from a Discovery Service
:param url: the url the user was redirected back to or
:param query: just the query part o... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/client_base.py/Base.parse_discovery_service_response |
2,163 | def parseLine(self, line):
"""Override this.
By default, this will split the line on whitespace and call
self.parseFields (catching any errors).
"""
try:
self.parseFields(*line.split())
except __HOLE__:
raise InvalidInetdConfError, 'Invali... | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/runner/inetdconf.py/SimpleConfFile.parseLine |
2,164 | def choice(a, size=None, replace=True, p=None, random_state=None):
"""
choice(a, size=None, replace=True, p=None)
Generates a random sample from a given 1-D array
.. versionadded:: 1.7.0
Parameters
-----------
a : 1-D array-like or int
If an ndarray, a random sample is generated f... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/utils/random.py/choice |
2,165 | def main():
try:
command = COMMANDS.get(args.all.pop(0).lower(), usage)
except:
command = usage
# fallback to usage.
if command is usage:
return command()
# retrieve lang
try:
lang = args.grouped.get('lang', []).pop(0)
if lang not in LANGS:
... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/script/i18ntool.py/main |
2,166 | def initialiseShapeLearners(self):
self.shapeLearners_currentCollection = []
self.settings_shapeLearners_currentCollection = []
self.shapeLearnersSeenBefore_currentCollection = []
for i in range(len(self.currentCollection)):
shapeType = self.currentCollection[i]
... | ValueError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.initialiseShapeLearners |
2,167 | def indexOfShapeInCurrentCollection(self, shapeType):
try:
shapeType_index = self.currentCollection.index(shapeType)
except __HOLE__: #unknown shape
shapeType_index = -1
return shapeType_index | ValueError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.indexOfShapeInCurrentCollection |
2,168 | def indexOfShapeInAllShapesLearnt(self, shapeType):
try:
shapeType_index = self.shapesLearnt.index(shapeType)
except __HOLE__: #unknown shape
shapeType_index = -1
return shapeType_index | ValueError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.indexOfShapeInAllShapesLearnt |
2,169 | def shapeAtIndexInCurrentCollection(self, shapeType_index):
try:
shapeType = self.currentCollection[shapeType_index]
except __HOLE__: #unknown shape
shapeType = -1
return shapeType | ValueError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.shapeAtIndexInCurrentCollection |
2,170 | def shapeAtIndexInAllShapesLearnt(self, shapeType_index):
try:
shapeType = self.shapesLearnt[shapeType_index]
except __HOLE__: #unknown shape
shapeType = -1
return shapeType | ValueError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.shapeAtIndexInAllShapesLearnt |
2,171 | def newCollection(self, collection):
self.currentCollection = ""
# check, for each letter, that we have the corresponding dataset
for l in collection:
try:
self.generateSettings(l)
except __HOLE__:
# no dataset for this letter!
... | RuntimeError | dataset/ETHPy150Open chili-epfl/shape_learning/src/shape_learning/shape_learner_manager.py/ShapeLearnerManager.newCollection |
2,172 | def _get_win_folder_with_pywin32(csidl_name):
from win32com.shell import shellcon, shell
dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
# Try to make this a unicode path because SHGetFolderPath does
# not return unicode strings when there is unicode data in the
# path.
try:
... | ImportError | dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/utils/appdirs.py/_get_win_folder_with_pywin32 |
2,173 | def fsinit(self):
try:
NfSpy.fsinit(self)
except __HOLE__ as e:
raise fuse.FuseError, e.message | RuntimeError | dataset/ETHPy150Open bonsaiviking/NfSpy/nfspy/fusefs.py/NFSFuse.fsinit |
2,174 | def release(self):
"""Flush changes and release the configuration write lock. This instance must not be used anymore afterwards.
In Python 3, it's required to explicitly release locks and flush changes, as __del__ is not called
deterministically anymore."""
# checking for the lock here m... | IOError | dataset/ETHPy150Open gitpython-developers/GitPython/git/config.py/GitConfigParser.release |
2,175 | def read(self):
"""Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled"""
if self._is_initialized:
return
... | IOError | dataset/ETHPy150Open gitpython-developers/GitPython/git/config.py/GitConfigParser.read |
2,176 | def get_value(self, section, option, default=None):
"""
:param default:
If not None, the given default value will be returned in case
the option did not exist
:return: a properly typed value, either int, float or string
:raise TypeError: in case the value could n... | TypeError | dataset/ETHPy150Open gitpython-developers/GitPython/git/config.py/GitConfigParser.get_value |
2,177 | @click.command(help="Open a Python shell, bootstrapping the connection to MongoDB")
@click.option('--no-startup', is_flag=True)
def shell(no_startup=False):
"""
Open a Python shell, bootstrapping the connection to MongoDB
"""
# Set up a dictionary to serve as the environment for the shell, so
# that... | ImportError | dataset/ETHPy150Open openelections/openelections-core/openelex/tasks/shell.py/shell |
2,178 | @deferredAsThread
def _deserialize(self, fd):
while True:
try:
obj = Entity.deserialize(fd)
except EOFError:
fd.close()
break
except __HOLE__:
fd.close()
break | AttributeError | dataset/ETHPy150Open OrbitzWorldwide/droned/droned/lib/droned/clients/gremlin.py/GremlinClient._deserialize |
2,179 | def _repr_svg_(self):
"""Show SVG representation of the transducer (IPython magic).
>>> dg = DependencyGraph(
... 'John N 2\\n'
... 'loves V 0\\n'
... 'Mary N 2'
... )
>>> dg._repr_svg_().split('\\n')[0]
'<?xml version="1.0" encoding="UTF-8" s... | OSError | dataset/ETHPy150Open nltk/nltk/nltk/parse/dependencygraph.py/DependencyGraph._repr_svg_ |
2,180 | def _parse(self, input_, cell_extractor=None, zero_based=False, cell_separator=None, top_relation_label='ROOT'):
"""Parse a sentence.
:param extractor: a function that given a tuple of cells returns a
7-tuple, where the values are ``word, lemma, ctag, tag, feats, head,
rel``.
:... | ValueError | dataset/ETHPy150Open nltk/nltk/nltk/parse/dependencygraph.py/DependencyGraph._parse |
2,181 | def _hd(self, i):
try:
return self.nodes[i]['head']
except __HOLE__:
return None | IndexError | dataset/ETHPy150Open nltk/nltk/nltk/parse/dependencygraph.py/DependencyGraph._hd |
2,182 | def _rel(self, i):
try:
return self.nodes[i]['rel']
except __HOLE__:
return None
# what's the return type? Boolean or list? | IndexError | dataset/ETHPy150Open nltk/nltk/nltk/parse/dependencygraph.py/DependencyGraph._rel |
2,183 | def _update_or_create_shard(self, step):
""" Find or create a random shard and alter its `count` by the given step. """
shard_index = random.randint(0, self.field.shard_count - 1)
# Converting the set to a list introduces some randomness in the ordering, but that's fine
shard_pks = list(... | IndexError | dataset/ETHPy150Open potatolondon/djangae/djangae/fields/counting.py/RelatedShardManager._update_or_create_shard |
2,184 | def run_asv(args, current_repo=False):
cwd = os.path.abspath(os.path.dirname(__file__))
if current_repo:
try:
from asv.util import load_json, write_json
conf = load_json(os.path.join(cwd, 'asv.conf.json'))
conf['repo'] = os.path.normpath(os.path.join(cwd, '..'))
... | RuntimeError | dataset/ETHPy150Open scipy/scipy/benchmarks/run.py/run_asv |
2,185 | def is_git_repo_root(path):
try:
p = subprocess.Popen(['git', '-C', path, 'rev-parse', '--git-dir'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
return False
return (out.strip() == '.git')
... | OSError | dataset/ETHPy150Open scipy/scipy/benchmarks/run.py/is_git_repo_root |
2,186 | def __init__(self, func, when):
#: context of invocation: one of "setup", "call",
#: "teardown", "memocollect"
self.when = when
self.start = time()
try:
self.result = func()
except __HOLE__:
self.stop = time()
raise
except:
... | KeyboardInterrupt | dataset/ETHPy150Open pytest-dev/pytest/_pytest/runner.py/CallInfo.__init__ |
2,187 | def getslaveinfoline(node):
try:
return node._slaveinfocache
except __HOLE__:
d = node.slaveinfo
ver = "%s.%s.%s" % d['version_info'][:3]
node._slaveinfocache = s = "[%s] %s -- Python %s %s" % (
d['id'], d['sysplatform'], ver, d['executable'])
return s | AttributeError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/runner.py/getslaveinfoline |
2,188 | def importorskip(modname, minversion=None):
""" return imported module if it has at least "minversion" as its
__version__ attribute. If no minversion is specified the a skip
is only triggered if the module can not be imported.
"""
__tracebackhide__ = True
compile(modname, '', 'eval') # to catch... | ImportError | dataset/ETHPy150Open pytest-dev/pytest/_pytest/runner.py/importorskip |
2,189 | def lazy_gettext(string, **variables):
""" Similar to 'gettext' but the string returned is lazy which means
it will be translated when it is used as an actual string."""
try:
from speaklater import make_lazy_string
return make_lazy_string(gettext, string, **variables)
except __HOLE__... | ImportError | dataset/ETHPy150Open lingthio/Flask-User/flask_user/translations.py/lazy_gettext |
2,190 | def lookup(value, key):
"""
Return a dictionary lookup of key in value
"""
try:
return value[key]
except __HOLE__:
return "" | KeyError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_store/shop/templatetags/satchmo_util.py/lookup |
2,191 | def test_rowset_tables():
# print("Project ID:", project.id)
# del integration._to_cleanup[:]
cols = []
cols.append(Column(name='name', columnType='STRING', maximumSize=1000))
cols.append(Column(name='foo', columnType='STRING', enumValues=['foo', 'bar', 'bat']))
cols.append(Column(name='x', co... | ImportError | dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/integration/test_tables.py/test_rowset_tables |
2,192 | def test_tables_csv():
## Define schema
cols = []
cols.append(Column(name='Name', columnType='STRING'))
cols.append(Column(name='Born', columnType='INTEGER'))
cols.append(Column(name='Hipness', columnType='DOUBLE'))
cols.append(Column(name='Living', columnType='BOOLEAN'))
schema = Schema(n... | ImportError | dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/integration/test_tables.py/test_tables_csv |
2,193 | def test_tables_pandas():
try:
## check if we have pandas
import pandas as pd
## create a pandas DataFrame
df = pd.DataFrame({
'A' : ("foo", "bar", "baz", "qux", "asdf"),
'B' : tuple(math.pi*i for i in range(5)),
'C' : (101, 202, 303, 404, 505),
... | ImportError | dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/integration/test_tables.py/test_tables_pandas |
2,194 | def _process_command(self, cmd, sender):
# this function is runned by a worker thread
logger = self._logger.getChild('worker')
try:
arg_list = cmd.split()
logger.debug('get cmd: ' + str(arg_list))
args, unknown_args = self._cmd_parser.parse_known_args(arg_list... | SystemExit | dataset/ETHPy150Open KavenC/Linot/linot/command_server.py/CmdServer._process_command |
2,195 | def _failsafe_parse(self, requirement):
try:
return Requirement.parse(requirement, replacement=False)
except __HOLE__:
return Requirement.parse(requirement) | TypeError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/python/python_setup.py/PythonSetup._failsafe_parse |
2,196 | def main():
try:
hostname = raw_input("Enter remote host to test: ")
username = raw_input("Enter remote username: ")
except __HOLE__:
hostname = input("Enter remote host to test: ")
username = input("Enter remote username: ")
linux_test = {
'username': username... | NameError | dataset/ETHPy150Open ktbyers/netmiko/tests/test_linux.py/main |
2,197 | def get_endpoint(self, datacenter=None, network=None):
"""Get a message queue endpoint based on datacenter/network type.
:param datacenter: datacenter code
:param network: network ('public' or 'private')
"""
if datacenter is None:
datacenter = 'dal05'
if netw... | KeyError | dataset/ETHPy150Open softlayer/softlayer-python/SoftLayer/managers/messaging.py/MessagingManager.get_endpoint |
2,198 | def get_vcd_timescale( model ):
try:
return model.vcd_timescale
except __HOLE__:
return DEFAULT_TIMESCALE
#-----------------------------------------------------------------------
# write_vcd_header
#----------------------------------------------------------------------- | AttributeError | dataset/ETHPy150Open cornell-brg/pymtl/pymtl/tools/simulation/vcd.py/get_vcd_timescale |
2,199 | def test02_proxy(self):
"Testing Lazy-Geometry support (using the GeometryProxy)."
#### Testing on a Point
pnt = Point(0, 0)
nullcity = City(name='NullCity', point=pnt)
nullcity.save()
# Making sure TypeError is thrown when trying to set with an
# incompatible t... | TypeError | dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/gis/tests/geoapp/tests_mysql.py/GeoModelTest.test02_proxy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.