Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
9,200
|
@internationalizeDocstring
def field(self, irc, msg, args, index, text):
"""<number> <text>
Returns the <number>th space-separated field of <text>. I.e., if text
is "foo bar baz" and <number> is 2, "bar" is returned.
"""
try:
irc.reply(text.split()[index])
except __HOLE__:
irc.errorInvalid('field')
|
IndexError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Format/plugin.py/Format.field
|
9,201
|
@internationalizeDocstring
def format(self, irc, msg, args):
"""<format string> [<arg> ...]
Expands a Python-style format string using the remaining args. Just be
sure always to use %s, not %d or %f or whatever, because all the args
are strings.
"""
if not args:
raise callbacks.ArgumentError
s = args.pop(0)
try:
s %= tuple(args)
irc.reply(s)
except __HOLE__ as e:
self.log.debug(utils.exnToString(e))
irc.error(_('Not enough arguments for the format string.'),
Raise=True)
|
TypeError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Format/plugin.py/Format.format
|
9,202
|
def main(client):
# Initialize appropriate service.
media_service = client.GetService('MediaService', version='v201509')
# Construct selector and get all images.
offset = 0
selector = {
'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'],
'predicates': [{
'field': 'Type',
'operator': 'IN',
'values': ['IMAGE', 'VIDEO']
}],
'paging': {
'startIndex': str(offset),
'numberResults': str(PAGE_SIZE)
}
}
more_pages = True
while more_pages:
page = media_service.get(selector)
# Display results.
if 'entries' in page:
for image in page['entries']:
try:
dimensions = dict([(entry['key'], entry['value'])
for entry in image['dimensions']])
except __HOLE__:
dimensions = {'FULL': {'height': 0, 'width': 0}}
if image['type'] == 'IMAGE':
print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\''
' was found.' % (image['type'], image['mediaId'],
dimensions['FULL']['height'],
dimensions['FULL']['width'],
image['mimeType']))
elif image['type'] == 'VIDEO':
print ('%s with id \'%s\' was found.' % (image['type'],
image['mediaId']))
else:
print 'No images/videos were found.'
offset += PAGE_SIZE
selector['paging']['startIndex'] = str(offset)
more_pages = offset < int(page['totalNumEntries'])
|
AttributeError
|
dataset/ETHPy150Open googleads/googleads-python-lib/examples/adwords/v201509/misc/get_all_images_and_videos.py/main
|
9,203
|
def parse_elapsed(self, elapsed):
# slurm returns elapsed time in days-hours:minutes:seconds format
# Sometimes it will only return minutes:seconds, so days may be omitted
# For ease of calculating, we'll make sure all the delimeters are ':'
# Then reverse the list so that we're always counting up from seconds -> minutes -> hours -> days
total_seconds = 0
try:
elapsed = elapsed.replace('-', ':').split(':')
elapsed.reverse()
seconds_per_unit = [1, 60, 3600, 86400]
for index, multiplier in enumerate(seconds_per_unit):
if index < len(elapsed):
total_seconds += multiplier * int(elapsed[index])
except __HOLE__:
pass # slurm may return INVALID instead of a time
return total_seconds
|
ValueError
|
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/batchSystems/slurm.py/Worker.parse_elapsed
|
9,204
|
def sbatch(self, sbatch_line):
logger.debug("Running %r", sbatch_line)
try:
output = subprocess.check_output(sbatch_line, stderr=subprocess.STDOUT)
# sbatch prints a line like 'Submitted batch job 2954103'
result = int(output.strip().split()[-1])
logger.debug("sbatch submitted job %d", result)
return result
except subprocess.CalledProcessError as e:
logger.error("sbatch command failed with code %d: %s", e.returncode, e.output)
raise e
except __HOLE__ as e:
logger.error("sbatch command failed")
raise e
|
OSError
|
dataset/ETHPy150Open BD2KGenomics/toil/src/toil/batchSystems/slurm.py/Worker.sbatch
|
9,205
|
def create_module(base_cls_name, node):
"""create_module(base_cls_name: String, node: TreeNode) -> [ModuleSpec]
Construct a module spec that inherits from base_cls_name with
specification from node.
"""
if node.name in disallowed_modules: return []
if node.name == 'int': return [] #enum
def obsolete_class_list():
lst = []
items = ['vtkInteractorStyleTrackball',
'vtkStructuredPointsGeometryFilter',
'vtkConstrainedPointHandleRepresentation',
'vtkRenderViewBase',
'vtkRenderView']
def try_to_add_item(item):
try:
lst.append(getattr(vtk, item))
except AttributeError:
pass
for item in items:
try_to_add_item(item)
return lst
obsolete_list = obsolete_class_list()
def is_abstract():
"""is_abstract tries to instantiate the class. If it's
abstract, this will raise."""
# Consider obsolete classes abstract
if node.klass in obsolete_list:
return True
try:
getattr(vtk, node.name)()
except (TypeError, __HOLE__): # VTK raises type error on abstract classes
return True
return False
try:
node.klass.__doc__.decode('latin-1')
except UnicodeDecodeError:
print "ERROR decoding docstring", node.name
raise
input_ports, output_ports = get_ports(node.klass)
output_ports = list(output_ports) # drop generator
cacheable = (issubclass(node.klass, vtk.vtkAlgorithm) and
(not issubclass(node.klass, vtk.vtkAbstractMapper))) or \
issubclass(node.klass, vtk.vtkScalarTree)
is_algorithm = issubclass(node.klass, vtk.vtkAlgorithm)
tempfile = '_set_tempfile' if issubclass(node.klass, vtk.vtkWriter) else None
callback = '_set_callback' if is_algorithm else None
methods_last = hasattr(node.klass, 'SetRenderWindow')
module_spec = ClassSpec(node.name, base_cls_name, node.name,
node.klass.__doc__.decode('latin-1'), callback,
tempfile, cacheable, input_ports, output_ports,
compute='Update', cleanup='_cleanup',
methods_last=methods_last, abstract=is_abstract())
module_specs = [module_spec]
for child in node.children:
if child.name in disallowed_classes:
continue
module_specs.extend(create_module(node.name, child))
return module_specs
|
NotImplementedError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/vtk/vtk_wrapper/parse.py/create_module
|
9,206
|
def get_algorithm_ports(cls):
""" get_algorithm_ports(cls: class) -> None
If module is a subclass of vtkAlgorithm, this function will add all
SetInputConnection([id],[port]) and GetOutputPort([id]) as
SetInputConnection{id}([port]) and GetOutputPort{id}.
"""
input_ports = []
output_ports = []
if issubclass(cls, vtk.vtkAlgorithm):
# We try to instantiate the class here to get the number of
# ports and to avoid abstract classes
try:
instance = cls()
except __HOLE__:
pass
else:
for i in xrange(instance.GetNumberOfInputPorts()):
port_name = "SetInputConnection%d" % i
port_spec = InputPortSpec(name=port_name,
method_name="SetInputConnection",
port_type="vtkAlgorithmOutput",
docstring=get_doc(cls,
"SetInputConnection"),
show_port=True,
prepend_params=[i])
input_ports.append(port_spec)
for i in xrange(instance.GetNumberOfOutputPorts()):
port_name = "GetOutputPort%d" % i
port_spec = OutputPortSpec(name=port_name,
method_name="GetOutputPort",
port_type="vtkAlgorithmOutput",
docstring=get_doc(cls,
"GetOutputPort"),
show_port=True)
output_ports.append(port_spec)
return input_ports, output_ports
|
TypeError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/vtk/vtk_wrapper/parse.py/get_algorithm_ports
|
9,207
|
def get_get_set_ports(cls, get_set_dict):
"""get_get_set_ports(cls: class, get_set_dict: dict) -> None
Convert all Setxxx methods of cls into input ports and all Getxxx
methods of module into output ports
Keyword arguments:
cls --- class
get_set_dict --- the Set/Get method signatures returned by vtk_parser
"""
input_ports = []
output_ports = []
for name in get_set_dict:
if name in disallowed_get_set_ports:
continue
getter_name = 'Get%s' % name
setter_name = 'Set%s' % name
getter_method = getattr(cls, getter_name)
setter_method = getattr(cls, setter_name)
getter_sig = parser.get_method_signature(getter_method)
setter_sig = parser.get_method_signature(setter_method)
if len(getter_sig) > 1:
prune_signatures(cls, getter_name, getter_sig, output=True)
for order, getter in enumerate(getter_sig):
if getter[1]:
#print ("Can't handle getter %s (%s) of class %s: Needs input "
# "to get output" % (order+1, name, cls.__name__))
continue
if len(getter[0]) != 1:
#print ("Can't handle getter %s (%s) of class %s: More than a "
# "single output" % (order+1, name, cls.__name__))
continue
port_type = get_port_types(getter[0][0])
if is_type_allowed(port_type):
if name in color_ports:
ps = OutputPortSpec(name=name,
method_name=getter_name,
port_type="basic:Color",
show_port=False,
docstring=get_doc(cls, getter_name))
input_ports.append(ps)
else:
ps = OutputPortSpec(name=name,
method_name=getter_name,
port_type=port_type,
show_port=False,
docstring=get_doc(cls, getter_name))
output_ports.append(ps)
if len(setter_sig) > 1:
prune_signatures(cls, setter_name, setter_sig)
docstring = get_doc(cls, setter_name)
v = vtk.vtkVersion()
version = [v.GetVTKMajorVersion(),
v.GetVTKMinorVersion(),
v.GetVTKBuildVersion()]
if version < [6, 0, 0]:
# Always use VTK6-style names for InputData-style types
setter_name = get_vtk6_name(cls, setter_name)
name = setter_name[3:]
for ix, setter in enumerate(setter_sig):
if setter[1] is None:
continue
# Wrap SetFileNames for VisTrails file access
# FIXME add documentation
if file_name_pattern.match(name):
ps = InputPortSpec(name=name[:-4],
method_name=setter_name,
port_type="basic:File",
show_port=True)
input_ports.append(ps)
# Wrap color methods for VisTrails GUI facilities
# FIXME add documentation
elif name in color_ports:
ps = InputPortSpec(name=name,
method_name=setter_name,
port_type="basic:Color",
show_port=False)
input_ports.append(ps)
# Wrap SetRenderWindow for exporters
# FIXME Add documentation
elif name == 'RenderWindow' and cls == vtk.vtkExporter:
ps = InputPortSpec(name="vtkRenderer",
port_type="vtkRenderer",
show_port=True)
input_ports.append(ps)
else:
n = resolve_overloaded_name(name, ix, setter_sig)
port_types = get_port_types(setter[1])
if is_type_allowed(port_types):
if len(setter[1]) == 1:
show_port = True
try:
show_port = port_types[0] not in type_map_values
except __HOLE__: # hash error
pass
port_types = port_types[0]
else:
show_port = False
ps = InputPortSpec(name=n,
method_name=setter_name,
port_type=port_types,
show_port=show_port,
docstring=docstring,
depth=1)
input_ports.append(ps)
return input_ports, output_ports
|
TypeError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/vtk/vtk_wrapper/parse.py/get_get_set_ports
|
9,208
|
def get_other_ports(cls, other_list):
""" addOtherPorts(cls: Module, other_list: list) -> None
Convert all other ports such as Insert/Add.... into input/output
Keyword arguments:
cls --- class
other_dict --- any other method signatures that is not
Algorithm/SetGet/Toggle/State type
"""
input_ports = []
for name in other_list:
# DAK: check for static methods as name.upper() == name
if name in disallowed_other_ports or name.upper() == name:
continue
elif name=='CopyImportVoidPointer':
# FIXME add documentation
ps = InputPortSpec(name='CopyImportVoidString',
method_name='CopyImportVoidPointer',
port_type='basic:String',
show_port=True)
# elif name[:3] in ['Add','Set'] or name[:6]=='Insert':
else:
method = getattr(cls, name)
signatures = ""
if not isinstance(method, int):
signatures = parser.get_method_signature(method)
if len(signatures) > 1:
prune_signatures(cls, name, signatures)
docstring = get_doc(cls, name)
v = vtk.vtkVersion()
version = [v.GetVTKMajorVersion(),
v.GetVTKMinorVersion(),
v.GetVTKBuildVersion()]
if version < [6, 0, 0]:
# Always use VTK6-style names for InputData-style types
name = get_vtk6_name(cls, name)
for (ix, sig) in enumerate(signatures):
([result], params) = sig
port_types = get_port_types(params)
if not (name[:3] in ['Add','Set'] or
name[:6]=='Insert' or
(port_types is not None and len(port_types) == 0) or
result is None):
continue
if is_type_allowed(port_types):
n = resolve_overloaded_name(name, ix, signatures)
if n.startswith('Set'):
n = n[3:]
show_port = False
if len(port_types) < 1:
raise Exception("Shouldn't have empty input")
elif len(port_types) == 1:
if name[:3] in ['Add','Set'] or name[:6]=='Insert':
try:
show_port = port_types[0] not in type_map_values
except __HOLE__:
pass
port_types = port_types[0]
ps = InputPortSpec(name=n,
method_name=name,
port_type=port_types,
show_port=show_port,
docstring=docstring,
depth=1)
input_ports.append(ps)
elif result == None or port_types == []:
n = resolve_overloaded_name(name, ix, signatures)
ps = InputPortSpec(name=n,
method_name=name,
port_type='basic:Boolean',
method_type='nullary',
docstring=get_doc(cls, name),
depth=1)
input_ports.append(ps)
return input_ports, []
|
TypeError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/vtk/vtk_wrapper/parse.py/get_other_ports
|
9,209
|
def handle(self, *args, **kw):
apps = {}
for id, app in amo.APP_IDS.iteritems():
apps[id] = dict(guid=app.guid, versions=[],
name=amo.APPS_ALL[id].short)
versions = (AppVersion.objects.values_list('application', 'version')
.order_by('version_int'))
for app, version in versions:
try:
apps[app]['versions'].append(version)
except __HOLE__:
# Sunbird is still in the database but shouldn't show up here.
pass
# Local file, to be read by validator.
with storage.open(self.JSON_PATH, 'w') as f:
json.dump(apps, f)
log.debug("Wrote: %s" % f.name)
|
KeyError
|
dataset/ETHPy150Open mozilla/addons-server/src/olympia/applications/management/commands/dump_apps.py/Command.handle
|
9,210
|
def countMotifs(infile, motifs):
'''find regular expression *motifs* in
sequences within fasta formatted *infile*.
'''
it = FastaIterator.FastaIterator(infile)
positions = []
while 1:
try:
seq = it.next()
except __HOLE__:
break
if not seq:
break
rseq = Genomics.complement(seq.sequence)
lsequence = len(seq.sequence)
pos = []
for motif, pattern in motifs:
for x in pattern.finditer(seq.sequence):
pos.append((motif, "+", x.start(), x.end()))
for x in pattern.finditer(rseq):
pos.append(
(motif, "-", lsequence - x.end(), lsequence - x.start()))
positions.append((seq.title, pos))
return positions
|
StopIteration
|
dataset/ETHPy150Open CGATOxford/cgat/CGAT/Motifs.py/countMotifs
|
9,211
|
def check_prerequisites(self):
"""
Validate the prerequisites required to use the Amazon S3 cache backend.
Makes sure the Amazon S3 cache backend is configured
(:attr:`.Config.s3_cache_bucket` is defined by the user) and
:mod:`boto` is available for use.
:raises: :exc:`.CacheBackendDisabledError` when a prerequisite fails.
"""
if not self.config.s3_cache_bucket:
raise CacheBackendDisabledError("""
To use Amazon S3 as a cache you have to set the environment
variable $PIP_ACCEL_S3_BUCKET and configure your Amazon S3 API
credentials (see the documentation for details).
""")
try:
__import__('boto')
except __HOLE__:
raise CacheBackendDisabledError("""
Boto is required to use Amazon S3 as a cache but it looks like
Boto is not installed! You can resolve this issue by installing
pip-accel using the command `pip install pip-accel[s3]'. The
Amazon S3 cache backend will be disabled for now.
""")
|
ImportError
|
dataset/ETHPy150Open paylogic/pip-accel/pip_accel/caches/s3.py/S3CacheBackend.check_prerequisites
|
9,212
|
def zip_files(zip_file_name, *args, **kwargs):
zip_file = zipfile.ZipFile(zip_file_name, 'w', ZIP_MODE)
verbose = kwargs.pop('verbose', False)
exclude_paths = kwargs.pop('exclude_paths', [])
old_path = os.getcwd()
for arg in args:
if is_windows():
arg = '\\\\?\\'+os.path.abspath(arg).replace('/', '\\')
if os.path.exists(arg):
if os.path.isdir(arg):
directory = os.path.abspath(arg)
os.chdir(directory)
for root, dirs, files in os.walk(directory):
excluded = False
for exclude_path in exclude_paths:
if exclude_path in path_join(directory,root):
excluded = True
if not excluded:
for file in files:
file_loc = os.path.relpath(path_join(root, file), directory)
if verbose:
log(file_loc)
try:
zip_file.write(file_loc)
except __HOLE__:
os.utime(file_loc, None)
zip_file.write(file_loc)
for direc in dirs:
dir_loc = os.path.relpath(path_join(root, direc), directory)
if verbose:
log(dir_loc)
try:
zip_file.write(dir_loc)
except ValueError:
os.utime(file_loc, None)
zip_file.write(file_loc)
else:
file = os.path.abspath(arg)
directory = os.path.abspath(path_join(file, '..'))
os.chdir(directory)
file_loc = os.path.relpath(arg, directory)
if verbose:
log(file_loc)
try:
zip_file.write(file_loc)
except ValueError:
os.utime(file_loc, None)
zip_file.write(file_loc)
os.chdir(old_path)
zip_file.close()
|
ValueError
|
dataset/ETHPy150Open jyapayne/Web2Executable/utils.py/zip_files
|
9,213
|
def delete_preferences(queryset):
"""
Delete preferences objects if they are not present in registry. Return a list of deleted objects
"""
deleted = []
# Iterate through preferences. If an error is raised when accessing preference object, just delete it
for p in queryset:
try:
pref = p.preference
except __HOLE__:
p.delete()
deleted.append(p)
return deleted
|
KeyError
|
dataset/ETHPy150Open EliotBerriot/django-dynamic-preferences/dynamic_preferences/management/commands/checkpreferences.py/delete_preferences
|
9,214
|
def add_section(self, view, generator, index=None):
def with_type(gen):
def newgen():
res = gen()
try:
res.set_current_view_type(self.output_type)
except __HOLE__:
pass
return res
return newgen
super(ReportOfType, self).add_section(
view,
with_type(generator),
index
)
|
AttributeError
|
dataset/ETHPy150Open openstack/rack/rack/openstack/common/report/report.py/ReportOfType.add_section
|
9,215
|
def action(self, mode, operator):
try:
action = self.actionMaps[mode][operator]
moduleName, className = action.rsplit(".", 1)
Action = getattr(
importlib.import_module(moduleName),
className)
action = Action()
except __HOLE__:
debug("Key Error: %s %s" % (mode, operator))
self.dispatcher.reset()
action = DummyAction()
action.dispatcher = self.dispatcher
action.command = self.dispatcher.currentCommand
action.windowManager = self.windowManager
action.actionManager = self
action.registerManager = self.registerManager
action.globalVariables = self.globalVariables
if mode == "command":
action.window = self.windowManager.commandLine
action.window.buffer.insert(Position(1,1), "\n")
action.window.cursor.move(Position(1,0))
else:
action.window = self.windowManager.window
action.buffer = action.window.buffer
action.cursor = action.window.cursor
action.motions = action.window.motions
return action
|
KeyError
|
dataset/ETHPy150Open elmar-hinz/Python.Vii/vii/ActionManager.py/ActionManager.action
|
9,216
|
def get_writer(format):
try:
return {
Format.CSV: writers.CsvExportWriter,
Format.HTML: writers.HtmlExportWriter,
Format.ZIPPED_HTML: writers.ZippedHtmlExportWriter,
Format.JSON: writers.JsonExportWriter,
Format.XLS: writers.Excel2003ExportWriter,
Format.XLS_2007: writers.Excel2007ExportWriter,
Format.UNZIPPED_CSV: writers.UnzippedCsvExportWriter,
Format.CDISC_ODM: writers.CdiscOdmExportWriter,
Format.PYTHON_DICT: writers.PythonDictWriter,
}[format]()
except __HOLE__:
raise UnsupportedExportFormat("Unsupported export format: %s!" % format)
|
KeyError
|
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/couchexport/export.py/get_writer
|
9,217
|
def get_gateway(gateway, *args, **kwargs):
"""
Return a gateway instance specified by `gateway` name.
This caches gateway classes in a module-level dictionnary to avoid hitting
the filesystem every time we require a gateway.
Should the list of available gateways change at runtime, one should then
invalidate the cache, the simplest of ways would be to:
>>> gateway_cache = {}
"""
# Is the class in the cache?
clazz = gateway_cache.get(gateway, None)
if not clazz:
# Let's actually load it (it's not in the cache)
gateway_filename = "%s_gateway" % gateway
gateway_module = None
for app in settings.INSTALLED_APPS:
try:
gateway_module = import_module(".gateways.%s" % gateway_filename, package=app)
except ImportError:
pass
if not gateway_module:
raise GatewayModuleNotFound("Missing gateway: %s" % (gateway))
gateway_class_name = "".join(gateway_filename.title().split("_"))
try:
clazz = getattr(gateway_module, gateway_class_name)
except __HOLE__:
raise GatewayNotConfigured("Missing %s class in the gateway module." % gateway_class_name)
gateway_cache[gateway] = clazz
# We either hit the cache or load our class object, let's return an instance
# of it.
return clazz(*args, **kwargs)
|
AttributeError
|
dataset/ETHPy150Open agiliq/merchant/billing/gateway.py/get_gateway
|
9,218
|
def testFilter(self):
"""Test if filtering works properly."""
expected_values = {
'CITY1':0, 'CITY2':0, 'CITY3':0, 'CITY4' :0, 'CITY5' :0, 'CITY6' :0,
'CITY7':0, 'CITY8':0, 'CITY9':0, 'CITY10':0, 'CITY11':1, 'CITY12':1,
}
filter = unusual_trip_filter.UnusualTripFilter(0.1, quiet=True)
input = self.GetPath('tests', 'data', 'filter_unusual_trips')
loader = transitfeed.Loader(input, extra_validation=True)
schedule = loader.Load()
filter.filter(schedule)
for trip_id, expected_trip_type in expected_values.items():
actual_trip_type = schedule.trips[trip_id]['trip_type']
try:
self.assertEquals(int(actual_trip_type), expected_trip_type)
except __HOLE__:
self.assertEquals(actual_trip_type, '')
|
ValueError
|
dataset/ETHPy150Open google/transitfeed/tests/testunusual_trip_filter.py/UnusualTripFilterTestCase.testFilter
|
9,219
|
def test_to_file_schema(self):
"""
Ensure that the file is written according to the schema
if it is specified
"""
try:
from collections import OrderedDict
except __HOLE__:
from ordereddict import OrderedDict
tempfilename = os.path.join(self.tempdir, 'test.shp')
properties = OrderedDict([
('Shape_Leng', 'float:19.11'),
('BoroName', 'str:40'),
('BoroCode', 'int:10'),
('Shape_Area', 'float:19.11'),
])
schema = {'geometry': 'Polygon', 'properties': properties}
# Take the first 2 features to speed things up a bit
self.df.iloc[:2].to_file(tempfilename, schema=schema)
with fiona.open(tempfilename) as f:
result_schema = f.schema
self.assertEqual(result_schema, schema)
|
ImportError
|
dataset/ETHPy150Open geopandas/geopandas/geopandas/tests/test_geodataframe.py/TestDataFrame.test_to_file_schema
|
9,220
|
def watch_scanner(d, addrs, verbose = True, block_wordcount = 4, memo_filename = None):
"""Repeatedly scan memory, in randomized order, looking for changes.
When a change is found, we yield:
(timestamp, address, new_value, old_value).
Timestamps are as reported by time.time(). It's the first time we noticed
this change, timestamped as soon as possible.
Addresses are a list of things to watch:
(addr,)
Single numbers are the address of a word to watch. This guarantees
that the address is only read as that one single word. We won't read
anything nearby, and each read will be a single peek.
(a, b)
Two elements indicate a range of addresses from a to b, including
both endpoints. These are broken into randomized sections of exactly
block_wordcount words. To reduce unwanted statistical correlations,
we end up scanning a little past the beginning and end, but any
addresses outside the range is not reported.
"""
now = time.time()
start_timestamp = now
output_timestamp = now
round_number = 0
# We can use a file on disk as memo for debugging or if we need something
# that handles large sparse address spaces, but usually cStringIO is fine.
if memo_filename:
memo = open(memo_filename, 'w+b')
else:
memo = cStringIO.StringIO()
# Initialize the memo with current memory contents
for addr, fn in break_up_addresses(d, addrs, block_wordcount):
memo.seek(addr)
memo.write(fn())
# Scan in an endless series of shuffled rounds
while True:
round_number += 1
byte_count = 0
for addr, fn in break_up_addresses(d, addrs, block_wordcount):
# Timestamp as soon as the block read comes back.
# If there's an error, keep on going. TinySCSI complains enough already.
try:
block = fn()
except __HOLE__:
continue
timestamp = time.time()
byte_count += len(block)
# Keep track of differences with our memo buffer
memo.seek(addr)
memo_block = memo.read(len(block))
if block == memo_block:
continue
# If the block has changed, memoize it and report word-by-word diffs
memo.seek(addr)
memo.write(block)
block_wordcount = len(block) // 4
block_words = struct.unpack('<%dI' % block_wordcount, block[:block_wordcount * 4])
memo_words = struct.unpack('<%dI' % block_wordcount, memo_block[:block_wordcount * 4])
for i in range(block_wordcount):
old_value = memo_words[i]
new_value = block_words[i]
if new_value != old_value:
yield (timestamp, addr + i*4, new_value, old_value)
# Report status
now = time.time()
if verbose and now > output_timestamp + 1.0:
output_timestamp = now
print "* scanning %d bytes at %.03f Hz" % (byte_count, round_number / (now - start_timestamp))
|
IOError
|
dataset/ETHPy150Open scanlime/coastermelt/backdoor/watch.py/watch_scanner
|
9,221
|
def isfilesize(value):
global systems
try:
float(str(value))
return True
except __HOLE__:
pass # continue
def isnumeric_helper(suffix):
tmp_value = value.replace(suffix, '')
tmp_value.strip()
try:
float(tmp_value)
return True
except ValueError:
return False
for system in systems:
for factor, suffix in system:
if type(suffix) is str:
if isnumeric_helper(suffix):
return True
else:
for name in suffix:
if isnumeric_helper(name):
return True
return False
|
ValueError
|
dataset/ETHPy150Open aerospike/aerospike-admin/lib/filesize.py/isfilesize
|
9,222
|
def __str__(self):
try:
curr = self._examples
for frag in self._path[1:]:
curr = curr[frag]
except __HOLE__:
if frag in self._special:
curr = self._special[frag]
else:
curr = '{%s}' % '.'.join(self._path)
self._path[1:] = []
return curr
|
KeyError
|
dataset/ETHPy150Open pyjs/pyjs/examples/_examples/util.py/_e.__str__
|
9,223
|
def _find_python():
if sys.version_info[0] == 2 and sys.executable and os.path.isfile(sys.executable):
return sys.executable
for python in ('python2', 'python2.7', 'python2.6'):
try:
subprocess.call([python, '-c', '"raise SystemExit"'])
return python
except __HOLE__:
pass
return 'python'
|
OSError
|
dataset/ETHPy150Open pyjs/pyjs/examples/_examples/util.py/_find_python
|
9,224
|
def convert_body_to_bytes(resp):
"""
If the request body is a string, encode it to bytes (for python3 support)
By default yaml serializes to utf-8 encoded bytestrings.
When this cassette is loaded by python3, it's automatically decoded
into unicode strings. This makes sure that it stays a bytestring, since
that's what all the internal httplib machinery is expecting.
For more info on py3 yaml:
http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support
"""
try:
if not isinstance(resp['body']['string'], six.binary_type):
resp['body']['string'] = resp['body']['string'].encode('utf-8')
except (__HOLE__, TypeError, UnicodeEncodeError):
# The thing we were converting either wasn't a dictionary or didn't
# have the keys we were expecting. Some of the tests just serialize
# and deserialize a string.
# Also, sometimes the thing actually is binary, so if you can't encode
# it, just give up.
pass
return resp
|
KeyError
|
dataset/ETHPy150Open kevin1024/vcrpy/vcr/serializers/compat.py/convert_body_to_bytes
|
9,225
|
def convert_body_to_unicode(resp):
"""
If the request body is bytes, decode it to a string (for python3 support)
"""
try:
if not isinstance(resp['body']['string'], six.text_type):
resp['body']['string'] = resp['body']['string'].decode('utf-8')
except (__HOLE__, TypeError, UnicodeDecodeError):
# The thing we were converting either wasn't a dictionary or didn't
# have the keys we were expecting. Some of the tests just serialize
# and deserialize a string.
# Also, sometimes the thing actually is binary, so if you can't decode
# it, just give up.
pass
return resp
|
KeyError
|
dataset/ETHPy150Open kevin1024/vcrpy/vcr/serializers/compat.py/convert_body_to_unicode
|
9,226
|
def _parse_datetime(self, value):
for format in self._DATETIME_FORMATS:
try:
return datetime.datetime.strptime(value, format)
except __HOLE__:
pass
raise Error('Unrecognized date/time format: %r' % value)
|
ValueError
|
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/options.py/_Option._parse_datetime
|
9,227
|
def main(*args, **kwargs):
if sys.version_info[:2] < (3, 4):
logger.fatal("Error: Python 3.4+ is required")
sys.exit(-1)
arguments = docopt(__doc__, version=get_version())
formatter = "[%(asctime)s] :: %(levelname)s - %(message)s"
if arguments['-d']:
level = logging.DEBUG
else:
level = logging.INFO
logging.basicConfig(level=level, format=formatter)
config = None
if arguments['-c']:
config = read_yaml_config(arguments['-c'])
else:
config = read_yaml_config(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'default_broker.yaml'))
logger.debug("Using default configuration")
loop = asyncio.get_event_loop()
broker = Broker(config)
try:
loop.run_until_complete(broker.start())
loop.run_forever()
except __HOLE__:
loop.run_until_complete(broker.shutdown())
finally:
loop.close()
|
KeyboardInterrupt
|
dataset/ETHPy150Open beerfactory/hbmqtt/scripts/broker_script.py/main
|
9,228
|
@app.route('/trelloCallbacks/', methods=['GET', 'POST'])
def callback():
try:
if request.method != 'POST':
return BEACON
data = request.json
action = data['action']
board = slugify(data['model']['name'])
# NOTE: it's ugly to init for each request the parser class
parser = Parser()
payload = parser(action=action)
if payload:
send = Send(parser=parser, board=board, action=action, payload=payload)
send()
except __HOLE__ as e:
logging.error('missing necessary field :: {} :: {}'.format(e, data))
except Exception as e:
logging.error('unable to handle event :: {}'.format(e))
finally:
return BEACON
|
KeyError
|
dataset/ETHPy150Open Lujeni/matterllo/matterllo/__init__.py/callback
|
9,229
|
def _find_plugins(self):
"""Returns a map from plugin name to plugin jar."""
# Allow multiple flags and also comma-separated values in a single flag.
plugin_names = set([p for val in self.get_options().scalac_plugins for p in val.split(',')])
plugins = {}
buildroot = get_buildroot()
for jar in self.plugin_jars:
with open_zip(jar, 'r') as jarfile:
try:
with closing(jarfile.open(_PLUGIN_INFO_FILE, 'r')) as plugin_info_file:
plugin_info = ElementTree.parse(plugin_info_file).getroot()
if plugin_info.tag != 'plugin':
raise TaskError(
'File {} in {} is not a valid scalac plugin descriptor'.format(_PLUGIN_INFO_FILE,
jar))
name = plugin_info.find('name').text
if name in plugin_names:
if name in plugins:
raise TaskError('Plugin {} defined in {} and in {}'.format(name, plugins[name], jar))
# It's important to use relative paths, as the compiler flags get embedded in the zinc
# analysis file, and we port those between systems via the artifact cache.
plugins[name] = os.path.relpath(jar, buildroot)
except __HOLE__:
pass
unresolved_plugins = plugin_names - set(plugins.keys())
if unresolved_plugins:
raise TaskError('Could not find requested plugins: {}'.format(list(unresolved_plugins)))
return plugins
|
KeyError
|
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/jvm/tasks/jvm_compile/zinc/zinc_compile.py/ZincCompile._find_plugins
|
9,230
|
def get_settings(args=None, override_defaults={}):
"""Parse args and set other settings based on them
Default settings can be overriden by passing in a dictionary
Return a new dictionary containing all args and settings
"""
# Parse the arguments:
parser = argparser()
args = parser.parse_args(args)
settings = {
# Store args object:
'args': args,
# Instruct client to post stdout back to the server:
'receive_postbacks': True,
# Run client script with this shell interpreter:
'shell_command': 'bash',
# Client fetches URL resources with this command:
'http_fetcher': 'curl -LSs',
# Mime type to serve resource as:
'mime_type': args.mime_type,
# Client should send it's hostname in the request header:
'require_hostname_header': False,
# Log client stdout to server stdout:
'log_post_backs': args.log_post_backs,
# Enable TLS
'ssl': args.ssl,
# ssl context passed to server
'ssl_context': None,
# Enable SSL certificate pinning in client command:
'pin': args.pin or args.ssl is None,
# Total number of allowed HTTP gets on resource:
'num_gets': args.num_gets,
# Require X-knock header:
'require_knock': not args.disable_knock,
# The current knock:
'knock': args.knock,
# Server verbose flag
'verbose': args.verbose,
# Print curl command without shell_command
'survey': args.survey,
# SSH tunnel
'ssh': args.ssh,
# Server quiet flag
'quiet': args.quiet and not args.verbose,
# Log stdout on client:
'client_logging': args.client_logging,
# Client quiet flag
'client_quiet': args.client_quiet,
# Popen object processing log_post_backs
'log_process': None,
# File to receive log_post_backs:
'log_file': None,
# Don't print knock in wrapped curlbomb command:
'require_knock_from_environment': True,
# Client should use wget instead of curl
'wget': args.wget,
# Don't wrap curlbomb
'unwrapped': args.unwrapped,
# Use alternative stdin, only used in tests
'stdin': sys.stdin,
# Use alternative stdout, only used in tests
'stdout': sys.stdout,
# Output how long the command takes:
'time_command': False,
# Function to get curlbomb command given settings:
'get_curlbomb_command': get_curlbomb_command
}
settings.update(override_defaults)
if args.verbose:
logging.getLogger('curlbomb').setLevel(level=logging.INFO)
settings['log_post_backs'] = True
logging.getLogger('tornado.access').setLevel(level=logging.INFO)
if args.debug:
settings['verbose'] = True
logging.getLogger('curlbomb').setLevel(level=logging.DEBUG)
settings['log_post_backs'] = True
logging.getLogger('tornado.access').setLevel(level=logging.DEBUG)
if settings['require_knock'] and not settings['knock']:
settings['knock'] = base64.b64encode(bytes(random.sample(range(256), 12)),
altchars=b'_.').decode("utf-8")
if settings['survey']:
# Don't recieve post backs in survey mode:
settings['receive_postbacks'] = False
settings['client_logging'] = False
if args.disable_postback:
settings['receive_postbacks'] = False
if settings['unwrapped']:
# Output the unrwapped version of the curlbomb Without this
# setting, curlbomb usually outputs a url that retrieves a
# wrapper script that wraps the longer more complicated client
# command. This will output this unrwapped version instead.
settings['require_knock_from_environment'] = False
if args.pin and args.ssl is False:
print("--pin requires --ssl")
sys.exit(1)
if args.wget:
settings['http_fetcher'] = "wget -q -O -"
if args.log_post_backs:
print("wget can't stream the client output, so --log-posts is not "
"supported in wget mode")
sys.exit(1)
if args.pin:
print("SSL certificate pinning only works in curl mode")
sys.exit(1)
if args.port == "random":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',0))
settings['port'] = s.getsockname()[1]
s.close()
else:
settings['port'] = int(args.port)
settings['display_host'] = socket.gethostbyname(socket.gethostname())
settings['display_port'] = settings['port']
if settings['ssh']:
ssh_parts = settings['ssh'].split(":")
ssh_host = ssh_parts[0]
ssh_port = 22
http_port = settings['port']
if len(ssh_parts) == 3:
ssh_port = ssh_parts[1]
http_port = ssh_parts[2]
elif len(ssh_parts) == 2:
http_port = ssh_parts[1]
settings['ssh_forward'] = "0.0.0.0:{http_port}:localhost:{port}".format(
port=settings['port'], http_port=http_port)
settings['ssh_host'] = ssh_host
settings['ssh_port'] = ssh_port
settings['display_port'] = http_port
if '@' in ssh_host:
settings['ssh_user'], settings['display_host'] = ssh_host.split('@')
else:
settings['display_host'] = ssh_host
if args.domain:
# Override displayed host:port
parts = args.domain.split(":")
settings['display_host'] = parts[0]
if len(parts) > 1:
settings['display_port'] = parts[1]
if settings['ssl'] is not False:
settings['ssl_context'] = tls.get_ssl_context_from_settings(settings)
if not settings['stdout'].isatty() and not settings['quiet']:
# Imply we want log-posts if we pipe to a non-tty:
settings['log_post_backs'] = True
try:
prepare_cmd = args.prepare_command
except __HOLE__:
# No sub-command specified, default to run command with stdin
args.command = None
args.script_hash = None
args.signature = None
args.resource = settings['stdin']
prepare_cmd = run.prepare
prepare_cmd(args, settings, parser)
return settings
|
AttributeError
|
dataset/ETHPy150Open EnigmaCurry/curlbomb/curlbomb/settings.py/get_settings
|
9,231
|
def peek(it, n):
_peek = []
for _ in range(n):
try:
_peek.append(six.next(it))
except __HOLE__:
break
return _peek, itertools.chain(_peek, it)
|
StopIteration
|
dataset/ETHPy150Open daler/gffutils/gffutils/iterators.py/peek
|
9,232
|
def load(self, instance, session):
cache_name = self.field.get_cache_name()
cache_val = None
try:
cache_val = getattr(instance, cache_name)
if not isinstance(cache_val, Structure):
raise AttributeError
structure = cache_val
except __HOLE__:
structure = self.get_structure(instance, session)
setattr(instance, cache_name, structure)
if cache_val is not None:
structure.load_data(cache_val,
structure.cache.set_cache)
if session: # override session only if a new session is given
structure.session = session
return structure
|
AttributeError
|
dataset/ETHPy150Open lsbardel/python-stdnet/stdnet/odm/structfields.py/StructureFieldProxy.load
|
9,233
|
def register_serializer(format, serializer_module, serializers=None):
"""Register a new serializer.
``serializer_module`` should be the fully qualified module name
for the serializer.
If ``serializers`` is provided, the registration will be added
to the provided dictionary.
If ``serializers`` is not provided, the registration will be made
directly into the global register of serializers. Adding serializers
directly is not a thread-safe operation.
"""
if serializers is None and not _serializers:
_load_serializers()
try:
module = importlib.import_module(serializer_module)
except __HOLE__ as exc:
bad_serializer = BadSerializer(exc)
module = type('BadSerializerModule', (object,), {
'Deserializer': bad_serializer,
'Serializer': bad_serializer,
})
if serializers is None:
_serializers[format] = module
else:
serializers[format] = module
|
ImportError
|
dataset/ETHPy150Open django/django/django/core/serializers/__init__.py/register_serializer
|
9,234
|
def test_transaction_error_code_property(self):
""" Test ValidationError class 'transaction_error_code' property"""
transaction = Transaction(
amount_in_cents=1000,
currency='USD',
account=Account(
account_code='transactionmock'
)
)
# Mock 'save transaction' request to throw declined
# transaction validation error
with self.mock_request('transaction/declined-transaction.xml'):
try:
transaction.save()
except __HOLE__ as e:
error = e
self.assertEqual(error.transaction_error_code, 'insufficient_funds')
|
ValidationError
|
dataset/ETHPy150Open recurly/recurly-client-python/tests/tests_errors.py/RecurlyExceptionTests.test_transaction_error_code_property
|
9,235
|
def retry(exception_processor=generic_exception_processor):
"""
Generic retry decorator
Tries to call the decorated function. Should no exception be
raised, the value is simply returned, otherwise, call an
exception_processor function with the exception (type, value,
traceback) tuple (with the intention that it could raise the
exception without losing the traceback) and the exception
processor's optionally usable context value (exc_processor_cxt).
It's recommended to delete all references to the traceback passed
to the exception_processor to speed up garbage collector via the
'del' operator.
This context value is passed to and returned from every invocation
of the exception processor. This can be used to more conveniently
(vs. an object with __call__ defined) implement exception
processors that have some state, such as the 'number of attempts'.
The first invocation will pass None.
:param f: A function to be retried.
:type f: function
:param exception_processor: A function to process raised
exceptions.
:type exception_processor: function
"""
def yield_new_function_from(f):
def shim(*args, **kwargs):
exc_processor_cxt = None
while True:
# Avoid livelocks while spinning on retry by yielding.
gevent.sleep(0.1)
try:
return f(*args, **kwargs)
except __HOLE__:
raise
except:
exception_info_tuple = None
try:
exception_info_tuple = sys.exc_info()
exc_processor_cxt = exception_processor(
exception_info_tuple,
exc_processor_cxt=exc_processor_cxt)
finally:
# Although cycles are harmless long-term, help the
# garbage collector.
del exception_info_tuple
return functools.wraps(f)(shim)
return yield_new_function_from
|
KeyboardInterrupt
|
dataset/ETHPy150Open wal-e/wal-e/wal_e/retries.py/retry
|
9,236
|
def __init__(self, _, params):
BaseCache.__init__(self, params)
self._cache = {}
self._expire_info = {}
max_entries = params.get('max_entries', 300)
try:
self._max_entries = int(max_entries)
except (ValueError, TypeError):
self._max_entries = 300
cull_frequency = params.get('cull_frequency', 3)
try:
self._cull_frequency = int(cull_frequency)
except (ValueError, __HOLE__):
self._cull_frequency = 3
self._lock = RWLock()
|
TypeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/cache/backends/locmem.py/CacheClass.__init__
|
9,237
|
def get(self, key, default=None):
self.validate_key(key)
self._lock.reader_enters()
try:
exp = self._expire_info.get(key)
if exp is None:
return default
elif exp > time.time():
try:
return pickle.loads(self._cache[key])
except pickle.PickleError:
return default
finally:
self._lock.reader_leaves()
self._lock.writer_enters()
try:
try:
del self._cache[key]
del self._expire_info[key]
except __HOLE__:
pass
return default
finally:
self._lock.writer_leaves()
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/cache/backends/locmem.py/CacheClass.get
|
9,238
|
def has_key(self, key):
self.validate_key(key)
self._lock.reader_enters()
try:
exp = self._expire_info.get(key)
if exp is None:
return False
elif exp > time.time():
return True
finally:
self._lock.reader_leaves()
self._lock.writer_enters()
try:
try:
del self._cache[key]
del self._expire_info[key]
except __HOLE__:
pass
return False
finally:
self._lock.writer_leaves()
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/cache/backends/locmem.py/CacheClass.has_key
|
9,239
|
def _delete(self, key):
try:
del self._cache[key]
except __HOLE__:
pass
try:
del self._expire_info[key]
except KeyError:
pass
|
KeyError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/cache/backends/locmem.py/CacheClass._delete
|
9,240
|
def test_nonbackground_prepare(self):
task = {"command": "echo hello", "background": True}
task2 = 'sleep 1'
self.obj.parameters.merge({"prepare": [task, task2]})
try:
self.obj.prepare()
except __HOLE__:
self.fail()
|
ValueError
|
dataset/ETHPy150Open Blazemeter/taurus/tests/modules/test_shellexec.py/TestBlockingTasks.test_nonbackground_prepare
|
9,241
|
@classmethod
def get_best_handler(cls, mimetype):
"""Returns the handler and score that that best fit the mimetype."""
best_score = 0
best_fit = None
for review_ui in _file_attachment_review_uis:
for mt in review_ui.supported_mimetypes:
try:
score = score_match(mimeparse.parse_mime_type(mt),
mimetype)
if score > best_score:
best_score = score
best_fit = review_ui
except __HOLE__:
continue
return best_score, best_fit
|
ValueError
|
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/reviews/ui/base.py/FileAttachmentReviewUI.get_best_handler
|
9,242
|
@classmethod
def for_type(cls, attachment):
"""Returns the handler that is the best fit for provided mimetype."""
if attachment.mimetype:
try:
mimetype = mimeparse.parse_mime_type(attachment.mimetype)
except:
logging.error('Unable to parse MIME type "%s" for %s',
attachment.mimetype, attachment)
return None
# Override the mimetype if mimeparse is known to misinterpret this
# type of file as 'octet-stream'
extension = os.path.splitext(attachment.filename)[1]
if extension in MIMETYPE_EXTENSIONS:
mimetype = MIMETYPE_EXTENSIONS[extension]
score, handler = cls.get_best_handler(mimetype)
if handler:
try:
return handler(attachment.get_review_request(), attachment)
except __HOLE__ as e:
logging.error('Unable to load review UI for %s: %s',
attachment, e)
except Exception as e:
logging.error('Error instantiating '
'FileAttachmentReviewUI %r: %s',
handler, e)
return None
|
ObjectDoesNotExist
|
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/reviews/ui/base.py/FileAttachmentReviewUI.for_type
|
9,243
|
def unregister_ui(review_ui):
"""Unregisters a review UI class.
This will unregister a previously registered review UI.
Only FileAttachmentReviewUI subclasses are supported. The class must
have been registered beforehand or a ValueError will be thrown.
"""
if not issubclass(review_ui, FileAttachmentReviewUI):
raise TypeError('Only FileAttachmentReviewUI subclasses can be '
'unregistered')
try:
_file_attachment_review_uis.remove(review_ui)
except __HOLE__:
logging.error('Failed to unregister missing review UI %r' %
review_ui)
raise ValueError('This review UI was not previously registered')
|
ValueError
|
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/reviews/ui/base.py/unregister_ui
|
9,244
|
def _db_str_to_datetime(value):
if value is None:
return None
try:
return from_utimestamp(long(value))
except __HOLE__:
pass
try:
return parse_date(value.strip(), utc, 'datetime')
except Exception:
return None
|
ValueError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/_db_str_to_datetime
|
9,245
|
def _custom_field_default(self, field):
default = field.get('value')
options = field.get('options')
if default and options and default not in options:
try:
default = options[int(default)]
except (ValueError, __HOLE__):
self.env.log.warning('Invalid default value "%s" '
'for custom field "%s"',
default, field['name'])
if default and field.get('type') == 'time':
try:
default = parse_date(default,
hint=field.get('format'))
except TracError as e:
self.env.log.warning('Invalid default value "%s" '
'for custom field "%s": %s',
default, field['name'], e)
default = None
return default
|
IndexError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/Ticket._custom_field_default
|
9,246
|
def get_value_or_default(self, name):
"""Return the value of a field or the default value if it is undefined
"""
try:
value = self.values[name]
return value if value is not empty else self.get_default(name)
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/Ticket.get_value_or_default
|
9,247
|
def get_comment_number(self, cdate):
"""Return a comment number by its date."""
ts = to_utimestamp(cdate)
for cnum, in self.env.db_query("""\
SELECT oldvalue FROM ticket_change
WHERE ticket=%s AND time=%s AND field='comment'
""", (self.id, ts)):
try:
return int(cnum.rsplit('.', 1)[-1])
except __HOLE__:
break
|
ValueError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/Ticket.get_comment_number
|
9,248
|
def save_changes(self, author=None, comment=None, when=None, cnum='',
replyto=None):
"""
Store ticket changes in the database. The ticket must already exist in
the database. Returns False if there were no changes to save, True
otherwise.
:since 1.0: the `cnum` parameter is deprecated, and threading should
be controlled with the `replyto` argument
"""
assert self.exists, "Cannot update a new ticket"
if 'cc' in self.values:
self['cc'] = _fixup_cc_list(self.values['cc'])
props_unchanged = all(self.values.get(k) == v
for k, v in self._old.iteritems())
if (not comment or not comment.strip()) and props_unchanged:
return False # Not modified
if when is None:
when = datetime_now(utc)
when_ts = to_utimestamp(when)
# Perform type conversions
db_values = self._to_db_types(self.values)
old_db_values = self._to_db_types(self._old)
with self.env.db_transaction as db:
db("UPDATE ticket SET changetime=%s WHERE id=%s",
(when_ts, self.id))
# find cnum if it isn't provided
if not cnum:
num = 0
for ts, old in db("""
SELECT DISTINCT tc1.time, COALESCE(tc2.oldvalue,'')
FROM ticket_change AS tc1
LEFT OUTER JOIN ticket_change AS tc2
ON tc2.ticket=%s AND tc2.time=tc1.time
AND tc2.field='comment'
WHERE tc1.ticket=%s ORDER BY tc1.time DESC
""", (self.id, self.id)):
# Use oldvalue if available, else count edits
try:
num += int(old.rsplit('.', 1)[-1])
break
except __HOLE__:
num += 1
cnum = str(num + 1)
if replyto:
cnum = '%s.%s' % (replyto, cnum)
# store fields
for name in self._old.keys():
if name in self.custom_fields:
for row in db("""SELECT * FROM ticket_custom
WHERE ticket=%s and name=%s
""", (self.id, name)):
db("""UPDATE ticket_custom SET value=%s
WHERE ticket=%s AND name=%s
""", (db_values.get(name), self.id, name))
break
else:
db("""INSERT INTO ticket_custom (ticket,name,value)
VALUES(%s,%s,%s)
""", (self.id, name, db_values.get(name)))
else:
db("UPDATE ticket SET %s=%%s WHERE id=%%s"
% name, (db_values.get(name), self.id))
db("""INSERT INTO ticket_change
(ticket,time,author,field,oldvalue,newvalue)
VALUES (%s, %s, %s, %s, %s, %s)
""", (self.id, when_ts, author, name,
old_db_values.get(name), db_values.get(name)))
# always save comment, even if empty
# (numbering support for timeline)
db("""INSERT INTO ticket_change
(ticket,time,author,field,oldvalue,newvalue)
VALUES (%s,%s,%s,'comment',%s,%s)
""", (self.id, when_ts, author, cnum, comment))
old_values = self._old
self._old = {}
self.values['changetime'] = when
for listener in TicketSystem(self.env).change_listeners:
listener.ticket_changed(self, comment, author, old_values)
return int(cnum.rsplit('.', 1)[-1])
|
ValueError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/Ticket.save_changes
|
9,249
|
def _find_change(self, cnum):
"""Find a comment by its number."""
scnum = str(cnum)
with self.env.db_query as db:
for row in db("""
SELECT time, author, newvalue FROM ticket_change
WHERE ticket=%%s AND field='comment'
AND (oldvalue=%%s OR oldvalue %s)
""" % db.like(),
(self.id, scnum, '%' + db.like_escape('.' + scnum))):
return row
# Fallback when comment number is not available in oldvalue
num = 0
for ts, old, author, comment in db("""
SELECT DISTINCT tc1.time, COALESCE(tc2.oldvalue,''),
tc2.author, COALESCE(tc2.newvalue,'')
FROM ticket_change AS tc1
LEFT OUTER JOIN ticket_change AS tc2
ON tc2.ticket=%s AND tc2.time=tc1.time
AND tc2.field='comment'
WHERE tc1.ticket=%s ORDER BY tc1.time
""", (self.id, self.id)):
# Use oldvalue if available, else count edits
try:
num = int(old.rsplit('.', 1)[-1])
except __HOLE__:
num += 1
if num == cnum:
break
else:
return
# Find author if NULL
if author is None:
for author, in db("""
SELECT author FROM ticket_change
WHERE ticket=%%s AND time=%%s AND NOT field %s LIMIT 1
""" % db.prefix_match(),
(self.id, ts, db.prefix_match_value('_'))):
break
return ts, author, comment
|
ValueError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/Ticket._find_change
|
9,250
|
def delete(self):
"""Delete the enum value.
"""
assert self.exists, "Cannot delete non-existent %s" % self.type
with self.env.db_transaction as db:
self.env.log.info("Deleting %s %s", self.type, self.name)
db("DELETE FROM enum WHERE type=%s AND value=%s",
(self.type, self._old_value))
# Re-order any enums that have higher value than deleted
# (close gap)
for enum in self.select(self.env):
try:
if int(enum.value) > int(self._old_value):
enum.value = unicode(int(enum.value) - 1)
enum.update()
except __HOLE__:
pass # Ignore cast error for this non-essential operation
TicketSystem(self.env).reset_ticket_fields()
self.value = self._old_value = None
self.name = self._old_name = None
|
ValueError
|
dataset/ETHPy150Open edgewall/trac/trac/ticket/model.py/AbstractEnum.delete
|
9,251
|
def robust_line_iter(istream):
"Read lines, continuing if a blocking system call gets interrupted."
tries_since_success = 0
sub = _color_pattern.sub
lines = unbuffered_lines(istream)
while True:
try:
l = next(lines)
tries_since_success = 0
# trim and remove shell colors
l_no_color = sub(u'', l.rstrip())
yield l_no_color
except __HOLE__:
break
except IOError:
# sometimes we can get interrupted on a blocking read
# let's retry a few times
tries_since_success += 1
if tries_since_success >= MAX_IO_RETRIES:
# something's really wrong
break
|
StopIteration
|
dataset/ETHPy150Open larsyencken/anytop/anytop/common.py/robust_line_iter
|
9,252
|
def dropSlave(self):
"""
Drop a slave after crash
Arguments: None
Returns: None
"""
if self.noseSlave is not None:
try:
self.sendToSlave(None) # Tell the slave we are finished with it.
except (EOFError, __HOLE__, socket.error), e:
pass
self.noseSlave = None
self.toSlave.close()
self.fromSlave.close()
self.toSlave = self.fromSlave = None
self.hasCrashed = True
|
IOError
|
dataset/ETHPy150Open ooici/pyon/pyon/util/insulate.py/TestSlave.dropSlave
|
9,253
|
def runTest(self, count, orgtest):
"""
Runs the test.
Argument: count - the test number to run, as counted by both
master and slave independently.
Returns: (result status, result data)
"""
self.startSlave()
if self.noseSlave is None:
return ResultCollector.ERROR, (SkipAfterCrash(' - previous test crashed, skipping.'), None)
try:
self.sendToSlave(count)
except (EOFError, IOError, socket.error), e:
_, _, tb = sys.exc_info()
self.dropSlave()
return ResultCollector.ERROR, (e, tb)
try:
status, exc, (stdout, stderr), func_dict = self.readFromSlave()
if func_dict is not None:
orgtest.test.func_dict.update(func_dict)
sys.stdout.write(stdout)
sys.stderr.write(stderr)
return status, exc
except (EOFError, __HOLE__, socket.error), e:
_, _, tb = sys.exc_info()
self.dropSlave()
return ResultCollector.ERROR, (CrashInTestError(), tb)
|
IOError
|
dataset/ETHPy150Open ooici/pyon/pyon/util/insulate.py/TestSlave.runTest
|
9,254
|
@traced
def status(self):
try:
d = self._req('GET', '/status')
return DBStatus.from_dict(d)
except __HOLE__:
return DBStatus.not_running()
|
IOError
|
dataset/ETHPy150Open natduca/quickopen/src/db_proxy.py/DBProxy.status
|
9,255
|
@classmethod
def delsession(cls, session):
try:
cls.__sessions.remove(session)
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.delsession
|
9,256
|
def disconnect(self, handler):
''' Disconnect a request handler from this session. Shutdown this
session if there is no running emulation.
'''
with self._handlerslock:
try:
self._handlers.remove(handler)
except __HOLE__:
raise ValueError, \
"Handler %s not associated with this session" % handler
num_handlers = len(self._handlers)
if num_handlers == 0:
# shut down this session unless we are instantiating, running,
# or collecting final data
if self.getstate() < coreapi.CORE_EVENT_INSTANTIATION_STATE or \
self.getstate() > coreapi.CORE_EVENT_DATACOLLECT_STATE:
self.shutdown()
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.disconnect
|
9,257
|
def add_state_hook(self, state, hook):
try:
hooks = self._state_hooks[state]
assert hook not in hooks
hooks.append(hook)
except __HOLE__:
self._state_hooks[state] = [hook]
if self._state == state:
hook(state)
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.add_state_hook
|
9,258
|
def del_state_hook(self, state, hook):
try:
hooks = self._state_hooks[state]
self._state_hooks[state] = filter(lambda x: x != hook, hooks)
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.del_state_hook
|
9,259
|
def getenviron(self, state=True):
''' Get an environment suitable for a subprocess.Popen call.
This is the current process environment with some session-specific
variables.
'''
env = os.environ.copy()
env['SESSION'] = "%s" % self.sessionid
env['SESSION_SHORT'] = "%s" % self.shortsessionid()
env['SESSION_DIR'] = "%s" % self.sessiondir
env['SESSION_NAME'] = "%s" % self.name
env['SESSION_FILENAME'] = "%s" % self.filename
env['SESSION_USER'] = "%s" % self.user
env['SESSION_NODE_COUNT'] = "%s" % self.node_count
if state:
env['SESSION_STATE'] = "%s" % self.getstate()
try:
readfileintodict(os.path.join(CORE_CONF_DIR, "environment"), env)
except __HOLE__:
pass
if self.user:
try:
readfileintodict(os.path.join('/home', self.user, ".core",
"environment"), env)
except IOError:
pass
return env
|
IOError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.getenviron
|
9,260
|
def delobj(self, objid):
''' Remove an emulation object.
'''
self._objslock.acquire()
try:
o = self._objs.pop(objid)
except __HOLE__:
o = None
self._objslock.release()
if o:
o.shutdown()
del o
gc.collect()
# print "gc count:", gc.get_count()
# for o in gc.get_objects():
# if isinstance(o, PyCoreObj):
# print "XXX XXX XXX PyCoreObj:", o
# for r in gc.get_referrers(o):
# print "XXX XXX XXX referrer:", gc.get_referrers(o)
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.delobj
|
9,261
|
def addremovectrlnet(self, netidx, remove=False, conf_reqd=True):
''' Create a control network bridge as necessary.
When the remove flag is True, remove the bridge that connects control
interfaces. The conf_reqd flag, when False, causes a control network
bridge to be added even if one has not been configured.
'''
prefixspeclist = self.getctrlnetprefixes()
prefixspec = prefixspeclist[netidx]
if not prefixspec:
if conf_reqd:
return None # no controlnet needed
else:
prefixspec = nodes.CtrlNet.DEFAULT_PREFIX_LIST[netidx]
serverintf = self.getctrlnetserverintf()[netidx]
# return any existing controlnet bridge
try:
ctrlnet = self.getctrlnetobj(netidx)
if remove:
self.delobj(ctrlnet.objid)
return None
return ctrlnet
except KeyError:
if remove:
return None
# build a new controlnet bridge
oid = "ctrl%dnet" % netidx
# use the updown script for control net 0 only.
updown_script = None
if netidx == 0:
try:
if self.cfg['controlnet_updown_script']:
updown_script = self.cfg['controlnet_updown_script']
except __HOLE__:
pass
# Check if session option set, overwrite if so
if hasattr(self.options, 'controlnet_updown_script'):
new_uds = self.options.controlnet_updown_script
if new_uds:
updown_script = new_uds
prefixes = prefixspec.split()
if len(prefixes) > 1:
# A list of per-host prefixes is provided
assign_address = True
if self.master:
try:
# split first (master) entry into server and prefix
prefix = prefixes[0].split(':', 1)[1]
except IndexError:
# no server name. possibly only one server
prefix = prefixes[0]
else:
# slave servers have their name and localhost in the serverlist
servers = self.broker.getserverlist()
servers.remove('localhost')
prefix = None
for server_prefix in prefixes:
try:
# split each entry into server and prefix
server, p = server_prefix.split(':')
except ValueError:
server = ""
p = None
if server == servers[0]:
# the server name in the list matches this server
prefix = p
break
if not prefix:
msg = "Control network prefix not found for server '%s'" % \
servers[0]
self.exception(coreapi.CORE_EXCP_LEVEL_ERROR,
"Session.addremovectrlnet()", None, msg)
assign_address = False
try:
prefix = prefixes[0].split(':', 1)[1]
except IndexError:
prefix = prefixes[0]
else: # len(prefixes) == 1
# TODO: can we get the server name from the servers.conf or from the node assignments?
# with one prefix, only master gets a ctrlnet address
assign_address = self.master
prefix = prefixes[0]
ctrlnet = self.addobj(cls=nodes.CtrlNet, objid=oid, prefix=prefix,
assign_address=assign_address,
updown_script=updown_script, serverintf=serverintf)
# tunnels between controlnets will be built with Broker.addnettunnels()
self.broker.addnet(oid)
for server in self.broker.getserverlist():
self.broker.addnodemap(server, oid)
return ctrlnet
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.addremovectrlnet
|
9,262
|
def addremovectrlif(self, node, netidx=0, remove=False, conf_reqd=True):
''' Add a control interface to a node when a 'controlnet' prefix is
listed in the config file or session options. Uses
addremovectrlnet() to build or remove the control bridge.
If conf_reqd is False, the control network may be built even
when the user has not configured one (e.g. for EMANE.)
'''
ctrlnet = self.addremovectrlnet(netidx, remove, conf_reqd)
if ctrlnet is None:
return
if node is None:
return
if node.netif(ctrlnet.CTRLIF_IDX_BASE + netidx):
return # ctrl# already exists
ctrlip = node.objid
try:
addrlist = ["%s/%s" % (ctrlnet.prefix.addr(ctrlip),
ctrlnet.prefix.prefixlen)]
except __HOLE__:
msg = "Control interface not added to node %s. " % node.objid
msg += "Invalid control network prefix (%s). " % ctrlnet.prefix
msg += "A longer prefix length may be required for this many nodes."
node.exception(coreapi.CORE_EXCP_LEVEL_ERROR,
"Session.addremovectrlif()", msg)
return
ifi = node.newnetif(net = ctrlnet, ifindex = ctrlnet.CTRLIF_IDX_BASE + netidx,
ifname = "ctrl%d" % netidx, hwaddr = MacAddr.random(),
addrlist = addrlist)
node.netif(ifi).control = True
|
ValueError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.addremovectrlif
|
9,263
|
def updatectrlifhosts(self, netidx=0, remove=False):
''' Add the IP addresses of control interfaces to the /etc/hosts file.
'''
if not self.getcfgitembool('update_etc_hosts', False):
return
try:
ctrlnet = self.getctrlnetobj(netidx)
except __HOLE__:
return
header = "CORE session %s host entries" % self.sessionid
if remove:
if self.getcfgitembool('verbose', False):
self.info("Removing /etc/hosts file entries.")
filedemunge('/etc/hosts', header)
return
entries = []
for ifc in ctrlnet.netifs():
name = ifc.node.name
for addr in ifc.addrlist:
entries.append("%s %s" % (addr.split('/')[0], ifc.node.name))
if self.getcfgitembool('verbose', False):
self.info("Adding %d /etc/hosts file entries." % len(entries))
filemunge('/etc/hosts', header, '\n'.join(entries) + '\n')
|
KeyError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/Session.updatectrlifhosts
|
9,264
|
def configure_values(self, msg, values):
if values is None:
return None
kvs = values.split('|')
for kv in kvs:
try:
(key, value) = kv.split('=', 1)
except __HOLE__:
raise ValueError, "invalid key in metdata: %s" % kv
self.additem(key, value)
return None
|
ValueError
|
dataset/ETHPy150Open coreemu/core/daemon/core/session.py/SessionMetaData.configure_values
|
9,265
|
@staticmethod
def get_permutation_from_orientations(orientation_in, orientation_out):
"""
This function return the permutation necessary to convert a coordinate/image from orientation_in
to orientation_out
:param orientation_in: string (ex: AIL)
:param orientation_out: string (ex: RPI)
:return: two lists: permutation list (int) and inversion list (-1 if need to inverse)
"""
opposite_character = {'L': 'R', 'R': 'L', 'A': 'P', 'P': 'A', 'I': 'S', 'S': 'I'}
# change the orientation of the image
perm = [0, 1, 2]
inversion = [1, 1, 1]
for i, character in enumerate(orientation_in):
try:
perm[i] = orientation_out.index(character)
except __HOLE__:
perm[i] = orientation_out.index(opposite_character[character])
inversion[i] = -1
return perm, inversion
|
ValueError
|
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_image.py/Image.get_permutation_from_orientations
|
9,266
|
def save_plane(self, plane='sagittal', index=None, format='.png', suffix='', seg=None, thr=0, cmap_col='red', path_output='./'):
"""
Save a slice of self in the specified plan.
:param plane: 'sagittal', 'coronal' or 'axial'. default = 'sagittal'
:param index: index of the slice to save (if none, middle slice in the given direction/plan)
:param format: format to be saved in. default = '.png'
:param suffix: suffix to add to the image file name.
:param seg: segmentation to add in transparency to the image to save. Type Image.
:param thr: threshold to apply to the segmentation
:param col: colormap description : 'red', 'red-yellow', or 'blue-cyan'
:return filename_png: file name of the saved image
"""
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from math import sqrt
from sct_utils import slash_at_the_end
if type(index) is not list:
index = [index]
slice_list = [self.get_slice(plane=plane, index=i, seg=seg) for i in index]
path_output = slash_at_the_end(path_output, 1)
if seg is not None:
import matplotlib.colors as col
color_white = col.colorConverter.to_rgba('white', alpha=0.0)
if cmap_col == 'red-yellow':
color_red = col.colorConverter.to_rgba('red', alpha=0.7)
color_yellow = col.colorConverter.to_rgba('yellow', alpha=0.8)
cmap_seg = col.LinearSegmentedColormap.from_list('cmap_seg', [color_white, color_yellow, color_red], N=256)
elif cmap_col == 'blue-cyan':
color_blue = col.colorConverter.to_rgba('blue', alpha=0.7)
color_cyan = col.colorConverter.to_rgba('cyan', alpha=0.8)
cmap_seg = col.LinearSegmentedColormap.from_list('cmap_seg', [color_white, color_blue, color_cyan], N=256)
else:
color_red = col.colorConverter.to_rgba('red', alpha=0.7)
cmap_seg = col.LinearSegmentedColormap.from_list('cmap_seg', [color_white, color_red], N=256)
n_lines = int(sqrt(len(slice_list)))
n_col = int(len(slice_list)/n_lines)
n_lines += 1
try:
fig = plt.figure(figsize=(n_lines*10, n_col*20))
for i, slices in enumerate(slice_list):
slice_im, slice_seg = slices
plot = fig.add_subplot(n_lines, n_col, i+1)
plot.imshow(slice_im, cmap=cm.gray, interpolation='nearest')
if index[i] is None:
title = 'mid slice'
else:
title = 'slice '+str(index[i])
plot.set_title(title)
if seg is not None:
slice_seg[slice_seg < thr] = 0
plot.imshow(slice_seg, cmap=cmap_seg, interpolation='nearest')
plt.axis('off')
# plt.imshow(slice, cmap=cm.gray, interpolation='nearest')
# if seg is not None:
# plt.imshow(slice_seg, cmap=cmap_seg, interpolation='nearest')
# plt.axis('off')
fname_png = path_output + self.file_name + suffix + format
plt.savefig(fname_png, bbox_inches='tight')
except __HOLE__, e:
from sct_utils import printv
printv('WARNING: your device does not seem to have display feature', self.verbose, type='warning')
printv(str(e), self.verbose, type='warning')
return fname_png
|
RuntimeError
|
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_image.py/Image.save_plane
|
9,267
|
def save_quality_control(self, plane='sagittal', n_slices=1, seg=None, thr=0, cmap_col='red', format='.png', path_output='./', verbose=1):
from sct_utils import printv
nx, ny, nz, nt, px, py, pz, pt = self.dim
if plane == 'sagittal':
max_n_slices = nx
elif plane == 'coronal':
max_n_slices = ny
elif plane == 'axial' or plane == 'transverse':
max_n_slices = nz
else:
max_n_slices = None
printv('ERROR: wrong plan input to save slice. Please choose "sagittal", "coronal" or "axial"', self.verbose, type='error')
if n_slices > max_n_slices:
index_list = range(max_n_slices)
elif n_slices == 1:
index_list = [int(round(max_n_slices/2))]
else:
gap = max_n_slices/n_slices
index_list = [((i+1)*gap)-1 for i in range(n_slices)]
index_list.sort()
try:
filename_image_png = self.save_plane(plane=plane, suffix='_'+plane+'_plane', index=index_list, format=format, path_output=path_output)
info_str = 'QC output image: ' + filename_image_png
if seg is not None:
filename_gmseg_image_png = self.save_plane(plane=plane, suffix='_'+plane+'_plane_seg', index=index_list, seg=seg, thr=thr, cmap_col=cmap_col, format=format, path_output=path_output)
info_str += ' & ' + filename_gmseg_image_png
printv(info_str, verbose, 'info')
except __HOLE__, e:
printv('WARNING: your device does not seem to have display feature', self.verbose, type='warning')
printv(str(e), self.verbose, type='warning')
|
RuntimeError
|
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_image.py/Image.save_quality_control
|
9,268
|
def change_data_orientation(data, old_orientation='RPI', orientation="RPI"):
"""
This function changes the orientation of a data matrix from a give orientation to another.
This function assumes that the user already knows the orientation of the data
:param data: data of the image
:param old_orientation: Current orientation of the data
:param orientation: Desired orientation for the data
:return: Data matrix representing the
"""
opposite_character = {'L': 'R', 'R': 'L', 'A': 'P', 'P': 'A', 'I': 'S', 'S': 'I'}
# change the orientation of the image
perm = [0, 1, 2]
inversion = [1, 1, 1]
for i, character in enumerate(old_orientation):
try:
perm[i] = orientation.index(character)
except __HOLE__:
perm[i] = orientation.index(opposite_character[character])
inversion[i] = -1
# axes inversion
data = data[::inversion[0], ::inversion[1], ::inversion[2]]
# axes manipulations
from numpy import swapaxes
if perm == [1, 0, 2]:
data = swapaxes(data, 0, 1)
elif perm == [2, 1, 0]:
data = swapaxes(data, 0, 2)
elif perm == [0, 2, 1]:
data = swapaxes(data, 1, 2)
elif perm == [2, 1, 0]:
data = swapaxes(data, 0, 2)
elif perm == [2, 0, 1]:
data = swapaxes(data, 0, 2) # transform [2, 0, 1] to [1, 0, 2]
data = swapaxes(data, 0, 1) # transform [1, 0, 2] to [0, 1, 2]
elif perm == [1, 2, 0]:
data = swapaxes(data, 0, 2) # transform [1, 2, 0] to [0, 2, 1]
data = swapaxes(data, 1, 2) # transform [0, 2, 1] to [0, 1, 2]
elif perm == [0, 1, 2]:
# do nothing
pass
else:
print 'Error: wrong orientation'
return data
# =======================================================================================================================
# Start program
#=======================================================================================================================
|
ValueError
|
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_image.py/change_data_orientation
|
9,269
|
def user_data(self, access_token, *args, **kwargs):
"""Return user data provided"""
try:
return self.get_json('https://eco.taobao.com/router/rest', params={
'method': 'taobao.user.get',
'fomate': 'json',
'v': '2.0',
'access_token': access_token
})
except __HOLE__:
return None
|
ValueError
|
dataset/ETHPy150Open omab/python-social-auth/social/backends/taobao.py/TAOBAOAuth.user_data
|
9,270
|
def filesize(bytes, format='auto1024'):
"""
Returns the number of bytes in either the nearest unit or a specific unit
(depending on the chosen format method).
Acceptable formats are:
auto1024, auto1000
convert to the nearest unit, appending the abbreviated unit name to the
string (e.g. '2 KiB' or '2 kB').
auto1024 is the default format.
auto1024long, auto1000long
convert to the nearest multiple of 1024 or 1000, appending the correctly
pluralized unit name to the string (e.g. '2 kibibytes' or '2 kilobytes').
kB, MB, GB, TB, PB, EB, ZB or YB
convert to the exact unit (using multiples of 1000).
KiB, MiB, GiB, TiB, PiB, EiB, ZiB or YiB
convert to the exact unit (using multiples of 1024).
The auto1024 and auto1000 formats return a string, appending the correct
unit to the value. All other formats return the floating point value.
If an invalid format is specified, the bytes are returned unchanged.
"""
format_len = len(format)
# Check for valid format
if format_len in (2, 3):
if format_len == 3 and format[0] == 'K':
format = 'k%s' % format[1:]
if not format[-1] == 'B' or format[0] not in filesize_formats:
return bytes
if format_len == 3 and format[1] != 'i':
return bytes
elif format not in ('auto1024', 'auto1000',
'auto1024long', 'auto1000long'):
return bytes
# Check for valid bytes
try:
bytes = int(bytes) if six.PY3 else long(bytes) # NOQA - flake8/py3 reports error: long does not exists in py3
except (ValueError, __HOLE__):
return bytes
# Auto multiple of 1000 or 1024
if format.startswith('auto'):
if format[4:8] == '1000':
base = 1000
else:
base = 1024
logarithm = bytes and math.log(bytes, base) or 0
index = min(int(logarithm) - 1, len(filesize_formats) - 1)
if index >= 0:
if base == 1000:
bytes = bytes and bytes / math.pow(1000, index + 1)
else:
bytes = bytes >> (10 * (index))
bytes = bytes and bytes / 1024.0
unit = filesize_formats[index]
else:
# Change the base to 1000 so the unit will just output 'B' not 'iB'
base = 1000
unit = ''
if bytes >= 10 or ('%.1f' % bytes).endswith('.0'):
bytes = '%.0f' % bytes
else:
bytes = '%.1f' % bytes
if format.endswith('long'):
unit = filesize_long_formats.get(unit, '')
if base == 1024 and unit:
unit = '%sbi' % unit[:2]
unit = '%sbyte%s' % (unit, bytes != '1' and 's' or '')
else:
unit = '%s%s' % (base == 1024 and unit.upper() or unit,
base == 1024 and 'iB' or 'B')
return '%s %s' % (bytes, unit)
if bytes == 0:
return bytes
base = filesize_formats.index(format[0]) + 1
# Exact multiple of 1000
if format_len == 2:
return bytes / (1000.0 ** base)
# Exact multiple of 1024
elif format_len == 3:
bytes = bytes >> (10 * (base - 1))
return bytes / 1024.0
|
TypeError
|
dataset/ETHPy150Open divio/django-filer/filer/templatetags/filer_tags.py/filesize
|
9,271
|
def runserver(config):
setup_loggers(config)
activity_logger = logging.getLogger("activity_logger")
databases = DatabaseStore(config)
backend = Backend(databases, config)
frontend = Frontend(config)
poller = zmq.Poller()
poller.register(backend.socket, zmq.POLLIN)
poller.register(frontend.socket, zmq.POLLIN)
activity_logger.info('Elevator server started on %s' % frontend.host)
while True:
try:
sockets = dict(poller.poll())
if frontend.socket in sockets:
if sockets[frontend.socket] == zmq.POLLIN:
msg = frontend.socket.recv_multipart(copy=False)
backend.socket.send_multipart(msg, copy=False)
if backend.socket in sockets:
if sockets[backend.socket] == zmq.POLLIN:
msg = backend.socket.recv_multipart(copy=False)
frontend.socket.send_multipart(msg, copy=False)
except __HOLE__:
activity_logger.info('Gracefully shuthing down workers')
del backend
activity_logger.info('Stopping frontend')
del frontend
activity_logger.info('Done')
return
except Exception as e:
log_critical(e)
del backend
del frontend
return
|
KeyboardInterrupt
|
dataset/ETHPy150Open oleiade/Elevator/elevator/server.py/runserver
|
9,272
|
def __init__(self, num, taskmaster):
"""
create 'num' jobs using the given taskmaster.
If 'num' is 1 or less, then a serial job will be used,
otherwise a parallel job with 'num' worker threads will
be used.
The 'num_jobs' attribute will be set to the actual number of jobs
allocated. If more than one job is requested but the Parallel
class can't do it, it gets reset to 1. Wrapping interfaces that
care should check the value of 'num_jobs' after initialization.
"""
self.job = None
if num > 1:
stack_size = explicit_stack_size
if stack_size is None:
stack_size = default_stack_size
try:
self.job = Parallel(taskmaster, num, stack_size)
self.num_jobs = num
except __HOLE__:
pass
if self.job is None:
self.job = Serial(taskmaster)
self.num_jobs = 1
|
NameError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Job.py/Jobs.__init__
|
9,273
|
def _setup_sig_handler(self):
"""Setup an interrupt handler so that SCons can shutdown cleanly in
various conditions:
a) SIGINT: Keyboard interrupt
b) SIGTERM: kill or system shutdown
c) SIGHUP: Controlling shell exiting
We handle all of these cases by stopping the taskmaster. It
turns out that it very difficult to stop the build process
by throwing asynchronously an exception such as
KeyboardInterrupt. For example, the python Condition
variables (threading.Condition) and queue's do not seem to
asynchronous-exception-safe. It would require adding a whole
bunch of try/finally block and except KeyboardInterrupt all
over the place.
Note also that we have to be careful to handle the case when
SCons forks before executing another process. In that case, we
want the child to exit immediately.
"""
def handler(signum, stack, self=self, parentpid=os.getpid()):
if os.getpid() == parentpid:
self.job.taskmaster.stop()
self.job.interrupted.set()
else:
os._exit(2)
self.old_sigint = signal.signal(signal.SIGINT, handler)
self.old_sigterm = signal.signal(signal.SIGTERM, handler)
try:
self.old_sighup = signal.signal(signal.SIGHUP, handler)
except __HOLE__:
pass
|
AttributeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Job.py/Jobs._setup_sig_handler
|
9,274
|
def _reset_sig_handler(self):
"""Restore the signal handlers to their previous state (before the
call to _setup_sig_handler()."""
signal.signal(signal.SIGINT, self.old_sigint)
signal.signal(signal.SIGTERM, self.old_sigterm)
try:
signal.signal(signal.SIGHUP, self.old_sighup)
except __HOLE__:
pass
|
AttributeError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Job.py/Jobs._reset_sig_handler
|
9,275
|
def __init__(self, num, stack_size, interrupted):
"""Create the request and reply queues, and 'num' worker threads.
One must specify the stack size of the worker threads. The
stack size is specified in kilobytes.
"""
self.requestQueue = queue.Queue(0)
self.resultsQueue = queue.Queue(0)
try:
prev_size = threading.stack_size(stack_size*1024)
except AttributeError, e:
# Only print a warning if the stack size has been
# explicitly set.
if not explicit_stack_size is None:
msg = "Setting stack size is unsupported by this version of Python:\n " + \
e.args[0]
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
except __HOLE__, e:
msg = "Setting stack size failed:\n " + str(e)
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
# Create worker threads
self.workers = []
for _ in range(num):
worker = Worker(self.requestQueue, self.resultsQueue, interrupted)
self.workers.append(worker)
if 'prev_size' in locals():
threading.stack_size(prev_size)
|
ValueError
|
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Job.py/ThreadPool.__init__
|
9,276
|
def token(self, location=None):
"""Get the next waiting token. If a location is given, then
return the token at currentIndex+location without advancing
currentIndex; setting it gives lookahead/lookback capability."""
try:
if location is None:
tok = self._buffer[self._currentIndex]
self._currentIndex += 1
else:
tok = self._buffer[self._currentIndex+location]
return tok
except __HOLE__:
raise ExpectedMoreTokensException(self._currentIndex+1)
|
IndexError
|
dataset/ETHPy150Open nltk/nltk/nltk/sem/logic.py/LogicParser.token
|
9,277
|
def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: General information about the Redis server
- clients: Client connections section
- memory: Memory consumption related information
- persistence: RDB and AOF related information
- stats: General statistics
- replication: Master/slave replication information
- cpu: CPU consumption statistics
- commandstats: Redis command statistics
- cluster: Redis Cluster section
- keyspace: Database related statistics
It can also take the following values:
- all: Return all sections
- default: Return only the default set of sections
When no parameter is provided, the default option is assumed.
:param str section: Optional
:return: dict
"""
def parse_value(value):
"""
:param value:
:return:
"""
try:
if b'.' in value:
return float(value)
else:
return int(value)
except __HOLE__:
if b',' in value or b'=' in value:
retval = {}
for row in value.split(b','):
key, val = row.rsplit(b'=', 1)
retval[key.decode('utf-8')] = parse_value(val)
return retval
return value.decode('utf-8')
def format_response(value):
"""Format the response from redis
:param str value: The return response from redis
:rtype: dict
"""
info = {}
for line in value.splitlines():
if line.startswith(b'#'):
continue
if b':' in line:
key, value = line.split(b':', 1)
info[key.decode('utf-8')] = parse_value(value)
return info
if section:
return self._execute([b'INFO', section],
format_callback=format_response)
return self._execute([b'INFO'], format_callback=format_response)
|
ValueError
|
dataset/ETHPy150Open gmr/tredis/tredis/server.py/ServerMixin.info
|
9,278
|
def is_uuid_like(val):
try:
converted = str(uuid.UUID(val))
if '-' not in val:
converted = converted.replace('-', '')
return converted == val
except (TypeError, __HOLE__, AttributeError):
return False
|
ValueError
|
dataset/ETHPy150Open openstack/stacktach/stacktach/utils.py/is_uuid_like
|
9,279
|
def __kill_posix(pid):
def __check_pid():
try:
os.kill(pid, 0)
return True
except __HOLE__:
return False
if __check_pid():
for sig in [15, 9]:
try:
os.killpg(pid, sig)
except OSError:
return
sleep(1)
if not __check_pid():
return
|
OSError
|
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/managers/util/kill.py/__kill_posix
|
9,280
|
def __init__(self, to, **kwargs):
try:
self.abstract_model = to._meta.object_name
except __HOLE__:
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter must be either a model or a model name" % (self.__class__.__name__, to)
self.abstract_model = to
else:
assert to._meta.abstract, "%s can only define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name)
self.options = kwargs
|
AttributeError
|
dataset/ETHPy150Open awesto/django-shop/shop/models/deferred.py/DeferredRelatedField.__init__
|
9,281
|
def __new__(cls, name, bases, attrs):
class Meta:
app_label = shop_settings.APP_LABEL
attrs.setdefault('Meta', Meta)
if not hasattr(attrs['Meta'], 'app_label') and not getattr(attrs['Meta'], 'abstract', False):
attrs['Meta'].app_label = Meta.app_label
attrs.setdefault('__module__', getattr(bases[-1], '__module__'))
Model = super(ForeignKeyBuilder, cls).__new__(cls, name, bases, attrs)
if Model._meta.abstract:
return Model
for baseclass in bases:
# classes which materialize an abstract model are added to a mapping dictionary
basename = baseclass.__name__
try:
if not issubclass(Model, baseclass) or not baseclass._meta.abstract:
raise ImproperlyConfigured("Base class %s is not abstract." % basename)
except (__HOLE__, NotImplementedError):
pass
else:
if basename in cls._materialized_models:
if Model.__name__ != cls._materialized_models[basename]:
raise AssertionError("Both Model classes '%s' and '%s' inherited from abstract"
"base class %s, which is disallowed in this configuration." %
(Model.__name__, cls._materialized_models[basename], basename))
elif isinstance(baseclass, cls):
cls._materialized_models[basename] = Model.__name__
# remember the materialized model mapping in the base class for further usage
baseclass._materialized_model = Model
cls.process_pending_mappings(Model, basename)
# search for deferred foreign fields in our Model
for attrname in dir(Model):
try:
member = getattr(Model, attrname)
except AttributeError:
continue
if not isinstance(member, DeferredRelatedField):
continue
mapmodel = cls._materialized_models.get(member.abstract_model)
if mapmodel:
field = member.MaterializedField(mapmodel, **member.options)
field.contribute_to_class(Model, attrname)
else:
ForeignKeyBuilder._pending_mappings.append((Model, attrname, member,))
Model.perform_model_checks()
return Model
|
AttributeError
|
dataset/ETHPy150Open awesto/django-shop/shop/models/deferred.py/ForeignKeyBuilder.__new__
|
9,282
|
def walk_controller(root_class, controller, hooks, seen=None):
seen = seen or set()
if type(controller) not in vars(six.moves.builtins).values():
# Avoid recursion loops
try:
if controller in seen:
return
seen.add(controller)
except __HOLE__:
# If we discover an unhashable item (like a list), it's not
# something that we want to traverse because it's not the sort of
# thing we would add a hook to
return
for hook in getattr(controller, '__hooks__', []):
# Append hooks from controller class definition
hooks.add(hook)
for name, value in getmembers(controller):
if name == 'controller':
continue
if name.startswith('__') and name.endswith('__'):
continue
if iscontroller(value):
for hook in hooks:
value._pecan.setdefault('hooks', set()).add(hook)
elif hasattr(value, '__class__'):
# Skip non-exposed methods that are defined in parent classes;
# they're internal implementation details of that class, and
# not actual routable controllers, so we shouldn't bother
# assigning hooks to them.
if (
isinstance(value, types.MethodType) and
any(filter(lambda c: value.__func__ in c.__dict__.values(),
value.__self__.__class__.mro()[1:]))
):
continue
walk_controller(root_class, value, hooks, seen)
|
TypeError
|
dataset/ETHPy150Open pecan/pecan/pecan/hooks.py/walk_controller
|
9,283
|
def PreconditionsFromHeaders(headers):
"""Creates bucket or object preconditions acccording to the provided headers.
Args:
headers: Dict of headers passed via gsutil -h
Returns:
gsutil Cloud API Preconditions object fields populated from headers, or None
if no precondition headers are present.
"""
return_preconditions = Preconditions()
try:
for header, value in headers.items():
if GOOG_GENERATION_MATCH_REGEX.match(header):
return_preconditions.gen_match = long(value)
if GOOG_METAGENERATION_MATCH_REGEX.match(header):
return_preconditions.meta_gen_match = long(value)
except __HOLE__, _:
raise ArgumentException('Invalid precondition header specified. '
'x-goog-if-generation-match and '
'x-goog-if-metageneration match must be specified '
'with a positive integer value.')
return return_preconditions
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/translation_helper.py/PreconditionsFromHeaders
|
9,284
|
@classmethod
def JsonLifecycleToMessage(cls, json_txt):
"""Translates lifecycle JSON to an apitools message."""
try:
deserialized_lifecycle = json.loads(json_txt)
# If lifecycle JSON is the in the following format
# {'lifecycle': {'rule': ... then strip out the 'lifecycle' key
# and reduce it to the following format
# {'rule': ...
if 'lifecycle' in deserialized_lifecycle:
deserialized_lifecycle = deserialized_lifecycle['lifecycle']
lifecycle = encoding.DictToMessage(
deserialized_lifecycle, apitools_messages.Bucket.LifecycleValue)
return lifecycle
except __HOLE__:
CheckForXmlConfigurationAndRaise('lifecycle', json_txt)
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/translation_helper.py/LifecycleTranslation.JsonLifecycleToMessage
|
9,285
|
@classmethod
def JsonCorsToMessageEntries(cls, json_cors):
"""Translates CORS JSON to an apitools message.
Args:
json_cors: JSON string representing CORS configuration.
Returns:
List of apitools Bucket.CorsValueListEntry. An empty list represents
no CORS configuration.
"""
try:
deserialized_cors = json.loads(json_cors)
cors = []
for cors_entry in deserialized_cors:
cors.append(encoding.DictToMessage(
cors_entry, apitools_messages.Bucket.CorsValueListEntry))
return cors
except __HOLE__:
CheckForXmlConfigurationAndRaise('CORS', json_cors)
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/translation_helper.py/CorsTranslation.JsonCorsToMessageEntries
|
9,286
|
@classmethod
def JsonToMessage(cls, json_data, message_type):
"""Converts the input JSON data into list of Object/BucketAccessControls.
Args:
json_data: String of JSON to convert.
message_type: Which type of access control entries to return,
either ObjectAccessControl or BucketAccessControl.
Raises:
ArgumentException on invalid JSON data.
Returns:
List of ObjectAccessControl or BucketAccessControl elements.
"""
try:
deserialized_acl = json.loads(json_data)
acl = []
for acl_entry in deserialized_acl:
acl.append(encoding.DictToMessage(acl_entry, message_type))
return acl
except __HOLE__:
CheckForXmlConfigurationAndRaise('ACL', json_data)
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/translation_helper.py/AclTranslation.JsonToMessage
|
9,287
|
def parse (self, name, command):
if command not in self.known:
return self.error.set('unknown command %s options are %s' % (command,', '.join(self.known)))
try:
if command in self.default:
insert = self.known[command](self.tokeniser.iterate,self.default[command])
else:
insert = self.known[command](self.tokeniser.iterate)
action = self.action[command]
if action == 'set-command':
self.scope.set(command,insert)
elif action == 'extend-name':
self.scope.extend(name,insert)
elif action == 'append-name':
self.scope.append(name,insert)
elif action == 'append-command':
self.scope.append(command,insert)
elif action == 'attribute-add':
self.scope.attribute_add(name,insert)
elif action == 'nlri-set':
self.scope.nlri_assign(name,self.assign[command],insert)
elif action == 'nlri-add':
for adding in insert:
self.scope.nlri_add(name,command,adding)
elif action == 'nlri-nexthop':
self.scope.nlri_nexthop(name,insert)
elif action == 'nexthop-and-attribute':
ip, attribute = insert
if ip:
self.scope.nlri_nexthop(name,ip)
if attribute:
self.scope.attribute_add(name,attribute)
elif action == 'nop':
pass
else:
raise RuntimeError('name %s command %s has no action set' % (name,command))
return True
except __HOLE__, exc:
return self.error.set(str(exc))
return True
|
ValueError
|
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/configuration/core/section.py/Section.parse
|
9,288
|
def mask_ntob(mask, err_msg=None):
try:
return (UINT32_MAX << (32 - mask)) & UINT32_MAX
except __HOLE__:
msg = 'illegal netmask'
if err_msg is not None:
msg = '%s %s' % (err_msg, msg)
raise ValueError(msg)
|
ValueError
|
dataset/ETHPy150Open openstack/dragonflow/dragonflow/controller/common/utils.py/mask_ntob
|
9,289
|
def parse_duration(duration):
# (-)PnYnMnDTnHnMnS
index = 0
if duration[0] == '-':
sign = '-'
index += 1
else:
sign = '+'
assert duration[index] == "P"
index += 1
dic = dict([(typ, 0) for (code, typ) in D_FORMAT if typ])
dlen = len(duration)
for code, typ in D_FORMAT:
#print duration[index:], code
if duration[index] == '-':
raise Exception("Negation not allowed on individual items")
if code == "T":
if duration[index] == "T":
index += 1
if index == len(duration):
raise Exception("Not allowed to end with 'T'")
else:
raise Exception("Missing T")
elif duration[index] == "T":
continue
else:
try:
mod = duration[index:].index(code)
_val = duration[index:index + mod]
try:
dic[typ] = int(_val)
except ValueError:
# smallest value used may also have a decimal fraction
if mod + index + 1 == dlen:
try:
dic[typ] = float(_val)
except __HOLE__:
if "," in _val:
_val = _val.replace(",", ".")
try:
dic[typ] = float(_val)
except ValueError:
raise Exception("Not a float")
else:
raise Exception("Not a float")
else:
raise ValueError(
"Fraction not allowed on other than smallest value")
index = mod + index + 1
except ValueError:
dic[typ] = 0
if index == dlen:
break
return sign, dic
|
ValueError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/time_util.py/parse_duration
|
9,290
|
def str_to_time(timestr, format=TIME_FORMAT):
"""
:param timestr:
:param format:
:return: UTC time
"""
if not timestr:
return 0
try:
then = time.strptime(timestr, format)
except __HOLE__: # assume it's a format problem
try:
elem = TIME_FORMAT_WITH_FRAGMENT.match(timestr)
except Exception, exc:
print >> sys.stderr, "Exception: %s on %s" % (exc, timestr)
raise
then = time.strptime(elem.groups()[0] + "Z", TIME_FORMAT)
return time.gmtime(calendar.timegm(then))
|
ValueError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/time_util.py/str_to_time
|
9,291
|
def main():
command, files = sys.argv[1], sys.argv[2:]
try:
watcher(command, files)
except __HOLE__:
pass
|
KeyboardInterrupt
|
dataset/ETHPy150Open mozilla/addons-server/docs/watcher.py/main
|
9,292
|
def _get_server_version_info(self, connection):
dbapi_con = connection.connection
version = []
r = re.compile('[.\-]')
for n in r.split(dbapi_con.server_version):
try:
version.append(int(n))
except __HOLE__:
version.append(n)
return tuple(version)
|
ValueError
|
dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/sqlalchemy/dialects/mysql/cymysql.py/MySQLDialect_cymysql._get_server_version_info
|
9,293
|
@_coldefs.deleter
def _coldefs(self):
try:
del self.__dict__['_coldefs']
except __HOLE__ as exc:
raise AttributeError(exc.args[0])
|
KeyError
|
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/fitsrec.py/FITS_rec._coldefs
|
9,294
|
def __del__(self):
try:
del self._coldefs
except __HOLE__:
pass
else:
if self.dtype.fields is not None:
for col in self._col_weakrefs:
if isinstance(col.array, np.ndarray):
col.array = col.array.copy()
|
AttributeError
|
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/fitsrec.py/FITS_rec.__del__
|
9,295
|
def _convert_ascii(self, column, field):
"""
Special handling for ASCII table columns to convert columns containing
numeric types to actual numeric arrays from the string representation.
"""
format = column.format
recformat = ASCII2NUMPY[format[0]]
# if the string = TNULL, return ASCIITNULL
nullval = str(column.null).strip().encode('ascii')
if len(nullval) > format.width:
nullval = nullval[:format.width]
dummy = np.char.ljust(field, format.width)
dummy = np.char.replace(dummy, encode_ascii('D'), encode_ascii('E'))
null_fill = encode_ascii(str(ASCIITNULL).rjust(format.width))
dummy = np.where(np.char.strip(dummy) == nullval, null_fill, dummy)
try:
dummy = np.array(dummy, dtype=recformat)
except __HOLE__ as exc:
indx = self._coldefs.names.index(column.name)
raise ValueError(
'%s; the header may be missing the necessary TNULL%d '
'keyword or the table contains invalid data' %
(exc, indx + 1))
return dummy
|
ValueError
|
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/fitsrec.py/FITS_rec._convert_ascii
|
9,296
|
@staff_member_required
def sponsor_export_data(request):
sponsors = []
data = ""
for sponsor in Sponsor.objects.order_by("added"):
d = {
"name": sponsor.name,
"url": sponsor.external_url,
"level": (sponsor.level.order, sponsor.level.name),
"description": "",
}
for sponsor_benefit in sponsor.sponsor_benefits.all():
if sponsor_benefit.benefit_id == 2:
d["description"] = sponsor_benefit.text
sponsors.append(d)
def izip_longest(*args):
fv = None
def sentinel(counter=([fv] * (len(args) - 1)).pop):
yield counter()
iters = [itertools.chain(it, sentinel(), itertools.repeat(fv)) for it in args]
try:
for tup in itertools.izip(*iters):
yield tup
except __HOLE__:
pass
def pairwise(iterable):
a, b = itertools.tee(iterable)
b.next()
return izip_longest(a, b)
def level_key(s):
return s["level"]
for level, level_sponsors in itertools.groupby(sorted(sponsors, key=level_key), level_key):
data += "%s\n" % ("-" * (len(level[1]) + 4))
data += "| %s |\n" % level[1]
data += "%s\n\n" % ("-" * (len(level[1]) + 4))
for sponsor, next in pairwise(level_sponsors):
description = sponsor["description"].strip()
description = description if description else "-- NO DESCRIPTION FOR THIS SPONSOR --"
data += "%s\n\n%s" % (sponsor["name"], description)
if next is not None:
data += "\n\n%s\n\n" % ("-" * 80)
else:
data += "\n\n"
return HttpResponse(data, content_type="text/plain;charset=utf-8")
|
IndexError
|
dataset/ETHPy150Open pinax/symposion/symposion/sponsorship/views.py/sponsor_export_data
|
9,297
|
def _update_image(facebook_id, image_url):
'''
Updates the user profile's image to the given image url
Unfortunately this is quite a pain to get right with Django
Suggestions to improve this are welcome
'''
image_name = 'fb_image_%s.jpg' % facebook_id
image_temp = NamedTemporaryFile()
try:
image_response = urllib2.urlopen(image_url)
except AttributeError:
image_response = urllib.request.urlopen(image_url)
image_content = image_response.read()
image_temp.write(image_content)
http_message = image_response.info()
image_size = len(image_content)
try:
content_type = http_message.type
except __HOLE__:
content_type = http_message.get_content_type()
image_file = InMemoryUploadedFile(
file=image_temp, name=image_name, field_name='image',
content_type=content_type, size=image_size, charset=None
)
image_file.seek(0)
image_temp.flush()
return image_name, image_file
|
AttributeError
|
dataset/ETHPy150Open tschellenbach/Django-facebook/django_facebook/connect.py/_update_image
|
9,298
|
def assertFailsValidation(self, clean, failed_fields):
self.assertRaises(ValidationError, clean)
try:
clean()
except __HOLE__, e:
self.assertEqual(sorted(failed_fields), sorted(e.message_dict.keys()))
|
ValidationError
|
dataset/ETHPy150Open adieu/django-nonrel/tests/modeltests/validation/__init__.py/ValidationTestCase.assertFailsValidation
|
9,299
|
def assertFieldFailsValidationWithMessage(self, clean, field_name, message):
self.assertRaises(ValidationError, clean)
try:
clean()
except __HOLE__, e:
self.assertTrue(field_name in e.message_dict)
self.assertEqual(message, e.message_dict[field_name])
|
ValidationError
|
dataset/ETHPy150Open adieu/django-nonrel/tests/modeltests/validation/__init__.py/ValidationTestCase.assertFieldFailsValidationWithMessage
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.