function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
---|---|---|
def headRequest(self, group, index, id = None):
if id is not None:
try:
xref = self.dbm['Message-IDs'][id]
except __HOLE__:
return defer.fail(NewsServerError("No such article: " + id))
else:
group, index = xref[0]
index = int(index)
try:
a = self.dbm['groups'][group].articles[index]
except KeyError:
return defer.fail(NewsServerError("No such group: " + group))
else:
return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders())) | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.headRequest |
def bodyRequest(self, group, index, id = None):
if id is not None:
try:
xref = self.dbm['Message-IDs'][id]
except KeyError:
return defer.fail(NewsServerError("No such article: " + id))
else:
group, index = xref[0]
index = int(index)
try:
a = self.dbm['groups'][group].articles[index]
except __HOLE__:
return defer.fail(NewsServerError("No such group: " + group))
else:
return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body))) | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/news/database.py/NewsShelf.bodyRequest |
def is_user_lockable(request):
"""Check if the user has a profile with nolockout
If so, then return the value to see if this user is special
and doesn't get their account locked out
"""
try:
field = getattr(User, 'USERNAME_FIELD', 'username')
kwargs = {
field: request.POST.get(USERNAME_FORM_FIELD)
}
user = User.objects.get(**kwargs)
except User.DoesNotExist:
# not a valid user
return True
if hasattr(user, 'nolockout'):
# need to invert since we need to return
# false for users that can't be blocked
return not user.nolockout
elif hasattr(settings, 'AUTH_PROFILE_MODULE'):
try:
profile = user.get_profile()
if hasattr(profile, 'nolockout'):
# need to invert since we need to return
# false for users that can't be blocked
return not profile.nolockout
except (SiteProfileNotAvailable, __HOLE__, AttributeError):
# no profile
return True
# Default behavior for a user to be lockable
return True | ObjectDoesNotExist | dataset/ETHPy150Open django-pci/django-axes/axes/decorators.py/is_user_lockable |
def cart_add_listener(cart=None, product=None, form=None, request=None, **kwargs):
"""Post-processes the form, handling upsell formfields.
fields (potentially) in the form:
upsell_count: controls how many upsell formblocks to look for.
for ix in range(0,upsell_count):
upsell_include_ix: true if this one is to be included
upsell_qty_ix: quantity
upsell_slug_ix: product slug
"""
log.debug("cart_add_listener heard satchmo_cart_add_complete")
try:
rawct = form.get('upsell_count', 0)
ct = int(rawct)
except __HOLE__:
log.debug("Got bad upsell_count: %s", rawct)
ct = 0
results = []
if ct>0:
for i in range(0,ct):
results.append(_add_upsell(form, cart, i))
return results | ValueError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_ext/upsell/views.py/cart_add_listener |
def _add_upsell(form, cart, i):
field_include = "upsell_include_%s" % i
field_qty = "upsell_qty_%s" % i
field_slug = "upsell_slug_%s" % i
slug = ""
qty = Decimal('0')
if form.get(field_include, "false") == "true":
slug = form.get(field_slug, "")
if slug:
try:
rawqty = form.get(field_qty, 0)
if rawqty == "MATCH":
qty = Decimal(form['quantity'])
elif rawqty:
qty = Decimal(rawqty)
except __HOLE__:
log.debug('Bad upsell qty=%d', rawqty)
qty = Decimal('0')
except InvalidOperation:
log.debug('Bad upsell qty=%d', rawqty)
qty = Decimal('0')
if qty > 0:
from product.models import Product
try:
product = Product.objects.get_by_site(slug=slug)
try:
cart.add_item(product, number_added=qty)
log.info('Added upsell item: %s qty=%d', product.slug, qty)
return (True, product)
except CartAddProhibited, cap:
vetomsg = cap.veto_messages()
msg = _("'%(product)s' couldn't be added to the cart. %(details)s") % {
'product' : product.slug,
'detail' : cap.message
}
log.debug("Failed to add upsell item: '%s', message= %s", product.slug, msg)
return (False, product)
except Product.DoesNotExist:
log.debug("Could not find product: %s", slug)
return (False, None)
return (False, None) | ValueError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_ext/upsell/views.py/_add_upsell |
def run(self):
"""
try open dockerfile, output an error if there is one
"""
try:
return DockerfileParser(self.workflow.builder.df_path).content
except (__HOLE__, OSError) as ex:
return "Couldn't retrieve dockerfile: %r" % ex | IOError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/pre_return_dockerfile.py/CpDockerfilePlugin.run |
def _get_serializer(self, serializer_name):
try:
serializer = self.serializers[serializer_name]
except __HOLE__:
raise KeyError(
"Serializer {0} doesn't exist or isn't registered".format(
serializer_name
)
)
return serializer | KeyError | dataset/ETHPy150Open kevin1024/vcrpy/vcr/config.py/VCR._get_serializer |
def _get_matchers(self, matcher_names):
matchers = []
try:
for m in matcher_names:
matchers.append(self.matchers[m])
except __HOLE__:
raise KeyError(
"Matcher {0} doesn't exist or isn't registered".format(m)
)
return matchers | KeyError | dataset/ETHPy150Open kevin1024/vcrpy/vcr/config.py/VCR._get_matchers |
def auto_transform_markup(comment):
"""
Given a comment (``ThreadedComment`` or ``FreeThreadedComment``), this tag
looks up the markup type of the comment and formats the output accordingly.
It can also output the formatted content to a context variable, if a context name is
specified.
"""
try:
from django.utils.html import escape
from threadedcomments.models import MARKDOWN, TEXTILE, REST, PLAINTEXT
if comment.markup == MARKDOWN:
from django.contrib.markup.templatetags.markup import markdown
return markdown(comment.comment)
elif comment.markup == TEXTILE:
from django.contrib.markup.templatetags.markup import textile
return textile(comment.comment)
elif comment.markup == REST:
from django.contrib.markup.templatetags.markup import restructuredtext
return restructuredtext(comment.comment)
# elif comment.markup == HTML:
# return mark_safe(force_unicode(comment.comment))
elif comment.markup == PLAINTEXT:
return escape(comment.comment)
except __HOLE__:
# Not marking safe, in case tag fails and users input malicious code.
return force_unicode(comment.comment) | ImportError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/auto_transform_markup |
def do_auto_transform_markup(parser, token):
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, "%r tag must be of format {%% %r COMMENT %%} or of format {%% %r COMMENT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0], token.contents.split()[0])
if len(split) == 2:
return AutoTransformMarkupNode(split[1])
elif len(split) == 4:
return AutoTransformMarkupNode(split[1], context_name=split[3])
else:
raise template.TemplateSyntaxError, "Invalid number of arguments for tag %r" % split[0] | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_auto_transform_markup |
def do_get_threaded_comment_tree(parser, token):
"""
Gets a tree (list of objects ordered by preorder tree traversal, and with an
additional ``depth`` integer attribute annotated onto each ``ThreadedComment``.
"""
error_string = "%r tag must be of format {%% get_threaded_comment_tree for OBJECT [TREE_ROOT] as CONTEXT_VARIABLE %%}" % token.contents.split()[0]
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError(error_string)
if len(split) == 5:
return CommentTreeNode(split[2], split[4], split[3])
elif len(split) == 6:
return CommentTreeNode(split[2], split[5], split[3])
else:
raise template.TemplateSyntaxError(error_string) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_threaded_comment_tree |
def do_get_free_threaded_comment_tree(parser, token):
"""
Gets a tree (list of objects ordered by traversing tree in preorder, and with an
additional ``depth`` integer attribute annotated onto each ``FreeThreadedComment.``
"""
error_string = "%r tag must be of format {%% get_free_threaded_comment_tree for OBJECT [TREE_ROOT] as CONTEXT_VARIABLE %%}" % token.contents.split()[0]
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError(error_string)
if len(split) == 5:
return FreeCommentTreeNode(split[2], split[4], split[3])
elif len(split) == 6:
return FreeCommentTreeNode(split[2], split[5], split[3])
else:
raise template.TemplateSyntaxError(error_string) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_free_threaded_comment_tree |
def render(self, context):
content_object = self.content_object.resolve(context)
try:
tree_root = self.tree_root.resolve(context)
except template.VariableDoesNotExist:
if self.tree_root_str == 'as':
tree_root = None
else:
try:
tree_root = int(self.tree_root_str)
except __HOLE__:
tree_root = self.tree_root_str
context[self.context_name] = ThreadedComment.public.get_tree(content_object, root=tree_root)
return '' | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/CommentTreeNode.render |
def render(self, context):
content_object = self.content_object.resolve(context)
try:
tree_root = self.tree_root.resolve(context)
except template.VariableDoesNotExist:
if self.tree_root_str == 'as':
tree_root = None
else:
try:
tree_root = int(self.tree_root_str)
except __HOLE__:
tree_root = self.tree_root_str
context[self.context_name] = FreeThreadedComment.public.get_tree(content_object, root=tree_root)
return '' | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/FreeCommentTreeNode.render |
def do_get_comment_count(parser, token):
"""
Gets a count of how many ThreadedComment objects are attached to the given
object.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if split[1] != 'for' or split[3] != 'as':
raise template.TemplateSyntaxError, error_message
return ThreadedCommentCountNode(split[2], split[4]) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_comment_count |
def do_get_free_comment_count(parser, token):
"""
Gets a count of how many FreeThreadedComment objects are attached to the
given object.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if split[1] != 'for' or split[3] != 'as':
raise template.TemplateSyntaxError, error_message
return FreeThreadedCommentCountNode(split[2], split[4]) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_free_comment_count |
def do_get_threaded_comment_form(parser, token):
"""
Gets a FreeThreadedCommentForm and inserts it into the context.
"""
error_message = "%r tag must be of format {%% %r as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if split[1] != 'as':
raise template.TemplateSyntaxError, error_message
if len(split) != 3:
raise template.TemplateSyntaxError, error_message
if "free" in split[0]:
is_free = True
else:
is_free = False
return ThreadedCommentFormNode(split[2], free=is_free) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_threaded_comment_form |
def do_get_latest_comments(parser, token):
"""
Gets the latest comments by date_submitted.
"""
error_message = "%r tag must be of format {%% %r NUM_TO_GET as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if len(split) != 4:
raise template.TemplateSyntaxError, error_message
if split[2] != 'as':
raise template.TemplateSyntaxError, error_message
if "free" in split[0]:
is_free = True
else:
is_free = False
return LatestCommentsNode(split[1], split[3], free=is_free) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_latest_comments |
def do_get_user_comments(parser, token):
"""
Gets all comments submitted by a particular user.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if len(split) != 5:
raise template.TemplateSyntaxError, error_message
return UserCommentsNode(split[2], split[4]) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_user_comments |
def do_get_user_comment_count(parser, token):
"""
Gets the count of all comments submitted by a particular user.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, error_message
if len(split) != 5:
raise template.TemplateSyntaxError, error_message
return UserCommentCountNode(split[2], split[4]) | ValueError | dataset/ETHPy150Open caseywstark/colab/colab/apps/threadedcomments/templatetags/threadedcommentstags.py/do_get_user_comment_count |
@override_settings(DEBUG=True, TEMPLATE_DEBUG = True)
def test_correct_exception_index(self):
tests = [
('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)),
('{% load bad_tag %}{% for i in range %}{% for j in range %}{% badsimpletag %}{% endfor %}{% endfor %}', (58, 76)),
('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% for j in range %}Hello{% endfor %}{% endfor %}', (38, 56)),
('{% load bad_tag %}{% for i in range %}{% for j in five %}{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57)),
('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)),
]
context = Context({
'range': range(5),
'five': 5,
})
for source, expected_error_source_index in tests:
template = get_template_from_string(source)
try:
template.render(context)
except (__HOLE__, TypeError), e:
error_source_index = e.django_template_source[1]
self.assertEqual(error_source_index,
expected_error_source_index) | RuntimeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/tests/regressiontests/templates/nodelist.py/ErrorIndexTest.test_correct_exception_index |
@require_GET
@mobile_template('users/{mobile/}profile.html')
def profile(request, template, username):
# The browser replaces '+' in URL's with ' ' but since we never have ' ' in
# URL's we can assume everytime we see ' ' it was a '+' that was replaced.
# We do this to deal with legacy usernames that have a '+' in them.
username = username.replace(' ', '+')
user = User.objects.filter(username=username).first()
if not user:
try:
user = get_object_or_404(User, id=username)
except __HOLE__:
raise Http404('No Profile matches the given query.')
return redirect(reverse('users.profile', args=(user.username,)))
user_profile = get_object_or_404(Profile, user__id=user.id)
if not (request.user.has_perm('users.deactivate_users') or
user_profile.user.is_active):
raise Http404('No Profile matches the given query.')
groups = user_profile.user.groups.all()
return render(request, template, {
'profile': user_profile,
'awards': Award.objects.filter(user=user_profile.user),
'groups': groups,
'num_questions': num_questions(user_profile.user),
'num_answers': num_answers(user_profile.user),
'num_solutions': num_solutions(user_profile.user),
'num_documents': user_num_documents(user_profile.user)}) | ValueError | dataset/ETHPy150Open mozilla/kitsune/kitsune/users/views.py/profile |
@login_required
@require_http_methods(['GET', 'POST'])
@mobile_template('users/{mobile/}edit_settings.html')
def edit_settings(request, template):
"""Edit user settings"""
if request.method == 'POST':
form = SettingsForm(request.POST)
if form.is_valid():
form.save_for_user(request.user)
messages.add_message(request, messages.INFO,
_(u'Your settings have been saved.'))
return HttpResponseRedirect(reverse('users.edit_settings'))
# Invalid form
return render(request, template, {'form': form})
# Pass the current user's settings as the initial values.
values = request.user.settings.values()
initial = dict()
for v in values:
try:
# Uses ast.literal_eval to convert 'False' => False etc.
# TODO: Make more resilient.
initial[v['name']] = literal_eval(v['value'])
except (SyntaxError, __HOLE__):
# Attempted to convert the string value to a Python value
# but failed so leave it a string.
initial[v['name']] = v['value']
form = SettingsForm(initial=initial)
return render(request, template, {'form': form}) | ValueError | dataset/ETHPy150Open mozilla/kitsune/kitsune/users/views.py/edit_settings |
@ssl_required
@anonymous_csrf
@mobile_template('users/{mobile/}pw_reset_confirm.html')
def password_reset_confirm(request, template, uidb36=None, token=None):
"""View that checks the hash in a password reset link and presents a
form for entering a new password.
Based on django.contrib.auth.views.
"""
try:
uid_int = base36_to_int(uidb36)
except __HOLE__:
raise Http404
user = get_object_or_404(User, id=uid_int)
context = {}
if default_token_generator.check_token(user, token):
context['validlink'] = True
if request.method == 'POST':
form = SetPasswordForm(user, request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('users.pw_reset_complete'))
else:
form = SetPasswordForm(None)
else:
context['validlink'] = False
form = None
context['form'] = form
return render(request, template, context) | ValueError | dataset/ETHPy150Open mozilla/kitsune/kitsune/users/views.py/password_reset_confirm |
@require_GET
@never_cache
@json_view
def validate_field(request):
data = {'valid': True}
field = request.GET.get('field')
value = request.GET.get('value')
form = RegisterForm()
try:
form.fields[request.GET.get('field')].clean(request.GET.get('value'))
except ValidationError, e:
data = {
'valid': False,
'error': e.messages[0]
}
except __HOLE__:
data = {
'valid': False,
'error': _('Invalid field')
}
if data['valid']:
if field == 'username':
if User.objects.filter(username=value).exists():
data = {
'valid': False,
'error': _('This username is already taken!')
}
elif field == 'email':
if User.objects.filter(email=request.GET.get('value')).exists():
data = {
'valid': False,
'error': _('This email is already in use!')
}
return data | KeyError | dataset/ETHPy150Open mozilla/kitsune/kitsune/users/views.py/validate_field |
def __init__(self, url):
if url.startswith('mysql://'):
try:
import MySQLdb
assert MySQLdb is not None # avoid warnings
except __HOLE__:
import pymysql_sa
pymysql_sa.make_default_mysql_dialect()
self.url = url
self.config = Config(os.path.join(self.alembic_path, "alembic.ini"))
self.config.set_main_option("script_location", self.alembic_path)
self.config.set_main_option("url", self.url)
self.config.set_main_option("sqlalchemy.url", self.url) | ImportError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/weblab/db/upgrade/__init__.py/DbParticularUpgrader.__init__ |
def get_progress(self):
error = False
error_message = ''
try:
info = self.task.info
except (__HOLE__, NotImplementedError):
current = total = percent = None
logging.exception("No celery result backend?")
else:
if info is None:
current = total = percent = None
elif isinstance(info, Exception):
current = total = percent = 100
error = True
error_message = "%s: %s" % (type(info).__name__, info)
else:
current = info.get('current')
total = info.get('total')
percent = int(
current * 100. / total if total and current is not None
else 0
)
return {
'current': current,
'total': total,
'percent': percent,
'error': error,
'error_message': error_message,
} | TypeError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/soil/__init__.py/DownloadBase.get_progress |
@classmethod
def set_progress(cls, task, current, total):
try:
if task:
task.update_state(state='PROGRESS', meta={'current': current, 'total': total})
except (__HOLE__, NotImplementedError):
pass
except IntegrityError:
# Not called in task context just pass
pass | TypeError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/soil/__init__.py/DownloadBase.set_progress |
def fix_IE_for_attach(request, response):
"""
This function will prevent Django from serving a Content-Disposition header
while expecting the browser to cache it (only when the browser is IE). This
leads to IE not allowing the client to download.
"""
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent:
return response
offending_headers = ('no-cache', 'no-store')
if response.has_header('Content-Disposition'):
try:
del response['Pragma']
except __HOLE__:
pass
if response.has_header('Cache-Control'):
cache_control_values = [value.strip() for value in
response['Cache-Control'].split(',')
if value.strip().lower() not in offending_headers]
if not len(cache_control_values):
del response['Cache-Control']
else:
response['Cache-Control'] = ', '.join(cache_control_values)
return response | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/http/utils.py/fix_IE_for_attach |
def fix_IE_for_vary(request, response):
"""
This function will fix the bug reported at
http://support.microsoft.com/kb/824847/en-us?spid=8722&sid=global
by clearing the Vary header whenever the mime-type is not safe
enough for Internet Explorer to handle. Poor thing.
"""
useragent = request.META.get('HTTP_USER_AGENT', '').upper()
if 'MSIE' not in useragent and 'CHROMEFRAME' not in useragent:
return response
# These mime-types that are decreed "Vary-safe" for IE:
safe_mime_types = ('text/html', 'text/plain', 'text/sgml')
# The first part of the Content-Type field will be the MIME type,
# everything after ';', such as character-set, can be ignored.
mime_type = response.get('Content-Type', '').partition(';')[0]
if mime_type not in safe_mime_types:
try:
del response['Vary']
except __HOLE__:
pass
return response | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/http/utils.py/fix_IE_for_vary |
def runner_fail_no_test_found(self):
"""
Check that Python Nose runner fails if no tests were found
:return:
"""
obj = SeleniumExecutor()
obj.engine = EngineEmul()
obj.engine.config.merge({
ScenarioExecutor.EXEC: {
"executor": "selenium",
"scenario": {"script": __dir__() + "/../selenium/invalid/dummy.py"}
}
})
obj.execution = obj.engine.config['execution']
obj.prepare()
obj.startup()
try:
while not obj.check():
time.sleep(1)
self.fail()
except __HOLE__ as exc:
self.assertIn("Nothing to test.", exc.args[0])
obj.shutdown() | RuntimeError | dataset/ETHPy150Open Blazemeter/taurus/tests/modules/test_SeleniumExecutor.py/TestSeleniumNoseRunner.runner_fail_no_test_found |
def get_task(self, node):
task = self.project.next_task()
if task is None:
try:
tp_id = self._tasks_pool.pop()
task = self.project[tp_id]
except __HOLE__:
# project depleted and nothing in the pool,
# looks like the application is completed.
self.completed = True
raise ApplicationCompletedError(self)
task_id = task['id']
node.task_id = task_id
self._tasks_pool.add(task_id)
return task | KeyError | dataset/ETHPy150Open BasicWolf/kaylee/kaylee/contrib/controllers.py/SimpleController.get_task |
def get_task(self, node):
task = self.project.next_task()
if task is None:
try:
tp_id = self._tasks_pool.pop()
task = self.project[tp_id]
except __HOLE__:
# project depleted and nothing in the pool,
# looks like the application has completed.
self.completed = True
raise ApplicationCompletedError(self)
task_id = task['id']
node.task_id = task_id
self._tasks_pool.add(task_id)
if self.temporal_storage.contains(task_id, node.id):
raise NodeRequestRejectedError('The result of this task has been '
'already accepted.')
return task | KeyError | dataset/ETHPy150Open BasicWolf/kaylee/kaylee/contrib/controllers.py/ResultsComparatorController.get_task |
def open_files(pid=None, close_unused=True):
"""
Return a dict of open files for the given process.
The key of the dict is the file descriptor (a number).
If PID is not specified, the PID of the current program is used.
Only regular open files are returned.
If close_unused is True, do garbage collection prior to getting the list
of open files. This makes open_files() more reliable, as files which are
no longer reachable or used, but not yet closed by the resource manager.
This function relies on the external `lsof` program.
This function may raise an OSError.
"""
if pid is None:
pid = os.getpid()
if close_unused:
# garbage collection. Ensure that unreachable files are closed, making
# the output of open_files() more reliable.
gc.collect()
# lsof lists open files, including sockets, etc.
command = ['lsof', '-nlP', '-b', '-w', '-p', str(pid), '-F', 'ftn']
# set LC_ALL=UTF-8, so non-ASCII files are properly reported.
env = dict(os.environ).copy()
env['LC_ALL'] = 'UTF-8'
# Open a subprocess, wait till it is done, and get the STDOUT result
output = subprocess.Popen(command, stdout=subprocess.PIPE, env=env).communicate()[0]
# decode the output and split in lines.
output = output.decode('utf-8').split('\n')
files = {}
state = {'f': '', 't': ''}
for line in output:
try:
linetype, line = line[0], line[1:]
except __HOLE__:
continue
state[linetype] = line
if linetype == 'n':
if state['t'] == 'REG' and state['f'].isdigit():
files[int(state['f'])] = line
state = {'f': '', 't': ''}
return files | IndexError | dataset/ETHPy150Open twoolie/NBT/tests/utils.py/open_files |
def _create_poller(operation):
"""
Creates an operation poller from the passed in operation.
:param operation: A dict representing a GCE operation resource.
:returns: An :class:`OperationPoller` provider that can poll the status of
the operation.
"""
try:
operation_name = operation['name']
except KeyError:
raise MalformedOperation(
u"Failed to parse operation, could not find key "
u"name in: {}".format(operation)
)
if 'zone' in operation:
zone_url_parts = unicode(operation['zone']).split('/')
try:
project = zone_url_parts[-3]
zone = zone_url_parts[-1]
except IndexError:
raise MalformedOperation(
"'zone' key of operation had unexpected form: {}.\n"
"Expected '(.*/)?<project>/zones/<zone>'.\n"
"Full operation: {}.".format(operation['zone'], operation))
return ZoneOperationPoller(
zone=unicode(zone),
project=unicode(project),
operation_name=unicode(operation_name)
)
else:
try:
project = unicode(operation['selfLink']).split('/')[-4]
except KeyError:
raise MalformedOperation(
u"Failed to parse global operation, could not find key "
u"selfLink in: {}".format(operation)
)
except __HOLE__:
raise MalformedOperation(
"'selfLink' key of operation had unexpected form: {}.\n"
"Expected '(.*/)?<project>/global/operations/<name>'.\n"
"Full operation: {}.".format(operation['selfLink'], operation))
return GlobalOperationPoller(
project=unicode(project),
operation_name=unicode(operation_name)
) | IndexError | dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/gce.py/_create_poller |
def get_integer_argument(request, name, default):
try:
value = int(request.session.get(name, default))
return int(request.GET.get(name, value))
except (__HOLE__, ValueError):
return default | TypeError | dataset/ETHPy150Open bgolub/fftogo/fftogo/views.py/get_integer_argument |
@magic_arguments()
@argument(
'-i', '--input', action='append',
help='Names of input variable from shell.user_ns to be assigned to Matlab variables of the same names after calling self.pyconverter. Multiple names can be passed separated only by commas with no whitespace.'
)
@argument(
'-o', '--output', action='append',
help='Names of variables to be pushed from matlab to shell.user_ns after executing cell body and applying self.Matlab.get_variable(). Multiple names can be passed separated only by commas with no whitespace.'
)
@argument(
'-s', '--silent', action='store_true',
help='Do not display text output of MATLAB command'
)
@argument(
'-S', '--size', action='store', default='512,384',
help='Pixel size of plots, "width,height.'
)
@argument(
'-g', '--gui', action='store_true',
help='Show plots in a graphical user interface'
)
@argument(
'code',
nargs='*',
)
@needs_local_scope
@line_cell_magic
def matlab(self, line, cell=None, local_ns=None):
"Execute code in matlab."
args = parse_argstring(self.matlab, line)
code = line if cell is None else ' '.join(args.code) + cell
if local_ns is None:
local_ns = {}
width, height = args.size.split(',')
self.Matlab.set_plot_settings(width, height, not args.gui)
if args.input:
for input in ','.join(args.input).split(','):
try:
val = local_ns[input]
except __HOLE__:
val = self.shell.user_ns[input]
# The _Session.set_variable function which this calls
# should correctly detect numpy arrays and serialize them
# as json correctly.
self.set_matlab_var(input, val)
try:
result_dict = self.eval(code)
except MatlabInterperterError:
raise
except:
raise RuntimeError('\n'.join([
"There was an error running the code:",
code,
"-----------------------",
"Are you sure Matlab is started?",
]))
text_output = result_dict['content']['stdout']
# Figures get saved by matlab in reverse order...
imgfiles = result_dict['content']['figures'][::-1]
data_dir = result_dict['content']['datadir']
display_data = []
if text_output and not args.silent:
display_data.append(('MatlabMagic.matlab',
{'text/plain': text_output}))
for imgf in imgfiles:
if len(imgf):
# Store the path to the directory so that you can delete it
# later on:
with open(imgf, 'rb') as fid:
image = fid.read()
display_data.append(('MatlabMagic.matlab',
{'image/png': image}))
for disp_d in display_data:
publish_display_data(source=disp_d[0], data=disp_d[1])
# Delete the temporary data files created by matlab:
if len(data_dir):
rmtree(data_dir)
if args.output:
for output in ','.join(args.output).split(','):
self.shell.push({output:self.Matlab.get_variable(output)}) | KeyError | dataset/ETHPy150Open arokem/python-matlab-bridge/pymatbridge/matlab_magic.py/MatlabMagics.matlab |
def apply(self):
if not len(self.document):
# @@@ replace these DataErrors with proper system messages
raise DataError('Document tree is empty.')
header = self.document[0]
if not isinstance(header, nodes.field_list) or \
'rfc2822' not in header['classes']:
raise DataError('Document does not begin with an RFC-2822 '
'header; it is not a PEP.')
pep = None
for field in header:
if field[0].astext().lower() == 'pep': # should be the first field
value = field[1].astext()
try:
pep = int(value)
cvs_url = self.pep_cvs_url % pep
except __HOLE__:
pep = value
cvs_url = None
msg = self.document.reporter.warning(
'"PEP" header must contain an integer; "%s" is an '
'invalid value.' % pep, base_node=field)
msgid = self.document.set_id(msg)
prb = nodes.problematic(value, value or '(none)',
refid=msgid)
prbid = self.document.set_id(prb)
msg.add_backref(prbid)
if len(field[1]):
field[1][0][:] = [prb]
else:
field[1] += nodes.paragraph('', '', prb)
break
if pep is None:
raise DataError('Document does not contain an RFC-2822 "PEP" '
'header.')
if pep == 0:
# Special processing for PEP 0.
pending = nodes.pending(PEPZero)
self.document.insert(1, pending)
self.document.note_pending(pending)
if len(header) < 2 or header[1][0].astext().lower() != 'title':
raise DataError('No title!')
for field in header:
name = field[0].astext().lower()
body = field[1]
if len(body) > 1:
raise DataError('PEP header field body contains multiple '
'elements:\n%s' % field.pformat(level=1))
elif len(body) == 1:
if not isinstance(body[0], nodes.paragraph):
raise DataError('PEP header field body may only contain '
'a single paragraph:\n%s'
% field.pformat(level=1))
elif name == 'last-modified':
date = time.strftime(
'%d-%b-%Y',
time.localtime(os.stat(self.document['source'])[8]))
if cvs_url:
body += nodes.paragraph(
'', '', nodes.reference('', date, refuri=cvs_url))
else:
# empty
continue
para = body[0]
if name == 'author':
for node in para:
if isinstance(node, nodes.reference):
node.replace_self(mask_email(node))
elif name == 'discussions-to':
for node in para:
if isinstance(node, nodes.reference):
node.replace_self(mask_email(node, pep))
elif name in ('replaces', 'replaced-by', 'requires'):
newbody = []
space = nodes.Text(' ')
for refpep in re.split(',?\s+', body.astext()):
pepno = int(refpep)
newbody.append(nodes.reference(
refpep, refpep,
refuri=(self.document.settings.pep_base_url
+ self.pep_url % pepno)))
newbody.append(space)
para[:] = newbody[:-1] # drop trailing space
elif name == 'last-modified':
utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions)
if cvs_url:
date = para.astext()
para[:] = [nodes.reference('', date, refuri=cvs_url)]
elif name == 'content-type':
pep_type = para.astext()
uri = self.document.settings.pep_base_url + self.pep_url % 12
para[:] = [nodes.reference('', pep_type, refuri=uri)]
elif name == 'version' and len(body):
utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) | ValueError | dataset/ETHPy150Open adieu/allbuttonspressed/docutils/transforms/peps.py/Headers.apply |
def visit_entry(self, node):
self.entry += 1
if self.pep_table and self.entry == 2 and len(node) == 1:
node['classes'].append('num')
p = node[0]
if isinstance(p, nodes.paragraph) and len(p) == 1:
text = p.astext()
try:
pep = int(text)
ref = (self.document.settings.pep_base_url
+ self.pep_url % pep)
p[0] = nodes.reference(text, text, refuri=ref)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open adieu/allbuttonspressed/docutils/transforms/peps.py/PEPZeroSpecial.visit_entry |
@signalcommand
def handle(self, addrport='', *args, **options):
import django
import socket
import errno
from django.core.servers.basehttp import run
try:
from django.core.servers.basehttp import get_internal_wsgi_application as WSGIHandler
except ImportError:
from django.core.handlers.wsgi import WSGIHandler # noqa
try:
from django.core.servers.basehttp import AdminMediaHandler
HAS_ADMINMEDIAHANDLER = True
except ImportError:
HAS_ADMINMEDIAHANDLER = False
try:
from django.core.servers.basehttp import WSGIServerException as wsgi_server_exc_cls
except ImportError: # Django 1.6
wsgi_server_exc_cls = socket.error
if args:
raise CommandError('Usage is runserver %s' % self.args)
if not addrport:
addr = ''
port = '8000'
else:
try:
addr, port = addrport.split(':')
except ValueError:
addr, port = '', addrport
if not addr:
addr = '127.0.0.1'
if not port.isdigit():
raise CommandError("%r is not a valid port number." % port)
use_reloader = options.get('use_reloader', True)
shutdown_message = options.get('shutdown_message', '')
no_media = options.get('no_media', False)
quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
def inner_run():
import os
import time
try:
import hotshot
except ImportError:
pass # python 3.x
USE_CPROFILE = options.get('use_cprofile', False)
USE_LSPROF = options.get('use_lsprof', False)
if USE_LSPROF:
USE_CPROFILE = True
if USE_CPROFILE:
try:
import cProfile
USE_CPROFILE = True
except ImportError:
print("cProfile disabled, module cannot be imported!")
USE_CPROFILE = False
if USE_LSPROF and not USE_CPROFILE:
raise SystemExit("Kcachegrind compatible output format required cProfile from Python 2.5")
prof_path = options.get('prof_path', '/tmp')
prof_file = options.get('prof_file', '{path}.{duration:06d}ms.{time}')
if not prof_file.format(path='1', duration=2, time=3):
prof_file = '{path}.{duration:06d}ms.{time}'
print("Filename format is wrong. Default format used: '{path}.{duration:06d}ms.{time}'.")
def get_exclude_paths():
exclude_paths = []
media_url = getattr(settings, 'MEDIA_URL', None)
if media_url:
exclude_paths.append(media_url)
static_url = getattr(settings, 'STATIC_URL', None)
if static_url:
exclude_paths.append(static_url)
admin_media_prefix = getattr(settings, 'ADMIN_MEDIA_PREFIX', None)
if admin_media_prefix:
exclude_paths.append(admin_media_prefix)
return exclude_paths
def make_profiler_handler(inner_handler):
def handler(environ, start_response):
path_info = environ['PATH_INFO']
# when using something like a dynamic site middleware is could be necessary
# to refetch the exclude_paths every time since they could change per site.
if no_media and any(path_info.startswith(p) for p in get_exclude_paths()):
return inner_handler(environ, start_response)
path_name = path_info.strip("/").replace('/', '.') or "root"
profname = "%s.%d.prof" % (path_name, time.time())
profname = os.path.join(prof_path, profname)
if USE_CPROFILE:
prof = cProfile.Profile()
else:
prof = hotshot.Profile(profname)
start = datetime.now()
try:
return prof.runcall(inner_handler, environ, start_response)
finally:
# seeing how long the request took is important!
elap = datetime.now() - start
elapms = elap.seconds * 1000.0 + elap.microseconds / 1000.0
if USE_LSPROF:
kg = KCacheGrind(prof)
with open(profname, 'w') as f:
kg.output(f)
elif USE_CPROFILE:
prof.dump_stats(profname)
profname2 = prof_file.format(path=path_name, duration=int(elapms), time=int(time.time()))
profname2 = os.path.join(prof_path, "%s.prof" % profname2)
if not USE_CPROFILE:
prof.close()
os.rename(profname, profname2)
return handler
print("Validating models...")
if hasattr(self, 'check'):
self.check(display_num_errors=True)
else:
self.validate(display_num_errors=True)
print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE))
print("Development server is running at http://%s:%s/" % (addr, port))
print("Quit the server with %s." % quit_command)
path = options.get('admin_media_path', '')
if not path:
admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
if os.path.isdir(admin_media_path):
path = admin_media_path
else:
path = os.path.join(django.__path__[0], 'contrib/admin/media')
try:
handler = WSGIHandler()
if HAS_ADMINMEDIAHANDLER:
handler = AdminMediaHandler(handler, path)
if USE_STATICFILES:
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if (use_static_handler and (settings.DEBUG or insecure_serving)):
handler = StaticFilesHandler(handler)
handler = make_profiler_handler(handler)
run(addr, int(port), handler)
except wsgi_server_exc_cls as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
errno.EACCES: "You don't have permission to access that port.",
errno.EADDRINUSE: "That port is already in use.",
errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
}
if not isinstance(e, socket.error): # Django < 1.6
ERRORS[13] = ERRORS.pop(errno.EACCES)
ERRORS[98] = ERRORS.pop(errno.EADDRINUSE)
ERRORS[99] = ERRORS.pop(errno.EADDRNOTAVAIL)
try:
if not isinstance(e, socket.error): # Django < 1.6
error_text = ERRORS[e.args[0].args[0]]
else:
error_text = ERRORS[e.errno]
except (AttributeError, KeyError):
error_text = str(e)
sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n')
# Need to use an OS exit because sys.exit doesn't work in a thread
os._exit(1)
except __HOLE__:
if shutdown_message:
print(shutdown_message)
sys.exit(0)
if use_reloader:
from django.utils import autoreload
autoreload.main(inner_run)
else:
inner_run() | KeyboardInterrupt | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/runprofileserver.py/Command.handle |
def ve2no(f, *args):
'Convert ValueError result to -1'
try:
return f(*args)
except __HOLE__:
return -1 | ValueError | dataset/ETHPy150Open tabatkins/bikeshed/bikeshed/SortedList.py/ve2no |
def fixup_script_(root, file_, old_dir, new_dir, version,
rewrite_env_python=False):
old_shebang = '#!%s/bin/python' % os.path.normcase(os.path.abspath(old_dir))
new_shebang = '#!%s/bin/python' % os.path.normcase(os.path.abspath(new_dir))
env_shebang = '#!/usr/bin/env python'
filename = os.path.join(root, file_)
with open(filename, 'rb') as f:
if f.read(2) != b'#!':
# no shebang
return
f.seek(0)
lines = f.readlines()
if not lines:
# warn: empty script
return
def rewrite_shebang(version=None):
logger.debug('fixing %s' % filename)
shebang = new_shebang
if version:
shebang = shebang + version
shebang = (shebang + '\n').encode('utf-8')
with open(filename, 'wb') as f:
f.write(shebang)
f.writelines(lines[1:])
try:
bang = lines[0].decode('utf-8').strip()
except __HOLE__:
# binary file
return
if not bang.startswith('#!'):
return
elif bang == old_shebang:
rewrite_shebang()
elif (bang.startswith(old_shebang)
and bang[len(old_shebang):] == version):
rewrite_shebang(version)
elif rewrite_env_python and bang.startswith(env_shebang):
if bang == env_shebang:
rewrite_shebang()
elif bang[len(env_shebang):] == version:
rewrite_shebang(version)
else:
# can't do anything
return | UnicodeDecodeError | dataset/ETHPy150Open edwardgeorge/virtualenv-clone/clonevirtualenv.py/fixup_script_ |
def main():
parser = optparse.OptionParser("usage: %prog [options]"
" /path/to/existing/venv /path/to/cloned/venv")
parser.add_option('-v',
action="count",
dest='verbose',
default=False,
help='verbosity')
options, args = parser.parse_args()
try:
old_dir, new_dir = args
except __HOLE__:
print("virtualenv-clone {}".format(__version__))
parser.error("not enough arguments given.")
old_dir = os.path.normpath(os.path.abspath(old_dir))
new_dir = os.path.normpath(os.path.abspath(new_dir))
loglevel = (logging.WARNING, logging.INFO, logging.DEBUG)[min(2,
options.verbose)]
logging.basicConfig(level=loglevel, format='%(message)s')
try:
clone_virtualenv(old_dir, new_dir)
except UserError:
e = sys.exc_info()[1]
parser.error(str(e)) | ValueError | dataset/ETHPy150Open edwardgeorge/virtualenv-clone/clonevirtualenv.py/main |
def __call__(self, value):
try:
return self.values[str(value).lower()]
except __HOLE__:
raise InvalidConfiguration("Error casting value {!r} to boolean".format(value)) | KeyError | dataset/ETHPy150Open osantana/prettyconf/prettyconf/casts.py/Boolean.__call__ |
def __call__(self, value):
try:
return self.options[value]
except __HOLE__:
raise InvalidConfiguration("Invalid option {!r}".format(value)) | KeyError | dataset/ETHPy150Open osantana/prettyconf/prettyconf/casts.py/Option.__call__ |
def export_cases(domain, cases, workbook, filter_group=None, users=None, all_groups=None, process=None):
by_user_id = dict([(user.user_id, user) for user in users]) if users else {}
by_group_id = dict([(g.get_id, g) for g in all_groups]) if all_groups else {}
owner_ids = set(by_user_id.keys())
if filter_group:
owner_ids.add(filter_group.get_id)
else:
# |= reassigns owner_ids to the union of the two sets
owner_ids |= set(by_group_id.keys())
case_static_keys = (
"case_id",
"username",
"user_id",
"owner_id",
"owner_name",
"type",
"name",
"opened_on",
"modified_on",
"closed",
"closed_on",
"domain",
"external_id",
)
case_dynamic_keys = get_case_properties(domain)
case_rows = []
def render_case_attr(case, key):
attr = getattr(case, key)
if isinstance (attr, dict):
return attr.get('#text', '')
else:
return attr
num_cases = len(cases)
def get_matching_owner(case):
if by_user_id:
if case.user_id in by_user_id:
return case.user_id
elif get_owner_id(case) in by_user_id:
return get_owner_id(case)
else:
return get_owner_id(case)
for i, case in enumerate(cases):
if process:
DownloadBase.set_progress(process, i, num_cases)
if get_owner_id(case) in owner_ids:
matching_owner = get_matching_owner(case)
case_row = {'dynamic_properties': {}}
for key in case_static_keys:
if key == 'username':
try:
case_row[key] = by_user_id[matching_owner].raw_username
except (__HOLE__, KeyError):
case_row[key] = ''
elif key == 'owner_name':
if users and case.owner_id in by_user_id:
case_row[key] = by_user_id[case.owner_id].full_name
elif case.owner_id in by_group_id:
case_row[key] = by_group_id[case.owner_id].name
else:
case_row[key] = ''
else:
case_row[key] = getattr(case, key)
for key in case.dynamic_properties():
case_row['dynamic_properties'][key] = render_case_attr(case, key)
case_rows.append(case_row)
def format_dynamic_key(key):
return "d.{key}".format(key=key)
def tidy_up_case_row(case_row):
row = dict([(key, case_row[key]) for key in case_static_keys])
for key in case_dynamic_keys:
row[format_dynamic_key(key)] = case_row['dynamic_properties'].get(key, workbook.undefined)
return row
case_headers = list(case_static_keys)
case_headers.extend([format_dynamic_key(key) for key in case_dynamic_keys])
workbook.open("Cases", case_headers)
for case_row in case_rows:
workbook.write_row("Cases", tidy_up_case_row(case_row))
return workbook | TypeError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqcase/export.py/export_cases |
@property
def previous(self):
try:
idx = _jump_list_index
next_index = idx + 1
if next_index > 100:
next_index = 100
next_index = min(len(_jump_list) - 1, next_index)
_jump_list_index = next_index
return _jump_list[next_index]
except (IndexError, __HOLE__) as e:
return None | KeyError | dataset/ETHPy150Open guillermooo/Vintageous/vi/jump_list.py/JumpList.previous |
@property
def next(self):
try:
idx = _jump_list_index
next_index = idx - 1
if next_index < 0:
next_index = 0
next_index = min(len(_jump_list) - 1, next_index)
_jump_list_index = next_index
return _jump_list[next_index]
except (IndexError, __HOLE__) as e:
return None | KeyError | dataset/ETHPy150Open guillermooo/Vintageous/vi/jump_list.py/JumpList.next |
@property
def latest(self):
global _current_latest
try:
i = 1 if (_current_latest == 0) else 0
_current_latest = min(len(_jump_list) - 1, i)
return _jump_list[_current_latest]
except (IndexError, __HOLE__) as e:
return None | KeyError | dataset/ETHPy150Open guillermooo/Vintageous/vi/jump_list.py/JumpList.latest |
def _compare_result(self, expected, result, result_str):
matched_value = None
# None
if expected is None:
if result is None:
pass
elif result == u'':
pass # TODO(auggy): known issue Bug#1544720
else:
raise NoMatch('%(result_str)s: Expected None, got %(result)s.'
% {'result_str': result_str, 'result': result})
# dictionary
elif isinstance(expected, dict):
if not isinstance(result, dict):
raise NoMatch('%(result_str)s: %(result)s is not a dict.'
% {'result_str': result_str, 'result': result})
ex_keys = sorted(expected.keys())
res_keys = sorted(result.keys())
if ex_keys != res_keys:
ex_delta = []
res_delta = []
for key in ex_keys:
if key not in res_keys:
ex_delta.append(key)
for key in res_keys:
if key not in ex_keys:
res_delta.append(key)
raise NoMatch(
'Dictionary key mismatch:\n'
'Extra key(s) in template:\n%(ex_delta)s\n'
'Extra key(s) in %(result_str)s:\n%(res_delta)s\n' %
{'ex_delta': ex_delta, 'result_str': result_str,
'res_delta': res_delta})
for key in ex_keys:
# TODO(auggy): pass key name along as well for error reporting
res = self._compare_result(expected[key], result[key],
result_str)
matched_value = res or matched_value
# list
elif isinstance(expected, list):
if not isinstance(result, list):
raise NoMatch(
'%(result_str)s: %(result)s is not a list.' %
{'result_str': result_str, 'result': result})
expected = expected[:]
extra = []
for res_obj in result:
for i, ex_obj in enumerate(expected):
try:
matched_value = self._compare_result(ex_obj,
res_obj,
result_str)
del expected[i]
break
except NoMatch:
pass
else:
extra.append(res_obj)
error = []
if expected:
error.append('Extra list items in template:')
error.extend([repr(o) for o in expected])
if extra:
error.append('Extra list items in %(result_str)s:' %
{'result_str': result_str})
error.extend([repr(o) for o in extra])
if error:
raise NoMatch('\n'.join(error))
# template string
elif isinstance(expected, six.string_types) and '%' in expected:
# NOTE(vish): escape stuff for regex
for char in '[]<>?':
expected = expected.replace(char, '\\%s' % char)
# NOTE(vish): special handling of subs that are not quoted. We are
# expecting an int but we had to pass in a string
# so the json would parse properly.
if expected.startswith("%(int:"):
result = str(result)
expected = expected.replace('int:', '')
expected = expected % self.subs
expected = '^%s$' % expected
match = re.match(expected, result)
if not match:
raise NoMatch(
'Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: %(result)s' %
{'expected': expected, 'result_str': result_str,
'result': result})
try:
matched_value = match.group('id')
except __HOLE__:
if match.groups():
matched_value = match.groups()[0]
# string
elif isinstance(expected, six.string_types):
# NOTE(danms): Ignore whitespace in this comparison
expected = expected.strip()
if isinstance(result, six.string_types):
result = result.strip()
if expected != result:
# NOTE(tdurakov):this attempt to parse string as JSON
# is needed for correct comparison of hypervisor.cpu_info,
# which is stringified JSON object
#
# TODO(tdurakov): remove this check as soon as
# hypervisor.cpu_info become common JSON object in REST API.
try:
expected = objectify(expected)
result = objectify(result)
return self._compare_result(expected, result,
result_str)
except ValueError:
pass
raise NoMatch(
'Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: '
'%(result)s' % {'expected': expected,
'result_str': result_str,
'result': result})
# int
elif isinstance(expected, (six.integer_types, float)):
if expected != result:
raise NoMatch(
'Values do not match:\n'
'Template: %(expected)s\n%(result_str)s: '
'%(result)s' % {'expected': expected,
'result_str': result_str,
'result': result})
else:
raise ValueError(
'Unexpected type %(expected_type)s'
% {'expected_type': type(expected)})
return matched_value | IndexError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/functional/api_samples_test_base.py/ApiSampleTestBase._compare_result |
def start(app, args):
app.check()
if os.path.exists(app.pid_path()):
print "~ Oops. %s is already started! (or delete %s)" % (os.path.normpath(app.path), os.path.normpath(app.pid_path()))
print "~"
sys.exit(1)
sysout = app.readConf('application.log.system.out')
sysout = sysout!='false' and sysout!='off'
if not sysout:
sout = None
else:
sout = open(os.path.join(app.log_path(), 'system.out'), 'w')
try:
pid = subprocess.Popen(app.java_cmd(args), stdout=sout, env=os.environ).pid
except __HOLE__:
print "Could not execute the java executable, please make sure the JAVA_HOME environment variable is set properly (the java executable should reside at JAVA_HOME/bin/java). "
sys.exit(-1)
print "~ OK, %s is started" % os.path.normpath(app.path)
if sysout:
print "~ output is redirected to %s" % os.path.normpath(os.path.join(app.log_path(), 'system.out'))
pid_file = open(app.pid_path(), 'w')
pid_file.write(str(pid))
print "~ pid is %s" % pid
print "~" | OSError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/framework/pym/play/commands/daemon.py/start |
def restart(app, args):
app.check()
if not os.path.exists(app.pid_path()):
print "~ Oops! %s is not started (server.pid not found)" % os.path.normpath(app.path)
print "~"
else:
pid = open(app.pid_path()).readline().strip()
os.remove(app.pid_path())
kill(pid)
sysout = app.readConf('application.log.system.out')
sysout = sysout!='false' and sysout!='off'
java_cmd = app.java_cmd(args)
if not sysout:
sout = None
else:
sout = open(os.path.join(app.log_path(), 'system.out'), 'w')
try:
pid = subprocess.Popen(java_cmd, stdout=sout, env=os.environ).pid
except __HOLE__:
print "Could not execute the java executable, please make sure the JAVA_HOME environment variable is set properly (the java executable should reside at JAVA_HOME/bin/java). "
sys.exit(-1)
print "~ OK, %s is restarted" % os.path.normpath(app.path)
if sysout:
print "~ output is redirected to %s" % os.path.normpath(os.path.join(app.log_path(), 'system.out'))
pid_file = open(app.pid_path(), 'w')
pid_file.write(str(pid))
print "~ New pid is %s" % pid
print "~"
sys.exit(0) | OSError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/framework/pym/play/commands/daemon.py/restart |
def out(app):
app.check()
if not os.path.exists(os.path.join(app.log_path(), 'system.out')):
print "~ Oops! %s not found" % os.path.normpath(os.path.join(app.log_path(), 'system.out'))
print "~"
sys.exit(-1)
sout = open(os.path.join(app.log_path(), 'system.out'), 'r')
try:
sout.seek(-5000, os.SEEK_END)
except __HOLE__:
sout.seek(0)
while True:
where = sout.tell()
line = sout.readline().strip()
if not line:
time.sleep(1)
sout.seek(where)
else:
print line | IOError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/framework/pym/play/commands/daemon.py/out |
def kill(pid):
if os.name == 'nt':
import ctypes
handle = ctypes.windll.kernel32.OpenProcess(1, False, int(pid))
if not ctypes.windll.kernel32.TerminateProcess(handle, 0):
print "~ Cannot kill the process with pid %s (ERROR %s)" % (pid, ctypes.windll.kernel32.GetLastError())
print "~ "
sys.exit(-1)
else:
try:
os.kill(int(pid), 15)
except __HOLE__:
print "~ Play was not running (Process id %s not found)" % pid
print "~"
sys.exit(-1) | OSError | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/framework/pym/play/commands/daemon.py/kill |
def _get_requirements(path):
try:
with open(path) as f:
packages = f.read().splitlines()
except (IOError, __HOLE__) as ex:
raise RuntimeError("Can't open file with requirements: %r", ex)
packages = (p.strip() for p in packages if not re.match("^\s*#", p))
packages = list(filter(None, packages))
return packages | OSError | dataset/ETHPy150Open projectatomic/atomic-reactor/setup.py/_get_requirements |
def valid_bits(bits, width, word_sep=''):
"""
:param bits: A network address in a delimited binary string format.
:param width: Maximum width (in bits) of a network address (excluding
delimiters).
:param word_sep: (optional) character or string used to delimit word
groups (default: '', no separator).
:return: ``True`` if network address is valid, ``False`` otherwise.
"""
if not _is_str(bits):
return False
if word_sep != '':
bits = bits.replace(word_sep, '')
if len(bits) != width:
return False
max_int = 2 ** width - 1
try:
if 0 <= int(bits, 2) <= max_int:
return True
except __HOLE__:
pass
return False | ValueError | dataset/ETHPy150Open drkjam/netaddr/netaddr/strategy/__init__.py/valid_bits |
def valid_bin(bin_val, width):
"""
:param bin_val: A network address in Python's binary representation format
('0bxxx').
:param width: Maximum width (in bits) of a network address (excluding
delimiters).
:return: ``True`` if network address is valid, ``False`` otherwise.
"""
if not _is_str(bin_val):
return False
if not bin_val.startswith('0b'):
return False
bin_val = bin_val.replace('0b', '')
if len(bin_val) > width:
return False
max_int = 2 ** width - 1
try:
if 0 <= int(bin_val, 2) <= max_int:
return True
except __HOLE__:
pass
return False | ValueError | dataset/ETHPy150Open drkjam/netaddr/netaddr/strategy/__init__.py/valid_bin |
def int_to_bin(int_val, width):
"""
:param int_val: An unsigned integer.
:param width: Maximum allowed width (in bits) of a unsigned integer.
:return: Equivalent string value in Python's binary representation format
('0bxxx').
"""
bin_tokens = []
try:
# Python 2.6.x and upwards.
bin_val = bin(int_val)
except __HOLE__:
# Python 2.4.x and 2.5.x
i = int_val
while i > 0:
word = i & 0xff
bin_tokens.append(BYTES_TO_BITS[word])
i >>= 8
bin_tokens.reverse()
bin_val = '0b' + _re.sub(r'^[0]+([01]+)$', r'\1', ''.join(bin_tokens))
if len(bin_val[2:]) > width:
raise IndexError('binary string out of bounds: %s!' % bin_val)
return bin_val | NameError | dataset/ETHPy150Open drkjam/netaddr/netaddr/strategy/__init__.py/int_to_bin |
def _run_process(self, command, *args, **kwargs):
stdout = kwargs.get('stdout', sys.stdout)
stderr = kwargs.get('stderr', sys.stderr)
kwargs.setdefault('cwd', self.path)
if isinstance(command, basestring):
command = shlex.split(command)
command = map(str, command)
env = os.environ.copy()
env['PYTHONUNBUFFERED'] = '1'
if kwargs.get('env'):
for key, value in kwargs['env'].iteritems():
env[key] = value
kwargs['env'] = env
kwargs['bufsize'] = 0
self.log.info('Running {}'.format(command))
try:
proc = Popen(command, *args, **kwargs)
except __HOLE__ as exc:
if not self.whereis(command[0], env):
msg = 'ERROR: Command not found: {}'.format(command[0])
else:
msg = traceback.format_exc()
raise CommandError(command, 1, stdout=None, stderr=msg)
return proc | OSError | dataset/ETHPy150Open getsentry/freight/freight/utils/workspace.py/Workspace._run_process |
def import_simplejson():
try:
import simplejson as json
except __HOLE__:
try:
import json # Python 2.6+
except ImportError:
try:
# Google App Engine
from django.utils import simplejson as json
except ImportError:
raise ImportError("Can't load a json library")
return json | ImportError | dataset/ETHPy150Open tweepy/tweepy/tweepy/utils.py/import_simplejson |
def __init__(self, trg_queue, item_id, max_tries=None, ttl=None,
lock=None, no_open=False, host=None):
'''Construct an FSQWorkItem object from an item_id (file-name), and
queue-name. The lock kwarg will override the default locking
preference (taken from environment).'''
self.id = item_id
self.queue = trg_queue
self.max_tries = _c.FSQ_MAX_TRIES if max_tries is None else max_tries
self.ttl = _c.FSQ_TTL if ttl is None else ttl
self.lock = _c.FSQ_LOCK if lock is None else lock
self.item = None
self.host = host
# open file immediately
if not no_open:
self.open()
try:
self.delimiter, arguments = deconstruct(item_id)
try:
# construct datetime.datetime from enqueued_at
self.enqueued_at = datetime.datetime.strptime(arguments[0],
_c.FSQ_TIMEFMT)
self.entropy = arguments[1]
self.pid = arguments[2]
self.hostname = arguments[3]
self.tries = arguments[4]
self.arguments = tuple(arguments[5:])
except __HOLE__, e:
raise FSQMalformedEntryError(errno.EINVAL, u'needed at least'\
u' 4 arguments to unpack, got:'\
u' {0}'.format(len(arguments)))
except ValueError, e:
raise FSQTimeFmtError(errno.EINVAL, u'invalid date string'\
u' for strptime fmt {0}:'\
u' {1}'.format(_c.FSQ_TIMEFMT,
arguments[0]))
try:
self.tries = int(self.tries)
except ValueError, e:
raise FSQTimeFmtError(errno.EINVAL, u'tries must be an int,'\
u' not {0}: {1}'.format(
self.tries.__class__.__name__,
self.tries))
try:
check_ttl_max_tries(self.tries, self.enqueued_at,
self.max_tries, self.ttl)
except (FSQMaxTriesError, FSQTTLExpiredError, ), e:
e.strerror = u': '.join([
e.strerror,
u'for item {0}; failed permanently'.format(self.id),
])
raise e
except Exception, e:
try:
# unhandled exceptions are perm failures
self.fail_perm()
finally:
self.close()
raise e | IndexError | dataset/ETHPy150Open axialmarket/fsq/fsq/items.py/FSQWorkItem.__init__ |
def open(self):
self.close()
try:
self.item = rationalize_file(fsq_path.item(self.queue, self.id,
host=self.host),
_c.FSQ_CHARSET, lock=self.lock)
except (OSError, __HOLE__, ), e:
if e.errno == errno.ENOENT:
raise FSQWorkItemError(e.errno, u'no such item in queue {0}:'\
u' {1}'.format(self.queue, self.id))
raise FSQWorkItemError(e.errno, wrap_io_os_err(e)) | IOError | dataset/ETHPy150Open axialmarket/fsq/fsq/items.py/FSQWorkItem.open |
def _create_config(self, params):
sys.stdout.write(
'Creating the on-premises instance configuration file... '
)
try:
os.makedirs(params.system.CONFIG_DIR)
except __HOLE__ as e:
if e.errno != errno.EEXIST:
raise e
if params.config_file != params.system.CONFIG_PATH:
shutil.copyfile(params.config_file, params.system.CONFIG_PATH)
sys.stdout.write('DONE\n') | OSError | dataset/ETHPy150Open aws/aws-cli/awscli/customizations/codedeploy/install.py/Install._create_config |
def main():
printLicenseInfo()
# for easier parsing, adds free --help and --version
# optparse (v2.3-v2.7) was chosen over argparse (v2.7+) for compatibility (and relative similarity) reasons
# and over getopt(v?) for additional functionality
parser = optparse.OptionParser( usage='usage: %prog [options] <manga name>',
version=('Manga Downloader %s' % VERSION) )
parser.set_defaults(
all_chapters_FLAG = False,
auto = False,
conversion_FLAG = False,
convert_Directory = False,
device = 'Kindle 3',
downloadFormat = '.cbz',
downloadPath = 'DEFAULT_VALUE',
inputDir = None,
outputDir = 'DEFAULT_VALUE',
overwrite_FLAG = False,
verbose_FLAG = False,
timeLogging_FLAG = False,
maxChapterThreads = 3,
useShortName = False,
spaceToken = '.',
proxy = None,
siteSelect = 0
)
parser.add_option( '--all',
action = 'store_true',
dest = 'all_chapters_FLAG',
help = 'Download all available chapters.' )
parser.add_option( '-d', '--directory',
dest = 'downloadPath',
help = 'The destination download directory. Defaults to the directory of the script.' )
parser.add_option( '--overwrite',
action = 'store_true',
dest = 'overwrite_FLAG',
help = 'Overwrites previous copies of downloaded chapters.' )
parser.add_option( '--verbose',
action = 'store_true',
dest = 'verbose_FLAG',
help = 'Verbose Output.' )
parser.add_option( '-x','--xml',
dest = 'xmlfile_path',
help = 'Parses the .xml file and downloads all chapters newer than the last chapter downloaded for the listed mangas.' )
parser.add_option( '-c', '--convertFiles',
action = 'store_true',
dest = 'conversion_FLAG',
help = 'Converts downloaded files to a Format/Size acceptable to the device specified by the --device parameter.' )
parser.add_option( '--device',
dest = 'device',
help = 'Specifies the conversion device. Omitting this option default to %default.' )
parser.add_option( '--convertDirectory',
action = 'store_true',
dest = 'convert_Directory',
help = 'Converts the image files stored in the directory specified by --inputDirectory. Stores the converted images in the directory specified by --outputDirectory' )
parser.add_option( '--inputDirectory',
dest = 'inputDir',
help = 'The directory containing the images to convert when --convertDirectory is specified.' )
parser.add_option( '--outputDirectory',
dest = 'outputDir',
help = 'The directory to store the images when --convertDirectory is specified.' )
parser.add_option( '-z', '--zip',
action = 'store_const',
dest = 'downloadFormat',
const = '.zip',
help = 'Downloads using .zip compression. Omitting this option defaults to %default.' )
parser.add_option( '-t', '--threads',
dest = 'maxChapterThreads',
help = 'Limits the number of chapter threads to the value specified.' )
parser.add_option( '--timeLogging',
action = 'store_true',
dest = 'timeLogging_FLAG',
help = 'Output time logging.' )
parser.add_option( '--useShortName',
action = 'store_true',
dest = 'useShortName_FLAG',
help = 'To support devices that limit the size of the filename, this parameter uses a short name' )
parser.add_option( '--spaceToken',
dest = 'spaceToken',
help = 'Specifies the character used to replace spaces in the manga name.' )
parser.add_option( '--proxy',
dest = 'proxy',
help = 'Specifies the proxy.' )
parser.add_option( '-s', '--site',
dest = 'siteSelect',
help = 'Specifies the site to download from.' )
(options, args) = parser.parse_args()
try:
options.siteSelect = int(options.siteSelect)
except:
options.siteSelect = 0
try:
options.maxChapterThreads = int(options.maxChapterThreads)
except:
options.maxChapterThreads = 2
if (options.maxChapterThreads <= 0):
options.maxChapterThreads = 2;
if(len(args) == 0 and ( not (options.convert_Directory or options.xmlfile_path != None) )):
parser.error('Manga not specified.')
#if(len(args) > 1):
# parser.error('Possible multiple mangas specified, please select one. (Did you forget to put quotes around a multi-word manga?)')
SetDownloadPathToName_Flag = False
SetOutputPathToDefault_Flag = False
if(len(args) > 0):
# Default Directory is the ./MangaName
if (options.downloadPath == 'DEFAULT_VALUE'):
SetDownloadPathToName_Flag = True
# Default outputDir is the ./MangaName
if (options.outputDir == 'DEFAULT_VALUE'):
SetOutputPathToDefault_Flag = True
PILAvailable = isImageLibAvailable()
# Check if PIL Library is available if either of convert Flags are set
if ((not PILAvailable) and (options.convert_Directory or options.conversion_FLAG)):
print ("\nConversion Functionality Not available.\nMust install the PIL (Python Image Library)")
sys.exit()
else:
if (PILAvailable):
from ConvertPackage.ConvertFile import convertFile
if (options.convert_Directory):
options.inputDir = os.path.abspath(options.inputDir)
# Changes the working directory to the script location
if (os.path.dirname(sys.argv[0]) != ""):
os.chdir(os.path.dirname(sys.argv[0]))
options.outputMgr = progressBarManager()
options.outputMgr.start()
try:
if (options.convert_Directory):
if ( options.outputDir == 'DEFAULT_VALUE' ):
options.outputDir = '.'
print("Converting Files: %s" % options.inputDir)
convertFile.convert(options.outputMgr, options.inputDir, options.outputDir, options.device, options.verbose_FLAG)
elif options.xmlfile_path != None:
xmlParser = MangaXmlParser(options)
xmlParser.downloadManga()
else:
threadPool = []
for manga in args:
print( manga )
options.manga = manga
if SetDownloadPathToName_Flag:
options.downloadPath = ('./' + fixFormatting(options.manga, options.spaceToken))
if SetOutputPathToDefault_Flag:
options.outputDir = options.downloadPath
options.downloadPath = os.path.realpath(options.downloadPath) + os.sep
# site selection
if(options.siteSelect == 0):
print('Which site?')
for i in siteDict:
print(siteDict[i][1])
# Python3 fix - removal of raw_input()
try:
options.siteSelect = raw_input()
except NameError:
options.siteSelect = input()
try:
options.site = siteDict[int(options.siteSelect)][0]
except __HOLE__:
raise InvalidSite('Site selection invalid.')
threadPool.append(SiteParserThread(options, None, None))
for thread in threadPool:
thread.start()
thread.join()
finally:
# Must always stop the manager
options.outputMgr.stop() | KeyError | dataset/ETHPy150Open jiaweihli/manga_downloader/src/manga.py/main |
def __init__(self, which_set, shuffle=False,
start=None, stop=None, axes=['b', 0, 1, 'c'],
preprocessor=None, fit_preprocessor=False,
fit_test_preprocessor=False):
self.args = locals()
if which_set not in ['train', 'valid', 'test']:
raise ValueError('Unrecognized which_set value "%s".' %
(which_set,) + '". Valid values are ' +
'["train", "valid", "test"].')
def dimshuffle(b01c):
default = ('b', 0, 1, 'c')
return b01c.transpose(*[default.index(axis) for axis in axes])
if control.get_load_data():
path = "${PYLEARN2_DATA_PATH}/binarized_mnist/binarized_mnist_" + \
which_set + ".npy"
im_path = serial.preprocess(path)
# Locally cache the files before reading them
datasetCache = cache.datasetCache
im_path = datasetCache.cache_file(im_path)
try:
X = serial.load(im_path)
except __HOLE__:
raise NotInstalledError("BinarizedMNIST data files cannot be "
"found in ${PYLEARN2_DATA_PATH}. Run "
"pylearn2/scripts/datasets/"
"download_binarized_mnist.py to get "
"the data")
else:
if which_set == 'train':
size = 50000
else:
size = 10000
X = numpy.random.binomial(n=1, p=0.5, size=(size, 28 ** 2))
m, d = X.shape
assert d == 28 ** 2
if which_set == 'train':
assert m == 50000
else:
assert m == 10000
if shuffle:
self.shuffle_rng = make_np_rng(None, [1, 2, 3],
which_method="shuffle")
for i in xrange(X.shape[0]):
j = self.shuffle_rng.randint(m)
# Copy ensures that memory is not aliased.
tmp = X[i, :].copy()
X[i, :] = X[j, :]
X[j, :] = tmp
super(BinarizedMNIST, self).__init__(
X=X,
view_converter=DefaultViewConverter(shape=(28, 28, 1))
)
assert not numpy.any(numpy.isnan(self.X))
if start is not None:
assert start >= 0
if stop > self.X.shape[0]:
raise ValueError('stop=' + str(stop) + '>' +
'm=' + str(self.X.shape[0]))
assert stop > start
self.X = self.X[start:stop, :]
if self.X.shape[0] != stop - start:
raise ValueError("X.shape[0]: %d. start: %d stop: %d"
% (self.X.shape[0], start, stop))
if which_set == 'test':
assert fit_test_preprocessor is None or \
(fit_preprocessor == fit_test_preprocessor)
if self.X is not None and preprocessor:
preprocessor.apply(self, fit_preprocessor) | IOError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/datasets/binarized_mnist.py/BinarizedMNIST.__init__ |
def to_python(self, value):
"""
Transforms the value to a Geometry object.
"""
try:
return GEOSGeometry(value)
except (GEOSException, ValueError, __HOLE__):
raise forms.ValidationError(self.error_messages['invalid_geom']) | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/gis/forms/fields.py/GeometryField.to_python |
def wait_one(self):
"""Waits until this worker has finished one work item or died."""
while True:
try:
item = self.output_queue.get(True, self.polltime)
except Queue.Empty:
continue
except __HOLE__:
LOGGER.debug('Exiting')
return
else:
item.check_result()
return | KeyboardInterrupt | dataset/ETHPy150Open bslatkin/dpxdt/dpxdt/client/workers.py/WorkflowThread.wait_one |
def _progress_workflow(self, item, workflow, generator):
try:
try:
error = item is not None and item.error
if error:
LOGGER.debug('Throwing workflow=%r error=%r',
workflow, error)
next_item = generator.throw(*error)
elif isinstance(item, WorkflowItem) and item.done:
LOGGER.debug(
'Sending workflow=%r finished item=%r',
workflow, item)
next_item = generator.send(item.result)
else:
LOGGER.debug(
'Sending workflow=%r finished item=%r',
workflow, item)
next_item = generator.send(item)
except __HOLE__:
LOGGER.debug('Exhausted workflow=%r', workflow)
workflow.done = True
except Return as e:
LOGGER.debug('Return from workflow=%r result=%r',
workflow, e.result)
workflow.done = True
workflow.result = e.result
except Exception as e:
LOGGER.exception(
'Error in workflow=%r from item=%r, error=%r',
workflow, item, error)
workflow.done = True
workflow.error = sys.exc_info()
else:
barrier = Barrier(workflow, generator, next_item)
self.pending.enqueue(barrier)
finally:
if workflow.done:
if workflow.root:
# Root workflow finished. This goes to the output
# queue so it can be received by the main thread.
return workflow
else:
# Sub-workflow finished. Reinject it into the
# workflow so a pending parent can catch it.
self.input_queue.put(workflow)
return None | StopIteration | dataset/ETHPy150Open bslatkin/dpxdt/dpxdt/client/workers.py/WorkflowThread._progress_workflow |
def handle_item(self, item):
if isinstance(item, WorkflowItem) and not item.done:
workflow = item
try:
generator = item.run(*item.args, **item.kwargs)
except __HOLE__ as e:
raise TypeError('Bad workflow function item=%r error=%s' % (
item, str(e)))
item = None
else:
barrier = self.pending.dequeue(item)
if barrier is None:
LOGGER.debug('Could not find barrier for finished item=%r',
item)
return None
item = barrier.get_item()
workflow = barrier.workflow
generator = barrier.generator
return self._progress_workflow(item, workflow, generator) | TypeError | dataset/ETHPy150Open bslatkin/dpxdt/dpxdt/client/workers.py/WorkflowThread.handle_item |
def parse_keyval_args(func):
@functools.wraps(func)
def wrapper(inst, args):
cmd = func.__name__[3:]
try:
d = dict(arg.split('=') for arg in args.split())
except ValueError:
# there were probably spaces around the '='
print("Invalid input: Bad arg list, or remove spaces from around "
"the '=' sign in your argument(s)")
inst.do_help(cmd)
else:
try:
return func(inst, **d)
except __HOLE__ as out:
print(out)
inst.do_help(cmd)
return wrapper | TypeError | dataset/ETHPy150Open bkjones/bunnyq/bunnyq.py/parse_keyval_args |
def request(self, call, *args):
request = methodcaller(call, *args)
try:
val = request(self.srv)
except api.PermissionError:
whoami = self.srv.get_whoami()
print("You don't have sufficient permissions"
" Login info: %s" % repr(whoami))
return
except (__HOLE__, IOError) as out:
print(repr(type(out)), out)
except http.HTTPError as out:
print out
except Exception as out:
print(repr(type(out)), out)
else:
return val | ValueError | dataset/ETHPy150Open bkjones/bunnyq/bunnyq.py/Bunny.request |
def get_value(self, json_serializable=False):
""" Retrieve the value
"""
if json_serializable:
try:
json.dumps(self.value)
return self.value
except __HOLE__ as e:
try:
if type(self.value) == list: # for iterables
return [{
"value": v["value"].json(),
"tags": v["tags"],
} for v in self.value]
else: # for values explicitly defining json method, e.g. parameters
return self.value.json()
except AttributeError:
try: # for numpy arrays
return self.value.tolist()
except AttributeError:
raise e
raise e
else:
return self.value | TypeError | dataset/ETHPy150Open impactlab/eemeter/eemeter/meter/base.py/DataContainer.get_value |
def json(self):
"""Serializes data. Non-serializable outputs are replaced with
"NOT_SERIALIZABLE".
"""
json_data = {}
for item in self.iteritems():
try:
value = item.get_value(json_serializable=True)
except __HOLE__:
value = "NOT_SERIALIZABLE"
item_data = {
"tags": list(item.tags),
"value": value,
}
if item.name in json_data:
json_data[item.name].append(item_data)
else:
json_data[item.name] = [item_data]
return json_data | TypeError | dataset/ETHPy150Open impactlab/eemeter/eemeter/meter/base.py/DataCollection.json |
def awaitTermination(self, timeout=None):
if self.scheduler is None:
raise RuntimeError('StreamimgContext not started')
try:
deadline = time.time() + timeout if timeout is not None else None
while True:
is_terminated = self._runOnce()
if is_terminated or (
deadline is not None and time.time() > deadline):
break
if self.batchCallback:
self.batchCallback()
except __HOLE__:
pass
finally:
self.sc.stop()
logger.info("StreamingContext stopped successfully") | KeyboardInterrupt | dataset/ETHPy150Open douban/dpark/dpark/dstream.py/StreamingContext.awaitTermination |
def runOnce(self):
try:
t, v = self._queue.popleft()
except __HOLE__:
time.sleep(0.1)
return False
if t == _STOP:
return True
self.generateRDDs(v)
return False | IndexError | dataset/ETHPy150Open douban/dpark/dpark/dstream.py/Scheduler.runOnce |
def updateCheckpointData(self, time):
newRdds = [(t, rdd.checkpoint_path) for t, rdd in self.generatedRDDs.items()
if rdd and rdd.checkpoint_path]
if newRdds:
oldRdds = self.checkpointData
self.checkpointData = dict(newRdds)
for t, p in oldRdds.iteritems():
if t not in self.checkpointData:
try:
shutil.rmtree(p)
except __HOLE__:
pass
for dep in self.dependencies:
dep.updateCheckpointData(time)
logger.info(
"updated checkpoint data for time %s (%d)",
time,
len(newRdds)) | OSError | dataset/ETHPy150Open douban/dpark/dpark/dstream.py/DStream.updateCheckpointData |
@cache_page(60 * 5)
def archive(request, year=None, month=None, day=None, page=1, mediatype=None):
"""View a paginated list of images by year, month or day."""
try:
page = int(page)
if year:
year = int(year)
if month:
month = int(month)
if day:
day = int(day)
except __HOLE__:
raise Http404
site = Site.objects.get_current()
try:
if mediatype == 'photo':
images = Photo.objects.filter(section__publication__site=site)
url_base = '/photos/'
elif mediatype == 'editorialcartoon':
images = EditorialCartoon.objects.filter(section__publication__site=site)
url_base = '/editorial-cartoons/'
elif mediatype == 'graphic':
images = Graphic.objects.filter(section__publication__site=site)
url_base = '/graphics/'
elif mediatype == 'layout':
images = Layout.objects.filter(section__publication__site=site)
url_base = '/layouts/'
elif mediatype == 'slideshow':
images = Slideshow.objects.filter(publication__site=site)
url_base = '/slideshows/'
elif mediatype == 'video':
images = Video.objects.filter(publication__site=site)
url_base = '/videos/'
elif mediatype == 'audioclip':
images = AudioClip.objects.filter(publication__site=site)
url_base = '/audio/'
else:
raise StandardError("mediatype should be 'photo', 'graphic', 'layout', 'slideshow', 'video' or 'audioclip'")
except:
raise Http404
mediatype = mediatype.capitalize()
if mediatype == 'Audioclip':
mediatype = "Audio clip"
elif mediatype == 'Editorialcartoon':
mediatype = "Editorial cartoon"
if not year:
images = images
archive_name = "%s " % mediatype
elif not month:
images = images.filter(pub_date__year=year)
archive_name = "%ss from %s" % (mediatype, year)
elif not day:
images = images.filter(pub_date__year=year, pub_date__month=month)
archive_name = "%ss from %s" % (mediatype, date(year, month, 1).strftime("%B %Y"))
else:
images = images.filter(pub_date=date(year, month, day))
archive_name = "%ss from %s" % (mediatype, date(year, month, day).strftime("%B %d, %Y"))
paginator = Paginator(images, 10)
try:
archive_page = paginator.page(page)
except (EmptyPage, InvalidPage):
raise Http404
if year:
url_base += '%s/' % year
if month:
url_base += '%s/' % month
if day:
url_base += '%s/' % day
next_page_url = '%sp%s/' % (url_base, page + 1)
previous_page_url = '%sp%s/' % (url_base, page - 1)
page = {
'archive_name': archive_name,
'archive_page': archive_page,
'next_page_url': next_page_url,
'previous_page_url': previous_page_url
}
return render_to_response('core/image_archives/archive.html', page, context_instance=RequestContext(request)) | ValueError | dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/core/image_views/views.py/archive |
@cache_page(60 * 5)
def detail(request, year=None, month=None, day=None, id=None, mediatype=None):
"""View a particular image."""
site = Site.objects.get_current()
# From an optimization standpoint, it makes no real sense to convert year,
# month and day to integers outside the try/except block; since only one
# mediatype can be chosen at any given time, this conversion will only
# happen once anyway.
try:
if mediatype == 'photo':
# image = Photo.objects.filter(section__publication__site=site).filter(pub_date=date(int(year), int(month), int(day))).get(id=int(id))
image = Photo.objects.get(id=int(id))
elif mediatype == 'editorialcartoon':
# image = EditorialCartoon.objects.filter(section__publication__site=site).filter(pub_date=date(int(year), int(month), int(day))).get(id=int(id))
image = EditorialCartoon.objects.get(id=int(id))
elif mediatype == 'graphic':
# image = Graphic.objects.filter(section__publication__site=site).filter(pub_date=date(int(year), int(month), int(day))).get(id=int(id))
image = Graphic.objects.get(id=int(id))
elif mediatype == 'layout':
# image = Layout.objects.filter(section__publication__site=site).filter(pub_date=date(int(year), int(month), int(day))).get(id=int(id))
image = Layout.objects.get(id=int(id))
else:
raise StandardError("mediatype should be 'photo', 'graphic' or 'layout'")
except __HOLE__, ValueError:
raise Http404
page = {
'image': image
}
return render_to_response('photography/image_detail.html', page, context_instance=RequestContext(request)) | ObjectDoesNotExist | dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/core/image_views/views.py/detail |
def __getattr__(self, attr, *args):
try:
return getattr(self.__class__, attr, *args)
except __HOLE__:
return getattr(self.get_query_set(), attr, *args) | AttributeError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/txcommon/db/models.py/ChainerManager.__getattr__ |
def to_python(self, value):
if type(value) == list:
return self._replace(value)
if type(value) == unicode and value.startswith('[') and \
value.endswith(']'):
try:
return self._replace(eval(value))
except __HOLE__:
pass
if value == '':
return []
if value is None:
return None
return self._replace(re.split(r'(?<!\\)\:', value)) | NameError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/txcommon/db/models.py/ListCharField.to_python |
def db_type(self, connection):
db_types = {'django.db.backends.mysql':'longblob',
'django.db.backends.sqlite3':'blob',
'django.db.backends.postgres':'text',
'django.db.backends.postgresql_psycopg2':'text'}
try:
return db_types[connection.settings_dict['ENGINE']]
except __HOLE__, e:
print str(e)
raise Exception, '%s currently works only with: %s' % (
self.__class__.__name__,', '.join(db_types.keys())) | KeyError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/txcommon/db/models.py/CompressedTextField.db_type |
def load_class(class_path, setting_name=None):
"""
Loads a class given a class_path. The setting value may be a string or a
tuple.
The setting_name parameter is only there for pretty error output, and
therefore is optional
"""
if not isinstance(class_path, six.string_types):
try:
class_path, app_label = class_path
except:
if setting_name:
raise exceptions.ImproperlyConfigured(CLASS_PATH_ERROR % (
setting_name, setting_name))
else:
raise exceptions.ImproperlyConfigured(CLASS_PATH_ERROR % (
'this setting', 'It'))
try:
class_module, class_name = class_path.rsplit('.', 1)
except __HOLE__:
if setting_name:
txt = '%s isn\'t a valid module. Check your %s setting' % (
class_path, setting_name)
else:
txt = '%s isn\'t a valid module.' % class_path
raise exceptions.ImproperlyConfigured(txt)
try:
mod = import_module(class_module)
except ImportError as e:
if setting_name:
txt = 'Error importing backend %s: "%s". Check your %s setting' % (
class_module, e, setting_name)
else:
txt = 'Error importing backend %s: "%s".' % (class_module, e)
raise exceptions.ImproperlyConfigured(txt)
try:
clazz = getattr(mod, class_name)
except AttributeError:
if setting_name:
txt = ('Backend module "%s" does not define a "%s" class. Check'
' your %s setting' % (class_module, class_name,
setting_name))
else:
txt = 'Backend module "%s" does not define a "%s" class.' % (
class_module, class_name)
raise exceptions.ImproperlyConfigured(txt)
return clazz | ValueError | dataset/ETHPy150Open ulule/django-courriers/courriers/utils.py/load_class |
def CloseFdNoError(fd, retries=5):
"""Close a file descriptor ignoring errors.
@type fd: int
@param fd: the file descriptor
@type retries: int
@param retries: how many retries to make, in case we get any
other error than EBADF
"""
try:
os.close(fd)
except __HOLE__, err:
if err.errno != errno.EBADF:
if retries > 0:
CloseFdNoError(fd, retries - 1)
# else either it's closed already or we're out of retries, so we
# ignore this and go on | OSError | dataset/ETHPy150Open ganeti/ganeti/lib/utils/wrapper.py/CloseFdNoError |
def ResetTempfileModule(_time=time.time):
"""Resets the random name generator of the tempfile module.
This function should be called after C{os.fork} in the child process to
ensure it creates a newly seeded random generator. Otherwise it would
generate the same random parts as the parent process. If several processes
race for the creation of a temporary file, this could lead to one not getting
a temporary name.
"""
# pylint: disable=W0212
if ((sys.hexversion >= 0x020703F0 and sys.hexversion < 0x03000000) or
sys.hexversion >= 0x030203F0):
# Python 2.7 automatically resets the RNG on pid changes (i.e. forking)
return
try:
lock = tempfile._once_lock
lock.acquire()
try:
# Re-seed random name generator
if tempfile._name_sequence:
tempfile._name_sequence.rng.seed(hash(_time()) ^ os.getpid())
finally:
lock.release()
except __HOLE__:
logging.critical("The tempfile module misses at least one of the"
" '_once_lock' and '_name_sequence' attributes") | AttributeError | dataset/ETHPy150Open ganeti/ganeti/lib/utils/wrapper.py/ResetTempfileModule |
def parse_timestamp(s):
''' Returns (datetime, tz offset in minutes) or (None, None). '''
m = re.match(""" ^
(?P<year>-?[0-9]{4}) - (?P<month>[0-9]{2}) - (?P<day>[0-9]{2})
T (?P<hour>[0-9]{2}) : (?P<minute>[0-9]{2}) : (?P<second>[0-9]{2})
(?P<microsecond>\.[0-9]{1,6})?
(?P<tz>
Z | (?P<tz_hr>[-+][0-9]{2}) : (?P<tz_min>[0-9]{2})
)?
$ """, s, re.X)
if m is not None:
values = m.groupdict()
if values["tz"] in ("Z", None):
tz = 0
else:
tz = int(values["tz_hr"]) * 60 + int(values["tz_min"])
if values["microsecond"] is None:
values["microsecond"] = 0
else:
values["microsecond"] = values["microsecond"][1:]
values["microsecond"] += "0" * (6 - len(values["microsecond"]))
values = dict((k, int(v)) for k, v in list(values.items())
if not k.startswith("tz"))
try:
return datetime(**values), tz
except __HOLE__:
pass
return None, None | ValueError | dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/data_management/toolboxes/scripts/ImportEnemySightingsXML.py/parse_timestamp |
def _try_timestamp(x):
try:
ts = pd.Timestamp(x)
return ts.to_pydatetime()
except (ValueError, __HOLE__):
return x | TypeError | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/_try_timestamp |
def _try_unix_timestamp(x):
try:
ts = pd.Timestamp.fromtimestamp(int(x))
return ts.to_pydatetime()
except (__HOLE__, TypeError):
return x | ValueError | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/_try_unix_timestamp |
def _try_boolean(x):
try:
x = x.lower()
if x in ('true', 'yes'):
return True
elif x in ('false', 'no'):
return False
return x
except (ValueError, __HOLE__):
return x | TypeError | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/_try_boolean |
def _try_int(x):
try:
return int(x)
except (ValueError, __HOLE__):
return x | TypeError | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/_try_int |
def _parse_storage_info(self):
self.storage = {}
while True:
# end of the road
try:
tup = self._next_tuple()
except __HOLE__:
break
orig_key = tup[0].strip(':')
key = _clean_param_name(tup[0])
if key == '' or key.startswith('#'):
# section is done
break
if key == 'storage desc params':
self._parse_storage_desc_params()
elif key in self._storage_cleaners:
result = self._storage_cleaners[key](tup)
self.storage[orig_key] = result
else:
self.storage[orig_key] = tup[1] | StopIteration | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/MetadataParser._parse_storage_info |
def _parse_nested_params(self, cleaners):
params = {}
while True:
try:
tup = self._next_tuple()
except __HOLE__:
break
if pd.isnull(tup[1]):
break
key, value = tup[1:]
if key.lower() in cleaners:
cleaner = cleaners[key.lower()]
value = cleaner(value)
params[key] = value
return params | StopIteration | dataset/ETHPy150Open cloudera/ibis/ibis/impala/metadata.py/MetadataParser._parse_nested_params |
def generate_api_docs():
logging.info('Generating api docs...')
from epydoc import docparser
try:
import roman
except __HOLE__:
print ("Could not import module 'roman,' docutils has not been installed"
"properly")
print "Please install docutils: http://docutils.sourceforge.net"
sys.exit(1)
from common import api
a = docparser.parse_docs(name='common.api')
variables = a.apidoc_links(imports=False,
packages=False,
submodules=False,
bases=False,
subclasses=False,
private=False,
overrides=False)
public_api_methods = api.PublicApi.methods.keys()
public_decorators = ['throttle', 'owner_required']
allowed_names = public_api_methods + public_decorators
for v in variables:
if v.name in public_api_methods:
prefix = "method"
elif v.name in public_decorators:
prefix = "deco"
else:
continue
filename = '%s_%s.txt' % (prefix, v.name)
path = os.path.join(DOC_DIR, filename)
logging.info(' for %s...' % v.name)
docs = rst_docs(v.value)
f = open(path, 'w')
f.write(docs)
f.close()
logging.info('Finished generating api docs.') | ImportError | dataset/ETHPy150Open CollabQ/CollabQ/build.py/generate_api_docs |
def get_input(message, prompt, default='', cleaner=required):
print message
real_prompt = '%s [%s]: ' % (prompt, default)
s = raw_input(real_prompt)
if not s and default:
s = default
try:
o = cleaner(s)
print '==============================='
except __HOLE__, e:
print
print 'Error:', e.message
o = get_input(message, prompt, default, cleaner)
return o | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/build.py/get_input |
def _strip_contrib(dirnames):
for d in IGNORED_CONTRIB:
try:
dirnames.remove(d)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/build.py/_strip_contrib |
def testAddingProtocol(self):
f = ErrorRaisingFetcher(RuntimeError())
fetchers.setDefaultFetcher(f, wrap_exceptions=False)
try:
discover.discover('users.stompy.janrain.com:8000/x')
except DiscoveryFailure, why:
self.fail('failed to parse url with port correctly')
except __HOLE__:
pass #expected
fetchers.setDefaultFetcher(None) | RuntimeError | dataset/ETHPy150Open adieu/python-openid/openid/test/test_discover.py/TestNormalization.testAddingProtocol |
def fetch(self, url, body=None, headers=None):
self.fetchlog.append((url, body, headers))
if self.redirect:
final_url = self.redirect
else:
final_url = url
try:
ctype, body = self.documents[url]
except __HOLE__:
status = 404
ctype = 'text/plain'
body = ''
else:
status = 200
return HTTPResponse(final_url, status, {'content-type': ctype}, body)
# from twisted.trial import unittest as trialtest | KeyError | dataset/ETHPy150Open adieu/python-openid/openid/test/test_discover.py/DiscoveryMockFetcher.fetch |
def fetch(self, url, body=None, headers=None):
self.fetchlog.append((url, body, headers))
u = urlsplit(url)
proxy_host = u[1]
xri = u[2]
query = u[3]
if not headers and not query:
raise ValueError("No headers or query; you probably didn't "
"mean to do that.")
if xri.startswith('/'):
xri = xri[1:]
try:
ctype, body = self.documents[xri]
except __HOLE__:
status = 404
ctype = 'text/plain'
body = ''
else:
status = 200
return HTTPResponse(url, status, {'content-type': ctype}, body) | KeyError | dataset/ETHPy150Open adieu/python-openid/openid/test/test_discover.py/MockFetcherForXRIProxy.fetch |
def _fix_ipython_pylab():
try:
from IPython import get_ipython
except ImportError:
return
shell = get_ipython()
if shell is None:
return
from IPython.core.error import UsageError
try:
shell.enable_pylab('inline', import_all=True)
except __HOLE__:
# if the shell is a normal terminal shell, we get here
pass
except UsageError:
pass | ValueError | dataset/ETHPy150Open glue-viz/glue/glue/app/qt/application.py/_fix_ipython_pylab |
def _create_menu(self):
mbar = self.menuBar()
menu = QtGui.QMenu(mbar)
menu.setTitle("&File")
menu.addAction(self._actions['data_new'])
if 'data_importers' in self._actions:
submenu = menu.addMenu("I&mport data")
for a in self._actions['data_importers']:
submenu.addAction(a)
# menu.addAction(self._actions['data_save']) # XXX add this
menu.addAction(self._actions['session_reset'])
menu.addAction(self._actions['session_restore'])
menu.addAction(self._actions['session_save'])
if 'session_export' in self._actions:
submenu = menu.addMenu("E&xport")
for a in self._actions['session_export']:
submenu.addAction(a)
menu.addSeparator()
menu.addAction("Edit &Settings", self._edit_settings)
menu.addAction("&Quit", QtGui.qApp.quit)
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("&Edit ")
menu.addAction(self._actions['undo'])
menu.addAction(self._actions['redo'])
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("&View ")
a = QtGui.QAction("&Console Log", menu)
a.triggered.connect(self._log._show)
menu.addAction(a)
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("&Canvas")
menu.addAction(self._actions['tab_new'])
menu.addAction(self._actions['viewer_new'])
menu.addSeparator()
menu.addAction(self._actions['gather'])
menu.addAction(self._actions['tab_rename'])
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("Data &Manager")
menu.addActions(self._layer_widget.actions())
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("&Toolbars")
tbar = EditSubsetModeToolBar()
self._mode_toolbar = tbar
self.addToolBar(tbar)
tbar.hide()
a = QtGui.QAction("Selection Mode &Toolbar", menu)
a.setCheckable(True)
a.toggled.connect(tbar.setVisible)
try:
tbar.visibilityChanged.connect(a.setChecked)
except __HOLE__: # Qt < 4.7. QtCore.Signal not supported
pass
menu.addAction(a)
menu.addActions(tbar.actions())
mbar.addMenu(menu)
menu = QtGui.QMenu(mbar)
menu.setTitle("&Plugins")
menu.addAction(self._actions['plugin_manager'])
menu.addSeparator()
if 'plugins' in self._actions:
for plugin in self._actions['plugins']:
menu.addAction(plugin)
mbar.addMenu(menu)
# trigger inclusion of Mac Native "Help" tool
menu = mbar.addMenu("&Help")
a = QtGui.QAction("&Online Documentation", menu)
a.triggered.connect(nonpartial(webbrowser.open, DOCS_URL))
menu.addAction(a)
a = QtGui.QAction("Send &Feedback", menu)
a.triggered.connect(nonpartial(submit_feedback))
menu.addAction(a)
menu.addSeparator()
menu.addAction("Version information", show_glue_info) | AttributeError | dataset/ETHPy150Open glue-viz/glue/glue/app/qt/application.py/GlueApplication._create_menu |
def RunCommand(self):
"""Command entry point for signurl command."""
if not HAVE_OPENSSL:
raise CommandException(
'The signurl command requires the pyopenssl library (try pip '
'install pyopenssl or easy_install pyopenssl)')
method, expiration, content_type, passwd = self._ParseAndCheckSubOpts()
storage_urls = self._EnumerateStorageUrls(self.args[1:])
key = None
client_email = None
try:
key, client_email = _ReadJSONKeystore(open(self.args[0], 'rb').read(),
passwd)
except ValueError:
# Ignore and try parsing as a pkcs12.
if not passwd:
passwd = getpass.getpass('Keystore password:')
try:
key, client_email = _ReadKeystore(
open(self.args[0], 'rb').read(), passwd)
except __HOLE__:
raise CommandException('Unable to parse private key from {0}'.format(
self.args[0]))
print 'URL\tHTTP Method\tExpiration\tSigned URL'
for url in storage_urls:
if url.scheme != 'gs':
raise CommandException('Can only create signed urls from gs:// urls')
if url.IsBucket():
gcs_path = url.bucket_name
else:
# Need to url encode the object name as Google Cloud Storage does when
# computing the string to sign when checking the signature.
gcs_path = '{0}/{1}'.format(url.bucket_name,
urllib.quote(url.object_name.encode(UTF8)))
final_url = _GenSignedUrl(key, client_email,
method, '', content_type, expiration,
gcs_path)
expiration_dt = datetime.fromtimestamp(expiration)
print '{0}\t{1}\t{2}\t{3}'.format(url.url_string.encode(UTF8), method,
(expiration_dt
.strftime('%Y-%m-%d %H:%M:%S')),
final_url.encode(UTF8))
response_code = self._ProbeObjectAccessWithClient(
key, client_email, gcs_path)
if response_code == 404 and method != 'PUT':
if url.IsBucket():
msg = ('Bucket {0} does not exist. Please create a bucket with '
'that name before a creating signed URL to access it.'
.format(url))
else:
msg = ('Object {0} does not exist. Please create/upload an object '
'with that name before a creating signed URL to access it.'
.format(url))
raise CommandException(msg)
elif response_code == 403:
self.logger.warn(
'%s does not have permissions on %s, using this link will likely '
'result in a 403 error until at least READ permissions are granted',
client_email, url)
return 0 | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/commands/signurl.py/UrlSignCommand.RunCommand |