Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,100
def find_in_workspaces(search_dirs=None, project=None, path=None, _workspaces=None, considered_paths=None, first_matching_workspace_only=False, first_match_only=False, workspace_to_source_spaces=None, source_path_to_packages=None): ''' Find all paths which match the search criteria. All workspaces are searched in order. Each workspace, each search_in subfolder, the project name and the path are concatenated to define a candidate path. If the candidate path exists it is appended to the result list. Note: the search might return multiple paths for 'share' from devel- and source-space. :param search_dir: The list of subfolders to search in (default contains all valid values: 'bin', 'etc', 'lib', 'libexec', 'share'), ``list`` :param project: The project name to search for (optional, not possible with the global search_in folders 'bin' and 'lib'), ``str`` :param path: The path, ``str`` :param _workspaces: (optional, used for unit tests), the list of workspaces to use. :param considered_paths: If not None, function will append all path that were searched :param first_matching_workspace_only: if True returns all results found for first workspace with results :param first_match_only: if True returns first path found (supercedes first_matching_workspace_only) :param workspace_to_source_spaces: the dictionary is populated with mappings from workspaces to source paths, pass in the same dictionary to avoid repeated reading of the catkin marker file :param source_path_to_packages: the dictionary is populated with mappings from source paths to packages, pass in the same dictionary to avoid repeated crawling :raises ValueError: if search_dirs contains an invalid folder name :returns: List of paths ''' search_dirs = _get_valid_search_dirs(search_dirs, project) if 'libexec' in search_dirs: search_dirs.insert(search_dirs.index('libexec'), 'lib') if _workspaces is None: _workspaces = get_workspaces() if workspace_to_source_spaces is None: workspace_to_source_spaces = {} if source_path_to_packages is None: source_path_to_packages = {} paths = [] existing_paths = [] try: for workspace in (_workspaces or []): for sub in search_dirs: # search in workspace p = os.path.join(workspace, sub) if project: p = os.path.join(p, project) if path: p = os.path.join(p, path) paths.append(p) if os.path.exists(p): existing_paths.append(p) if first_match_only: raise StopIteration # for search in share also consider source spaces if project is not None and sub == 'share': if workspace not in workspace_to_source_spaces: workspace_to_source_spaces[workspace] = get_source_paths(workspace) for source_path in workspace_to_source_spaces[workspace]: if source_path not in source_path_to_packages: source_path_to_packages[source_path] = find_packages(source_path) matching_packages = [p for p, pkg in source_path_to_packages[source_path].items() if pkg.name == project] if matching_packages: p = source_path if matching_packages[0] != os.curdir: p = os.path.join(p, matching_packages[0]) if path is not None: p = os.path.join(p, path) paths.append(p) if os.path.exists(p): existing_paths.append(p) if first_match_only: raise StopIteration if first_matching_workspace_only and existing_paths: break except __HOLE__: pass if considered_paths is not None: considered_paths.extend(paths) return existing_paths
StopIteration
dataset/ETHPy150Open ros/catkin/python/catkin/find_in_workspaces.py/find_in_workspaces
8,101
def _remove_method(self, meths, method): try: meths.remove(method) except __HOLE__: pass
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._remove_method
8,102
def _find_toggle_methods(self, klass, methods): """Find/store methods of the form <Value>{On,Off} in the given `methods`. Returns the remaining list of methods. """ meths = methods[:] tm = self.toggle_meths for method in meths[:]: if method[-2:] == 'On': key = method[:-2] if (key + 'Off') in meths and ('Get' + key) in meths: tm[key] = None meths.remove(method) meths.remove(key + 'Off') self._remove_method(meths, 'Set' + key) self._remove_method(meths, 'Get' + key) # get defaults if tm: obj = self._get_instance(klass) if obj: for key in tm: try: tm[key] = getattr(obj, 'Get%s'%key)() except __HOLE__, e: log("Type error during parsing: class %s will not expose method %s " % (klass.__name__, key)) except AttributeError, e: log("Attribute error during parsing: class %s will not expose method %s " % (klass.__name__, key)) return meths
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_toggle_methods
8,103
def _find_state_methods(self, klass, methods): """Find/store methods of the form Set<Prop>To<Value> in the given `methods`. Returns the remaining list of methods. The method also computes the mapped value of the different <Values>. """ # These ignored ones are really not state methods. ignore = ['SetUpdateExtentToWholeExtent'] meths = methods[:] sm = self.state_meths for method in meths[:]: if method not in ignore and method[:3] == 'Set': # Methods of form Set<Prop>To<Value> match = self._state_patn.search(method) # Second cond. ensures that this is not an accident. if match and (('Get'+method[3:]) not in meths): key = method[3:match.start()] # The <Prop> part. if (('Get' + key) in methods): val = method[match.start()+2:] # <Value> part. meths.remove(method) if sm.has_key(key): sm[key].append([val, None]) else: sm[key] = [[val, None]] meths.remove('Get'+ key) self._remove_method(meths, 'Set'+ key) if ('Get' + key + 'MaxValue') in meths: meths.remove('Get' + key + 'MaxValue') meths.remove('Get' + key + 'MinValue') try: meths.remove('Get' + key + 'AsString') except __HOLE__: pass # Find the values for each of the states, i.e. find that # vtkProperty.SetRepresentationToWireframe() corresponds to # vtkProperty.SetRepresentation(1). if sm: obj = self._get_instance(klass) if obj: for key, values in sm.items(): default = getattr(obj, 'Get%s'%key)() for x in values[:]: try: getattr(obj, 'Set%sTo%s'%(key, x[0]))() except: continue val = getattr(obj, 'Get%s'%key)() x[1] = val if val == default: values.insert(0, [x[0], val]) return meths
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_state_methods
8,104
def _find_get_set_methods(self, klass, methods): """Find/store methods of the form {Get,Set}Prop in the given `methods` and returns the remaining list of methods. Note that it makes sense to call this *after* `_find_state_methods` is called in order to avoid incorrect duplication. This method also computes the default value and the ranges of the arguments (when possible) by using the Get<Prop>{MaxValue,MinValue} methods. """ meths = methods[:] gsm = self.get_set_meths for method in meths[:]: # Methods of the Set/Get form. if method in ['Get', 'Set']: # This occurs with the vtkInformation class. continue elif (method[:3] == 'Set') and ('Get' + method[3:]) in methods: key = method[3:] meths.remove('Set' + key) meths.remove('Get' + key) if ('Get' + key + 'MaxValue') in meths: meths.remove('Get' + key + 'MaxValue') meths.remove('Get' + key + 'MinValue') gsm[key] = 1 else: gsm[key] = None # Find the default and range of the values. if gsm: obj = self._get_instance(klass) if obj: klass_name = klass.__name__ for key, value in gsm.items(): if klass_name == 'vtkPolyData': # Evil hack, this class segfaults! default = None else: try: default = getattr(obj, 'Get%s'%key)() except __HOLE__: default = None if value: low = getattr(obj, 'Get%sMinValue'%key)() high = getattr(obj, 'Get%sMaxValue'%key)() gsm[key] = (default, (low, high)) else: gsm[key] = (default, None) else: # We still might have methods that have a default range. for key, value in gsm.items(): if value == 1: gsm[key] = None return meths
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_get_set_methods
8,105
def _get_instance(self, klass): """Given a VTK class, `klass`, returns an instance of the class. If the class is abstract, it uses the class tree to return an instantiable subclass. This is necessary to get the values of the 'state' methods and the ranges for the Get/Set methods. """ obj = None try: obj = klass() except __HOLE__: if self._tree: t = self._tree n = t.get_node(klass.__name__) # Wendel if n == None: return False for c in n.children: obj = self._get_instance(t.get_class(c.name)) if obj: break return obj
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._get_instance
8,106
def load_config(config_file): error = None paths = [config_file] if config_file else ["blockade.yaml", "blockade.yml"] try: for path in paths: try: with open(path) as f: d = yaml.safe_load(f) return BlockadeConfig.from_dict(d) except __HOLE__ as e: if e.errno != errno.ENOENT: raise except Exception as e: error = e raise BlockadeError("Failed to load config (from --config, " "./blockade.yaml, or ./blockade.yml)" + (str(error) if error else ""))
IOError
dataset/ETHPy150Open dcm-oss/blockade/blockade/cli.py/load_config
8,107
def main(args=None): parser = setup_parser() opts = parser.parse_args(args=args) rc = 0 try: opts.func(opts) except InsufficientPermissionsError as e: puts_err(colored.red("\nInsufficient permissions error:\n") + str(e) + "\n") rc = 1 except BlockadeError as e: puts_err(colored.red("\nError:\n") + str(e) + "\n") rc = 1 except __HOLE__: puts_err(colored.red("Caught Ctrl-C. exiting!")) except: puts_err( colored.red("\nUnexpected error! This may be a Blockade bug.\n")) traceback.print_exc() rc = 2 sys.exit(rc)
KeyboardInterrupt
dataset/ETHPy150Open dcm-oss/blockade/blockade/cli.py/main
8,108
def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('ordinal_position', node) if value is not None: try: self.ordinal_position = int(value) except __HOLE__ as exp: raise_parse_error(node, 'Bad integer attribute: %s' % exp) if self.ordinal_position < 0: raise_parse_error(node, 'Invalid NonNegativeInteger')
ValueError
dataset/ETHPy150Open CybOXProject/python-cybox/cybox/bindings/http_session_object.py/HTTPRequestResponseType.buildAttributes
8,109
def execute(self): """ Called to execute the task. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed(). """ T = self.tm.trace if T: T.write(self.trace_message(u'Task.execute()', self.node)) try: cached_targets = [] for t in self.targets: if not t.retrieve_from_cache(): break cached_targets.append(t) if len(cached_targets) < len(self.targets): # Remove targets before building. It's possible that we # partially retrieved targets from the cache, leaving # them in read-only mode. That might cause the command # to fail. # for t in cached_targets: try: t.fs.unlink(t.path) except (__HOLE__, OSError): pass self.targets[0].build() else: for t in cached_targets: t.cached = 1 except SystemExit: exc_value = sys.exc_info()[1] raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code) except SCons.Errors.UserError: raise except SCons.Errors.BuildError: raise except Exception, e: buildError = SCons.Errors.convert_to_BuildError(e) buildError.node = self.targets[0] buildError.exc_info = sys.exc_info() raise buildError
IOError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Task.execute
8,110
def _exception_raise(self): """ Raises a pending exception that was recorded while getting a Task ready for execution. """ exc = self.exc_info()[:] try: exc_type, exc_value, exc_traceback = exc except __HOLE__: exc_type, exc_value = exc exc_traceback = None raise exc_type, exc_value, exc_traceback
ValueError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Task._exception_raise
8,111
def find_next_candidate(self): """ Returns the next candidate Node for (potential) evaluation. The candidate list (really a stack) initially consists of all of the top-level (command line) targets provided when the Taskmaster was initialized. While we walk the DAG, visiting Nodes, all the children that haven't finished processing get pushed on to the candidate list. Each child can then be popped and examined in turn for whether *their* children are all up-to-date, in which case a Task will be created for their actual evaluation and potential building. Here is where we also allow candidate Nodes to alter the list of Nodes that should be examined. This is used, for example, when invoking SCons in a source directory. A source directory Node can return its corresponding build directory Node, essentially saying, "Hey, you really need to build this thing over here instead." """ try: return self.candidates.pop() except __HOLE__: pass try: node = self.top_targets_left.pop() except IndexError: return None self.current_top = node alt, message = node.alter_targets() if alt: self.message = message self.candidates.append(node) self.candidates.extend(self.order(alt)) node = self.candidates.pop() return node
IndexError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster.find_next_candidate
8,112
def _find_next_ready_node(self): """ Finds the next node that is ready to be built. This is *the* main guts of the DAG walk. We loop through the list of candidates, looking for something that has no un-built children (i.e., that is a leaf Node or has dependencies that are all leaf Nodes or up-to-date). Candidate Nodes are re-scanned (both the target Node itself and its sources, which are always scanned in the context of a given target) to discover implicit dependencies. A Node that must wait for some children to be built will be put back on the candidates list after the children have finished building. A Node that has been put back on the candidates list in this way may have itself (or its sources) re-scanned, in order to handle generated header files (e.g.) and the implicit dependencies therein. Note that this method does not do any signature calculation or up-to-date check itself. All of that is handled by the Task class. This is purely concerned with the dependency graph walk. """ self.ready_exc = None T = self.trace if T: T.write(u'\n' + self.trace_message('Looking for a node to evaluate')) while True: node = self.next_candidate() if node is None: if T: T.write(self.trace_message('No candidate anymore.') + u'\n') return None node = node.disambiguate() state = node.get_state() # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node if CollectStats: if not hasattr(node, 'stats'): node.stats = Stats() StatsNodes.append(node) S = node.stats S.considered = S.considered + 1 else: S = None if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node))) if state == NODE_NO_STATE: # Mark this node as being on the execution stack: node.set_state(NODE_PENDING) elif state > NODE_PENDING: # Skip this node if it has already been evaluated: if S: S.already_handled = S.already_handled + 1 if T: T.write(self.trace_message(u' already handled (executed)')) continue executor = node.get_executor() try: children = executor.get_all_children() except __HOLE__: exc_value = sys.exc_info()[1] e = SCons.Errors.ExplicitExit(node, exc_value.code) self.ready_exc = (SCons.Errors.ExplicitExit, e) if T: T.write(self.trace_message(' SystemExit')) return node except Exception, e: # We had a problem just trying to figure out the # children (like a child couldn't be linked in to a # VariantDir, or a Scanner threw something). Arrange to # raise the exception when the Task is "executed." self.ready_exc = sys.exc_info() if S: S.problem = S.problem + 1 if T: T.write(self.trace_message(' exception %s while scanning children.\n' % e)) return node children_not_visited = [] children_pending = set() children_not_ready = [] children_failed = False for child in chain(executor.get_all_prerequisites(), children): childstate = child.get_state() if T: T.write(self.trace_message(u' ' + self.trace_node(child))) if childstate == NODE_NO_STATE: children_not_visited.append(child) elif childstate == NODE_PENDING: children_pending.add(child) elif childstate == NODE_FAILED: children_failed = True if childstate <= NODE_EXECUTING: children_not_ready.append(child) # These nodes have not even been visited yet. Add # them to the list so that on some next pass we can # take a stab at evaluating them (or their children). children_not_visited.reverse() self.candidates.extend(self.order(children_not_visited)) #if T and children_not_visited: # T.write(self.trace_message(' adding to candidates: %s' % map(str, children_not_visited))) # T.write(self.trace_message(' candidates now: %s\n' % map(str, self.candidates))) # Skip this node if any of its children have failed. # # This catches the case where we're descending a top-level # target and one of our children failed while trying to be # built by a *previous* descent of an earlier top-level # target. # # It can also occur if a node is reused in multiple # targets. One first descends though the one of the # target, the next time occurs through the other target. # # Note that we can only have failed_children if the # --keep-going flag was used, because without it the build # will stop before diving in the other branch. # # Note that even if one of the children fails, we still # added the other children to the list of candidate nodes # to keep on building (--keep-going). if children_failed: for n in executor.get_action_targets(): n.set_state(NODE_FAILED) if S: S.child_failed = S.child_failed + 1 if T: T.write(self.trace_message('****** %s\n' % self.trace_node(node))) continue if children_not_ready: for child in children_not_ready: # We're waiting on one or more derived targets # that have not yet finished building. if S: S.not_built = S.not_built + 1 # Add this node to the waiting parents lists of # anything we're waiting on, with a reference # count so we can be put back on the list for # re-evaluation when they've all finished. node.ref_count = node.ref_count + child.add_to_waiting_parents(node) if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' % (self.trace_node(node), repr(str(child))))) if T: for pc in children_pending: T.write(self.trace_message(' adding %s to the pending children set\n' % self.trace_node(pc))) self.pending_children = self.pending_children | children_pending continue # Skip this node if it has side-effects that are # currently being built: wait_side_effects = False for se in executor.get_action_side_effects(): if se.get_state() == NODE_EXECUTING: se.add_to_waiting_s_e(node) wait_side_effects = True if wait_side_effects: if S: S.side_effects = S.side_effects + 1 continue # The default when we've gotten through all of the checks above: # this node is ready to be built. if S: S.build = S.build + 1 if T: T.write(self.trace_message(u'Evaluating %s\n' % self.trace_node(node))) # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node return node return None
SystemExit
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster._find_next_ready_node
8,113
def will_not_build(self, nodes, node_func=lambda n: None): """ Perform clean-up about nodes that will never be built. Invokes a user defined function on all of these nodes (including all of their parents). """ T = self.trace pending_children = self.pending_children to_visit = set(nodes) pending_children = pending_children - to_visit if T: for n in nodes: T.write(self.trace_message(' removing node %s from the pending children set\n' % self.trace_node(n))) try: while len(to_visit): node = to_visit.pop() node_func(node) # Prune recursion by flushing the waiting children # list immediately. parents = node.waiting_parents node.waiting_parents = set() to_visit = to_visit | parents pending_children = pending_children - parents for p in parents: p.ref_count = p.ref_count - 1 if T: T.write(self.trace_message(' removing parent %s from the pending children set\n' % self.trace_node(p))) except __HOLE__: # The container to_visit has been emptied. pass # We have the stick back the pending_children list into the # taskmaster because the python 1.5.2 compatibility does not # allow us to use in-place updates self.pending_children = pending_children
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster.will_not_build
8,114
@classmethod def mpc_convert_lhs(cls, x): try: y = cls.context.convert(x) return y except __HOLE__: return NotImplemented
TypeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_mp_python.py/_mpc.mpc_convert_lhs
8,115
def convert(ctx, x, strings=True): """ Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``, ``mpc``, ``int``, ``float``, ``complex``, the conversion will be performed losslessly. If *x* is a string, the result will be rounded to the present working precision. Strings representing fractions or complex numbers are permitted. >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> mpmathify(3.5) mpf('3.5') >>> mpmathify('2.1') mpf('2.1000000000000001') >>> mpmathify('3/4') mpf('0.75') >>> mpmathify('2+3j') mpc(real='2.0', imag='3.0') """ if type(x) in ctx.types: return x if isinstance(x, int_types): return ctx.make_mpf(from_int(x)) if isinstance(x, float): return ctx.make_mpf(from_float(x)) if isinstance(x, complex): return ctx.make_mpc((from_float(x.real), from_float(x.imag))) prec, rounding = ctx._prec_rounding if isinstance(x, rational.mpq): p, q = x._mpq_ return ctx.make_mpf(from_rational(p, q, prec)) if strings and isinstance(x, basestring): try: _mpf_ = from_str(x, prec, rounding) return ctx.make_mpf(_mpf_) except __HOLE__: pass if hasattr(x, '_mpf_'): return ctx.make_mpf(x._mpf_) if hasattr(x, '_mpc_'): return ctx.make_mpc(x._mpc_) if hasattr(x, '_mpmath_'): return ctx.convert(x._mpmath_(prec, rounding)) return ctx._convert_fallback(x, strings)
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_mp_python.py/PythonMPContext.convert
8,116
def get_ext_modules(use_cython=USE_CYTHON): global cmdclass python_header_dir = get_python_header_dir() if use_cython: try: from Cython.Distutils import build_ext except __HOLE__: stderr.write('\"cython\" is not installed. Forcing \"USE_CYTHON\" ' 'to \"False\" in order to install.\n') use_cython = False if use_cython: ext_modules = [Extension('src.features', ['src/features.pyx'], include_dirs=[python_header_dir]), Extension('src.experiments', ['src/experiments.pyx'], include_dirs=[python_header_dir]), Extension('src.datasets', ['src/datasets.pyx'], include_dirs=[python_header_dir]), Extension('src.mongodb', ['src/mongodb.pyx'], include_dirs=[python_header_dir])] cmdclass.update({'build_ext': build_ext}) return ext_modules ext_modules = [Extension('src.features', ['src/features.c'], include_dirs=[python_header_dir]), Extension('src.experiments', ['src/experiments.pyx'], include_dirs=[python_header_dir]), Extension('src.datasets', ['src/datasets.c'], include_dirs=[python_header_dir]), Extension('src.mongodb', ['src/mongodb.c'], include_dirs=[python_header_dir])] return ext_modules
ImportError
dataset/ETHPy150Open mulhod/reviewer_experience_prediction/setup.py/get_ext_modules
8,117
def __init__(self, qname, rdtype, rdclass, response): self.qname = qname self.rdtype = rdtype self.rdclass = rdclass self.response = response min_ttl = -1 rrset = None for count in xrange(0, 15): try: rrset = response.find_rrset(response.answer, qname, rdclass, rdtype) if min_ttl == -1 or rrset.ttl < min_ttl: min_ttl = rrset.ttl break except __HOLE__: if rdtype != dns.rdatatype.CNAME: try: crrset = response.find_rrset(response.answer, qname, rdclass, dns.rdatatype.CNAME) if min_ttl == -1 or crrset.ttl < min_ttl: min_ttl = crrset.ttl for rd in crrset: qname = rd.target break continue except KeyError: raise NoAnswer raise NoAnswer if rrset is None: raise NoAnswer self.rrset = rrset self.expiration = time.time() + min_ttl
KeyError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Answer.__init__
8,118
def read_resolv_conf(self, f): """Process f as a file in the /etc/resolv.conf format. If f is a string, it is used as the name of the file to open; otherwise it is treated as the file itself.""" if isinstance(f, str) or isinstance(f, unicode): try: f = open(f, 'r') except __HOLE__: # /etc/resolv.conf doesn't exist, can't be read, etc. # We'll just use the default resolver configuration. self.nameservers = ['127.0.0.1'] return want_close = True else: want_close = False try: for l in f: if len(l) == 0 or l[0] == '#' or l[0] == ';': continue tokens = l.split() if len(tokens) == 0: continue if tokens[0] == 'nameserver': self.nameservers.append(tokens[1]) elif tokens[0] == 'domain': self.domain = dns.name.from_text(tokens[1]) elif tokens[0] == 'search': for suffix in tokens[1:]: self.search.append(dns.name.from_text(suffix)) finally: if want_close: f.close() if len(self.nameservers) == 0: self.nameservers.append('127.0.0.1')
IOError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Resolver.read_resolv_conf
8,119
def _win32_is_nic_enabled(self, lm, guid, interface_key): # Look in the Windows Registry to determine whether the network # interface corresponding to the given guid is enabled. # # (Code contributed by Paul Marks, thanks!) # try: # This hard-coded location seems to be consistent, at least # from Windows 2000 through Vista. connection_key = _winreg.OpenKey( lm, r'SYSTEM\CurrentControlSet\Control\Network' r'\{4D36E972-E325-11CE-BFC1-08002BE10318}' r'\%s\Connection' % guid) try: # The PnpInstanceID points to a key inside Enum (pnp_id, ttype) = _winreg.QueryValueEx( connection_key, 'PnpInstanceID') if ttype != _winreg.REG_SZ: raise ValueError device_key = _winreg.OpenKey( lm, r'SYSTEM\CurrentControlSet\Enum\%s' % pnp_id) try: # Get ConfigFlags for this device (flags, ttype) = _winreg.QueryValueEx( device_key, 'ConfigFlags') if ttype != _winreg.REG_DWORD: raise ValueError # Based on experimentation, bit 0x1 indicates that the # device is disabled. return not (flags & 0x1) finally: device_key.Close() finally: connection_key.Close() except (EnvironmentError, __HOLE__): # Pre-vista, enabled interfaces seem to have a non-empty # NTEContextList; this was how dnspython detected enabled # nics before the code above was contributed. We've retained # the old method since we don't know if the code above works # on Windows 95/98/ME. try: (nte, ttype) = _winreg.QueryValueEx(interface_key, 'NTEContextList') return nte is not None except WindowsError: return False
ValueError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Resolver._win32_is_nic_enabled
8,120
def parseBitShiftConstant(s, pos, tokens): try: c1, c2 = tokens[0] return int(c1) << int(c2) except __HOLE__: c1, c2, c3 = tokens[0] return (int(c1) << int(c2)) - c3 # # Rudimentary C source grammar # # Limitations: # # - Macros are not processed. # - The function body parser eats newlines and whitespace. # - Only very basic function pointers are supported. # - Structure typedefs are not supported. # # Make line feeds white space. Note that this breaks any syntax based on LineStart(), etc.
ValueError
dataset/ETHPy150Open skyostil/tracy/src/generator/Parser.py/parseBitShiftConstant
8,121
def parseSource(source): """ Parses the given source string and adds all found functions to the library. @param header: Source text @returns: A library containing the parsed functions """ task = Task.startTask("parser", "Parsing type declarations", len(source)) library = Library() # Read the type definitions typedefs = [] for match, pos, l in typedefDecl.scanString(source): task.updateProgress(pos) # Map enumerations to integers if match[0] == "enum": name = match[-1] type = Type("int") for i, e in enumerate(match[1]): enumeration, value = e if value is None: value = i type.addSymbolicConstant(enumeration, value) library.constants[enumeration] = value else: name, type = match[0] library.typeDefs[Type(name)] = type task.finish() # Read preprocessor constants task = Task.startTask("parser", "Parsing preprocessor constants", len(source)) for match, pos, l in preprocessorCommand.scanString(source): task.updateProgress(pos) # Only look for #define if match.command != "define": continue # Only accept integral constants try: value = parseInteger(None, None, [match.value]) except __HOLE__: continue library.constants[match.name] = value task.finish() def where(pos): return "Line %d, column %s" % (lineno(pos, source), col(pos, source)) task = Task.startTask("parser", "Parsing functions", len(source)) for match, pos, l in function.scanString(source): task.updateProgress(pos) name, type = match.name[0] if not name: continue f = Function(name, type) f.language = "c" for name, type in match.args: if not name or not type: continue f.parameters[name] = Parameter(name, type) # Grab the code if any if match.body: f.body = match.body library.functions[f.name] = f task.finish() return library
ValueError
dataset/ETHPy150Open skyostil/tracy/src/generator/Parser.py/parseSource
8,122
def __getattr__(self, attr): for replacement in settings.REPLACEMENTS: attr = attr.replace(replacement, '') attr = attr.lower() if attr == 'random': attr = self.data['randomize'][ str(random.randint(0, len(self.data['randomize']) - 1)) ] else: for shortcut, value in settings.SHORTCUTS: if attr == shortcut: attr = value break try: return self.data['browsers'][attr][ random.randint( 0, len(self.data['browsers'][attr]) - 1 ) ] except __HOLE__: return None
KeyError
dataset/ETHPy150Open SickRage/SickRage/lib/fake_useragent/fake.py/UserAgent.__getattr__
8,123
def queryset(self, request, queryset): try: return queryset.filter(**self.used_parameters) except __HOLE__ as e: raise IncorrectLookupParameters(e)
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/filters.py/FieldListFilter.queryset
8,124
def search_ip(request): if request.method == "POST": form = IpSearchForm(request.POST) try: if form.is_valid(): ip_type = form.cleaned_data['ip_type'] search_ip = form.cleaned_data['search_ip'] try: if ip_type == '4': network = ipaddr.IPv4Network(search_ip) if ip_type == '6': network = ipaddr.IPv6Network(search_ip) except ipaddr.AddressValueError, e: form._errors['__all__'] = ErrorList( ["Bad IPv{0} Address {1}".format(ip_type, search_ip)]) return render(request, 'core/core_form.html', { 'form': form }) try: network = Network.objects.get(network_str=search_ip) search_ip = network found_exact = True except ObjectDoesNotExist: found_exact = False network = Network(ip_type, network_str=search_ip, ip_type=ip_type) parent = calc_parent(network) eldars, sub_networks = calc_networks(network) if ip_type == '6': sip_upper, sip_lower = ipv6_to_longs(network.network.ip) eip_upper, eip_lower = ipv6_to_longs( network.network.broadcast) else: sip_upper, sip_lower = 0, int(network.network.ip) eip_upper, eip_lower = 0, int(network.network.broadcast) addrs_count = AddressRecord.objects.filter( ip_upper__gte=sip_upper, ip_lower__gte=sip_lower, ip_upper__lte=eip_upper, ip_lower__lte=eip_lower).count() if addrs_count > 100: addrs = None # This is too much else: addrs = AddressRecord.objects.filter( ip_upper__gte=sip_upper, ip_lower__gte=sip_lower, ip_upper__lte=eip_upper, ip_lower__lte=eip_lower) ptrs_count = PTR.objects.filter( ip_upper__gte=sip_upper, ip_lower__gte=sip_lower, ip_upper__lte=eip_upper, ip_lower__lte=eip_lower).count() if ptrs_count > 100: ptrs = None # This is too much else: ptrs = PTR.objects.filter( ip_upper__gte=sip_upper, ip_lower__gte=sip_lower, ip_upper__lte=eip_upper, ip_lower__lte=eip_lower) return render(request, 'core/core_results.html', { 'search_ip': search_ip, 'found_exact': found_exact, 'addrs': addrs, 'addrs_count': addrs_count, 'ptrs_count': ptrs_count, 'ptrs': ptrs, 'parent': parent, 'eldars': eldars, 'sub_networks': sub_networks, }) except __HOLE__, e: form._errors['__all__'] = ErrorList(e.messages) return render(request, 'core/core_form.html', { 'form': form }) else: form = IpSearchForm() return render(request, 'core/core_form.html', { 'form': form })
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/core/views.py/search_ip
8,125
def _set_submission_time_to_query(query, request): query[SUBMISSION_TIME] = {} try: if request.GET.get('start'): query[SUBMISSION_TIME]['$gte'] = format_date_for_mongo( request.GET['start']) if request.GET.get('end'): query[SUBMISSION_TIME]['$lte'] = format_date_for_mongo( request.GET['end']) except __HOLE__: return HttpResponseBadRequest( _("Dates must be in the format YY_MM_DD_hh_mm_ss")) return query
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/_set_submission_time_to_query
8,126
def dd_for_params(id_string, owner, request): start = end = None dd = DataDictionary.objects.get(id_string__exact=id_string, user=owner) if request.GET.get('start'): try: start = encode(request.GET['start']) except __HOLE__: # bad format return [False, HttpResponseBadRequest( _(u'Start time format must be YY_MM_DD_hh_mm_ss')) ] if request.GET.get('end'): try: end = encode(request.GET['end']) except ValueError: # bad format return [False, HttpResponseBadRequest( _(u'End time format must be YY_MM_DD_hh_mm_ss')) ] if start or end: dd.instances_for_export = instances_for_export(dd, start, end) return [True, dd]
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/dd_for_params
8,127
def charts(request, username, id_string): xform, is_owner, can_edit, can_view = get_xform_and_perms( username, id_string, request) # no access if not (xform.shared_data or can_view or request.session.get('public_link') == xform.uuid): return HttpResponseForbidden(_(u'Not shared.')) try: lang_index = int(request.GET.get('lang', 0)) except __HOLE__: lang_index = 0 try: page = int(request.GET.get('page', 0)) except ValueError: page = 0 else: page = max(page - 1, 0) summaries = build_chart_data(xform, lang_index, page) if request.is_ajax(): template = 'charts_snippet.html' else: template = 'charts.html' return render(request, template, { 'xform': xform, 'summaries': summaries, 'page': page + 1 })
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/charts
8,128
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first, saves 30-40% in performance when s # is an instance of unicode. This function gets called often in that # setting. if isinstance(s, unicode): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, basestring,): if hasattr(s, '__unicode__'): s = unicode(s) else: try: s = unicode(str(s), encoding, errors) except UnicodeEncodeError: if not isinstance(s, Exception): raise # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII data without special # handling to display as a string. We need to handle this # without raising a further exception. We do an # approximation to what the Exception's standard str() # output should be. s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) elif not isinstance(s, unicode): # Note: We use .decode() here, instead of unicode(s, encoding, # errors), so that if s is a SafeString, it ends up being a # SafeUnicode at the end. s = s.decode(encoding, errors) except __HOLE__, e: if not isinstance(s, Exception): raise UnicodeDecodeError(s, *e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) return s
UnicodeDecodeError
dataset/ETHPy150Open dcramer/sentry-old/sentry/utils/encoding.py/force_unicode
8,129
def _HashFile(self, fd): """Look for the required hashes in the file.""" hashes = fd.Get(fd.Schema.HASH) if hashes: found_all = True for fingerprint_type, hash_types in self.HASH_TYPES.iteritems(): for hash_type in hash_types: if fingerprint_type == "pecoff": hash_type = "pecoff_%s" % hash_type if not hashes.HasField(hash_type): found_all = False break if not found_all: break if found_all: return hashes fingerprinter = fingerprint.Fingerprinter(fd) if "generic" in self.HASH_TYPES: hashers = self._GetHashers(self.HASH_TYPES["generic"]) fingerprinter.EvalGeneric(hashers=hashers) if "pecoff" in self.HASH_TYPES: hashers = self._GetHashers(self.HASH_TYPES["pecoff"]) if hashers: fingerprinter.EvalPecoff(hashers=hashers) if not hashes: hashes = fd.Schema.HASH() for result in fingerprinter.HashIt(): fingerprint_type = result["name"] for hash_type in self.HASH_TYPES[fingerprint_type]: if hash_type not in result: continue if hash_type == "SignedData": # There can be several certs in the same file. for signed_data in result[hash_type]: hashes.signed_data.Append(revision=signed_data[0], cert_type=signed_data[1], certificate=signed_data[2]) continue # Set the hashes in the original object if fingerprint_type == "generic": hashes.Set(hash_type, result[hash_type]) elif fingerprint_type == "pecoff": hashes.Set("pecoff_%s" % hash_type, result[hash_type]) else: logging.error("Unknown fingerprint_type %s.", fingerprint_type) try: fd.Set(hashes) except __HOLE__: pass return hashes
IOError
dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/filestore.py/HashFileStore._HashFile
8,130
def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): """Load a datasets as downloaded from http://mlcomp.org Parameters ---------- name_or_id : the integer id or the string name metadata of the MLComp dataset to load set_ : select the portion to load: 'train', 'test' or 'raw' mlcomp_root : the filesystem path to the root folder where MLComp datasets are stored, if mlcomp_root is None, the MLCOMP_DATASETS_HOME environment variable is looked up instead. **kwargs : domain specific kwargs to be passed to the dataset loader. Read more in the :ref:`User Guide <datasets>`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'filenames', the files holding the raw to learn, 'target', the classification labels (integer index), 'target_names', the meaning of the labels, and 'DESCR', the full description of the dataset. Note on the lookup process: depending on the type of name_or_id, will choose between integer id lookup or metadata name lookup by looking at the unzipped archives and metadata file. TODO: implement zip dataset loading too """ if mlcomp_root is None: try: mlcomp_root = os.environ['MLCOMP_DATASETS_HOME'] except __HOLE__: raise ValueError("MLCOMP_DATASETS_HOME env variable is undefined") mlcomp_root = os.path.expanduser(mlcomp_root) mlcomp_root = os.path.abspath(mlcomp_root) mlcomp_root = os.path.normpath(mlcomp_root) if not os.path.exists(mlcomp_root): raise ValueError("Could not find folder: " + mlcomp_root) # dataset lookup if isinstance(name_or_id, numbers.Integral): # id lookup dataset_path = os.path.join(mlcomp_root, str(name_or_id)) else: # assume name based lookup dataset_path = None expected_name_line = "name: " + name_or_id for dataset in os.listdir(mlcomp_root): metadata_file = os.path.join(mlcomp_root, dataset, 'metadata') if not os.path.exists(metadata_file): continue with open(metadata_file) as f: for line in f: if line.strip() == expected_name_line: dataset_path = os.path.join(mlcomp_root, dataset) break if dataset_path is None: raise ValueError("Could not find dataset with metadata line: " + expected_name_line) # loading the dataset metadata metadata = dict() metadata_file = os.path.join(dataset_path, 'metadata') if not os.path.exists(metadata_file): raise ValueError(dataset_path + ' is not a valid MLComp dataset') with open(metadata_file) as f: for line in f: if ":" in line: key, value = line.split(":", 1) metadata[key.strip()] = value.strip() format = metadata.get('format', 'unknow') loader = LOADERS.get(format) if loader is None: raise ValueError("No loader implemented for format: " + format) return loader(dataset_path, metadata, set_=set_, **kwargs)
KeyError
dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/datasets/mlcomp.py/load_mlcomp
8,131
def from_db_value(self, value, *args, **kwargs): try: return KeyValueContainer(value, separator=self.separator) except __HOLE__ as e: raise ValidationError(e)
ValueError
dataset/ETHPy150Open rewardz/django_model_helpers/model_helpers.py/KeyValueField.from_db_value
8,132
def main(): if len(sys.argv) < 3: usage() sr_path = sys.argv[1] action = sys.argv[2] if action not in ('print', 'delete', 'move'): usage() if action == 'move': if len(sys.argv) < 4: print "error: must specify where to move bad VHDs" sys.exit(1) bad_vhd_path = sys.argv[3] if not os.path.exists(bad_vhd_path): os.makedirs(bad_vhd_path) bad_leaves = [] descendents = {} for fname in glob.glob(os.path.join(sr_path, "*.vhd")): (returncode, stdout, stderr) = execute( ['vhd-util', 'query', '-n', fname, '-p'], ok_exit_codes=[0, 22]) stdout = stdout.strip() if stdout.endswith('.vhd'): try: descendents[stdout].append(fname) except __HOLE__: descendents[stdout] = [fname] elif 'query failed' in stdout: bad_leaves.append(fname) def walk_vhds(root): yield root if root in descendents: for child in descendents[root]: for vhd in walk_vhds(child): yield vhd for bad_leaf in bad_leaves: for bad_vhd in walk_vhds(bad_leaf): print bad_vhd if action == "print": pass elif action == "delete": os.unlink(bad_vhd) elif action == "move": new_path = os.path.join(bad_vhd_path, os.path.basename(bad_vhd)) os.rename(bad_vhd, new_path) else: raise Exception("invalid action %s" % action)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/tools/xenserver/vdi_chain_cleanup.py/main
8,133
def __new__(mcs, name, bases, attributes): try: constructor = attributes["__new__"] except KeyError: return type.__new__(mcs, name, bases, attributes) def preparing_constructor(mcs, name, bases, attributes): try: mcs.__prepare__ except __HOLE__: return constructor(mcs, name, bases, attributes) namespace = mcs.__prepare__(name, bases) defining_frame = sys._getframe(1) for constant in reversed(defining_frame.f_code.co_consts): if inspect.iscode(constant) and constant.co_name == name: def get_index(attribute_name, _names=constant.co_names): # pylint: disable=cell-var-from-loop try: return _names.index(attribute_name) except ValueError: return 0 break else: return constructor(mcs, name, bases, attributes) by_appearance = sorted( attributes.items(), key=lambda item: get_index(item[0]) ) for key, value in by_appearance: namespace[key] = value return constructor(mcs, name, bases, namespace) attributes["__new__"] = functools.wraps(constructor)(preparing_constructor) return type.__new__(mcs, name, bases, attributes)
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/utils/schema.py/Prepareable.__new__
8,134
def __new__(mcs, name, bases, attrs): # Register the class as an item class attrs['__item__'] = True attrs['__item_name__'] = None # Instantiate an empty list to store the config item attribute names attributes = [] for base in reversed(bases): try: base_attributes = getattr(base, '_attributes', []) if base_attributes: attributes.extend(base_attributes) # Extend the attributes with the base argspec argument names # but skip "self" for argname in inspect.getargspec(base.__init__).args: if argname == 'self' or argname in attributes: continue if argname == 'name': continue attributes.append(argname) except __HOLE__: # On the base object type, __init__ is just a wrapper which # triggers a TypeError when we're trying to find out it's # argspec continue attrs['_attributes'] = attributes return type.__new__(mcs, name, bases, attrs)
TypeError
dataset/ETHPy150Open saltstack/salt/salt/utils/schema.py/BaseSchemaItemMeta.__new__
8,135
def main(args): """Runs the client, exits when done. See _CreateParser for the complete list of supported commands. Requires a $LAB_DEVICE_PROXY_URL environment variable (or --url argument) that's set to the server's URL. Args: args: List of command and arguments, e.g. ['./adb', 'install', 'foo.apk'] In the expected environment, symlinks or copies of this Python file are created for every command: adb, idevice_id, ideviceinfo, ... so arg[0] is the command name. If arg[0] contains "lab_device_proxy_client", it is skipped, along with optional "--url URL" arguments. This helps support unit tests and callers who don't want to create symlinks and/or set the "$LAB_DEVICE_PROXY_URL" environment variable. E.g.: ['lab_device_proxy_client.py', '--url', 'http://x:8084', 'ideviceinfo'] is equivalent to: os.environ['LAB_DEVICE_PROXY_URL'] = 'http://x:80804' ['ideviceinfo']. """ signal.signal(signal.SIGINT, signal.SIG_DFL) # Exit on Ctrl-C args = list(args) url = os.environ.get('LAB_DEVICE_PROXY_URL') if 'lab_device_proxy_client' in args[0]: args.pop(0) # happens when there are no symlinks. if len(args) > 1 and args[0] == '--url': args.pop(0) url = args.pop(0) if args: args[0] = os.path.basename(args[0]) if not url: sys.exit( 'The lab device proxy server URL is not set.\n\n' 'Either set the environment variable, e.g.:\n' ' export LAB_DEVICE_PROXY_URL=http://mylab:8084\n' 'or invoke the proxy with a "--url" argument, e.g.:\n' ' lab_device_proxy_client.py --url http://mylab:8084 %s ...' % (args[0] if args else '')) try: params = PARSER.parse_args(args) except __HOLE__: sys.exit(1) # Make stdout and stderr unbuffered, so we could get the output # immediately when we redirect the output to another stream. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0) # TODO(user) support os.environ.get('ANDROID_SERIAL')? exit_code = 1 try: client = LabDeviceProxyClient(url, sys.stdout, sys.stderr) exit_code = client.Call(*params) except: # pylint: disable=bare-except sys.stderr.write(GetStack()) sys.exit(exit_code)
ValueError
dataset/ETHPy150Open google/lab_device_proxy/lab_device_proxy_client.py/main
8,136
def get_package_info(package_name, pkginfo, pkgchk): try: return package_info[package_name] except __HOLE__: version = None pathname = None try: sadm_contents = open('/var/sadm/install/contents', 'r').read() except EnvironmentError: pass else: sadm_re = re.compile('^(\S*/bin/CC)(=\S*)? %s$' % package_name, re.M) sadm_match = sadm_re.search(sadm_contents) if sadm_match: pathname = os.path.dirname(sadm_match.group(1)) try: p = subprocess.Popen([pkginfo, '-l', package_name], stdout=subprocess.PIPE, stderr=open('/dev/null', 'w')) except EnvironmentError: pass else: pkginfo_contents = p.communicate()[0] version_re = re.compile('^ *VERSION:\s*(.*)$', re.M) version_match = version_re.search(pkginfo_contents) if version_match: version = version_match.group(1) if pathname is None: try: p = subprocess.Popen([pkgchk, '-l', package_name], stdout=subprocess.PIPE, stderr=open('/dev/null', 'w')) except EnvironmentError: pass else: pkgchk_contents = p.communicate()[0] pathname_re = re.compile(r'^Pathname:\s*(.*/bin/CC)$', re.M) pathname_match = pathname_re.search(pkgchk_contents) if pathname_match: pathname = os.path.dirname(pathname_match.group(1)) package_info[package_name] = (pathname, version) return package_info[package_name] # use the package installer tool lslpp to figure out where cppc and what # version of it is installed
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/sunc++.py/get_package_info
8,137
def add_video_from_post(form): try: name = form.get('name', '').strip() url = form.get('url', '').strip() duration = form.get('duration', '').strip() if len(name) < 1 or len(url) < 10 or len(duration) < 1 or \ int(duration) <= 0: raise ValueError('Input validation failed') v = Video(name, url, duration) with video_lock: video_list.append(v) except __HOLE__: abort(400)
ValueError
dataset/ETHPy150Open cn28h/mobilecloud-14-flask/week2/video/app.py/add_video_from_post
8,138
def runserver(self): """ Command to run for development environments. """ print(textwrap.dedent(""" {2} Welcome to Decanter! You're ready to go! Server running on http://{1}:{0} {2}""".format(self.port, self.hostname, '=' * 50))) try: self.run() except __HOLE__: # Don't show traceback when sending ^C during runserver print('\nGood-bye!')
KeyboardInterrupt
dataset/ETHPy150Open gengo/decanter/decanter/decanter.py/Decanter.runserver
8,139
def status(self): try: with open(self.pidfile, 'r') as fp: pid = int(fp.read()) os.kill(pid, 0) print("Decanter is running, pidfile: {0}, process: {1}".format( self.pidfile, pid)) except (__HOLE__, IOError): print("Decanter is not running")
OSError
dataset/ETHPy150Open gengo/decanter/decanter/decanter.py/Decanter.status
8,140
def user_ready(username): if username.endswith(".php"): return False uh = UserHistory(username) # First, check to see if the file is fresh uh.load_if_possible() if uh.data_age() < settings.HISTORY_TTL: return uh.num_weeks() # Then, do a quick weeklist fetch to compare try: weeks = list(fetcher.weeks(username)) except __HOLE__: # They probably don't exist return None present = True for start, end in weeks: if not uh.has_week(start): present = False break # If all weeks were present, update the timestamp if present: uh.set_timestamp() uh.save_default() return len(weeks) else: return False
AssertionError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_ready
8,141
def ajax_user_queuepos(request, username): "Returns what number the user is in the request queue." try: return jsonify(list(LastFmUser.queue()).index(LastFmUser.by_username(username)) + 1) except (ValueError, __HOLE__): return jsonify(None) ### Graphs ###
IndexError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/ajax_user_queuepos
8,142
@referrer_limit @cache_page(60 * 15) def graph_artist(request, username, artist, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width=800 if not height: width=300 uh = UserHistory(username) uh.load_if_possible() series_set = SeriesSet() series_set.add_series(Series( artist, uh.artist_plays(artist), "#369f", {0:4}, )) # Create the output output = FileOutput(padding=0, style=artist_detail_white_css) try: scale = AutoWeekDateScale(series_set, short_labels=True, month_gap=2) except __HOLE__: raise Http404("Bad data (ValueError)") # OK, render that. wg = WaveGraph(series_set, scale, artist_detail_white_css, False, vertical_scale=True) output.add_item(wg, x=0, y=0, width=width, height=height) # Save the images return stream_graph(output)
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_artist
8,143
@referrer_limit @cache_page(60 * 15) def graph_timeline(request, username, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width = 800 if not height: height = 300 series_set = graph_timeline_data(username) # Create the output output = FileOutput(padding=0, style=artist_detail_white_css) try: scale = AutoWeekDateScale(series_set, short_labels=True, month_gap=2) except ValueError: raise Http404("No data") # OK, render that. wg = WaveGraph(series_set, scale, artist_detail_white_css, False, vertical_scale=True) output.add_item(wg, x=0, y=0, width=width, height=height) # Save the images try: return stream_graph(output) except __HOLE__: raise Http404("No data")
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_timeline
8,144
@referrer_limit @cache_page(60 * 15) def graph_timeline_basic(request, username, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width = 1280 if not height: height = 50 series_set = graph_timeline_data(username) series_set.get_series(0).color = "3695" # Create the output output = FileOutput(padding=0, style=basic_timeline_css) try: scale = AutoWeekDateScale(series_set, short_labels=True) except ValueError: raise Http404("No data") # OK, render that. wg = WaveGraph(series_set, scale, basic_timeline_css, False, vertical_scale=False) output.add_item(wg, x=0, y=0, width=width, height=height) # Save the images try: return stream_graph(output) except __HOLE__: raise Http404("No data")
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_timeline_basic
8,145
@referrer_limit @cache_page(60 * 15) def graph_sig1(request, username, width=300, height=100): ready_or_update(username) width = int(width) height = int(height) if not width: width = 300 if not height: height = 100 series_set = graph_timeline_data(username) series_set.get_series(0).color = "3695" # Create the output output = FileOutput(padding=0, style=sig1_css) try: scale = AutoWeekDateScale(series_set, short_labels=True) except __HOLE__: raise Http404("No data") # OK, render that. lb = Label(username, sig1_css) output.add_item(lb, x=10, y=20-(height/2), width=width, height=height) wg = WaveGraph(series_set, scale, sig1_css, False, vertical_scale=False) output.add_item(wg, x=0, y=0, width=width, height=height) # Save the images try: return stream_graph(output) except ValueError: raise Http404("No data")
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_sig1
8,146
def user_artists(request, username): uh = UserHistory(username) uh.load_if_possible() artists = [(sum(weeks.values()), artist) for artist, weeks in uh.artists.items()] artists.sort() artists.reverse() try: max_plays = float(artists[0][0]) except __HOLE__: max_plays = 1000 artists = [(plays, artist, 100*plays/max_plays) for plays, artist in artists] return render(request, "user_artists.html", {"username": username, "artists": artists})
IndexError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_artists
8,147
def user_export_all_tabular(request, username, filetype): uh = UserHistory(username) uh.load_if_possible() data = [(("Week", {"bold":True}),("Artist", {"bold":True}),("Plays", {"bold":True}))] for week, artists in uh.weeks.items(): for artist, plays in artists.items(): data.append((week, artist, plays)) try: return as_filetype(data, filetype, filename="%s_all" % username) except __HOLE__: raise Http404("No such filetype")
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_all_tabular
8,148
def user_export_artist_tabular(request, username, artist, filetype): uh = UserHistory(username) uh.load_if_possible() data = [(("Week", {"bold":True}),("Plays", {"bold":True}))] try: for week, plays in uh.artists[artist].items(): data.append((week, plays)) except KeyError: raise Http404("No such artist.") try: return as_filetype(data, filetype, filename="%s_%s" % (username, artist)) except __HOLE__: raise Http404("No such filetype")
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_artist_tabular
8,149
def user_export_artist_json(request, username, artist): uh = UserHistory(username) uh.load_if_possible() try: return jsonify({"username": username, "artist":artist, "weeks":uh.artists[artist]}) except __HOLE__: raise Http404("No such artist.")
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_artist_json
8,150
def symb_forward(self, symb_input): # If no `wrt` is passed, we use the referenced module's graph and go # through it backwards, using all its parameters etc. if self.wrt is None: try: start = self.modules[0]._last_symb_inp[self._mode] end = self.modules[0]._last_symb_out[self._mode] except KeyError: raise ValueError("The module contained by `Backward` needs to occur first in the graph!") # But if `wrt` is passed, we call `symb_forward` of the referenced # module with the input that `wrt` had gotten, in order to create a # new graph through which we then go backwards. else: try: start = self.wrt._last_symb_inp[self._mode] except __HOLE__: raise ValueError("The module referenced by `Backward`'s `wrt` argument needs to occur first in the graph!") end = self.modules[0](start) end = df.utils.flatten(end) inp = df.utils.flatten(symb_input) # Match all "backward outputs" with inputs here. assert len(end) == len(inp), "Need same number of inputs to `Backward` as contained module has outputs ({})".format(len(end)) known_grads = dict(zip(end, inp)) # Go backwards for each "backward input" which then becomes output here. if isinstance(start, (list, tuple)): return [df.th.grad(None, wrt=s, known_grads=known_grads) for s in start] else: return df.th.grad(None, wrt=start, known_grads=known_grads)
KeyError
dataset/ETHPy150Open lucasb-eyer/DeepFried2/DeepFried2/containers/Backward.py/Backward.symb_forward
8,151
def __call__(self, parser, namespace, value, option_string=None): try: if self.settings.check_for_updates: common.check_for_updates(self.settings.package_name, self.api.check_versions()['cctrl']) except __HOLE__: pass except ConnectionException: pass apps = AppsController(self.api) common.execute_with_authenticated_user(self.api, lambda: apps.list(), self.settings) parser.exit()
KeyError
dataset/ETHPy150Open cloudControl/cctrl/cctrl/app_commands.py/list_action.__call__
8,152
def setup_cli(settings): api = common.init_api(settings) try: app = AppController(api, settings) parse_cmdline(app, settings) except __HOLE__: pass finally: common.shutdown(api, settings)
KeyboardInterrupt
dataset/ETHPy150Open cloudControl/cctrl/cctrl/app_commands.py/setup_cli
8,153
def run_only_if_psutil_is_available(func): try: import psutil except __HOLE__: psutil = None return run_only(func, lambda: psutil is not None)
ImportError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/processresources/test/testprocessresources.py/run_only_if_psutil_is_available
8,154
def test_message_from_kwargs(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(message='test', data={}) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'test')
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_message_from_kwargs
8,155
def test_explicit_message_on_exception_event(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(data={'message': 'foobar'}) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'foobar')
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_explicit_message_on_exception_event
8,156
def test_exception_event(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException() self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'ValueError: foo') self.assertTrue('exception' in event) exc = event['exception']['values'][0] self.assertEquals(exc['type'], 'ValueError') self.assertEquals(exc['value'], 'foo') self.assertEquals(exc['module'], ValueError.__module__) # this differs in some Python versions assert 'stacktrace' not in event stacktrace = exc['stacktrace'] self.assertEquals(len(stacktrace['frames']), 1) frame = stacktrace['frames'][0] self.assertEquals(frame['abs_path'], __file__.replace('.pyc', '.py')) self.assertEquals(frame['filename'], 'tests/base/tests.py') self.assertEquals(frame['module'], __name__) self.assertEquals(frame['function'], 'test_exception_event') self.assertTrue('timestamp' in event)
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_exception_event
8,157
def test_exception_event_true_exc_info(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(exc_info=True) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'ValueError: foo') self.assertTrue('exception' in event) exc = event['exception']['values'][0] stacktrace = exc['stacktrace'] self.assertEquals(len(stacktrace['frames']), 1) frame = stacktrace['frames'][0] self.assertEquals(frame['abs_path'], __file__.replace('.pyc', '.py')) self.assertEquals(frame['filename'], 'tests/base/tests.py') self.assertEquals(frame['module'], __name__)
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_exception_event_true_exc_info
8,158
def test_context(self): self.client.context.merge({ 'tags': {'foo': 'bar'}, }) try: raise ValueError('foo') except __HOLE__: self.client.captureException() else: self.fail('Exception should have been raised') assert len(self.client.events) == 1 event = self.client.events.pop(0) assert event['tags'] == {'foo': 'bar'}
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_context
8,159
def new_opensslconf(self): """ Create new openssl.conf configuration file. """ directory = os.path.dirname(self.configfile) for section in self.__class__.DEFAULT.keys(): self.config.add_section(section) print "[{}]".format(section) for option in self.__class__.DEFAULT[section]: if option == "0.organizationName": value = self.domain elif option == "dir": value = directory elif section == 'req_distinguished_name' and option == 'commonName': value = self.commonName else: value = self.__class__.DEFAULT[section][option] self.config.set(section, option, value) print "\t{}={}".format(option, value) try: os.makedirs(directory, 0700) except __HOLE__, e: print e with open(self.configfile, 'wb') as configfd: self.config.write(configfd) configfd.close() confsort.reorder(self.configfile)
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/Config.new_opensslconf
8,160
def parse_opensslconf(self): """ Parse the openssl.conf file to find relevant paths. """ self.config.read(self.configfile) configuration = {} for section in self.__class__.DEFAULT.keys(): for option in self.__class__.DEFAULT[section].keys(): raw = self.config.get(section, option) value = raw.split("#")[0].strip() # Remove comments if "$" in value: # Manage openssl variables variable = "".join(value.split("$")[1:]) variable = variable.split("/")[0] path = "/" + "/".join(value.split("/")[1:]) varvalue = self.config.get(section, variable) value = varvalue.split("#")[0].strip() + path try: configuration[section].update({option: value}) except __HOLE__: configuration[section] = {} # New section configuration[section].update({option: value}) return configuration
KeyError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/Config.parse_opensslconf
8,161
def fingerprint(filename): """ Return the sha256 fingerprint of a certificate `filename`. Can only be run on trusted/signed certificates. Equivalent to: openssl x509 -sha256 -in ./runtime.csr -noout -fingerprint """ log = subprocess.Popen(["openssl", "x509", "-sha256", "-in", filename, "-noout", "-fingerprint"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = log.communicate() if log.returncode != 0: raise IOError(stderr) try: fingerprint = stdout.split("=")[1].strip() except (__HOLE__, AttributeError): errormsg = "Error fingerprinting " \ "certificate file. {}".format(stderr) raise IOError(errormsg) return fingerprint
IndexError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/fingerprint
8,162
def new_runtime(conf, name, nodeid=None): """ Create new runtime certificate. Return name of certificate signing request file. Equivalent of: mkdir -p $new_certs_dir openssl req -config $OPENSSL_CONF -new \ -newkey rsa:2048 -nodes \ -out $new_certs_dir/runtime.csr \ -keyout $private_dir/runtime.key """ outpath = conf.configuration["CA_default"]["new_certs_dir"] name_dir = os.path.join(conf.configuration["CA_default"]["runtimes_dir"], name) private_key = os.path.join(name_dir, "private", "private.key") private = os.path.dirname(private_key) out = os.path.join(outpath, "{}.csr".format(name)) os.umask(0077) try: os.makedirs(outpath, 0755) except OSError: pass try: os.makedirs(private, 0700) except __HOLE__: pass organization = conf.domain commonname = name dnQualifier = "any" if nodeid is None else nodeid subject = "/O={}/CN={}/dnQualifier={}".format(organization, commonname, dnQualifier) # Creates ECC-based certificate log = subprocess.Popen(["openssl", "ecparam", "-genkey", "-name", "prime256v1", "-out", private_key], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = log.communicate() if log.returncode != 0: raise IOError(stderr) log = subprocess.Popen(["openssl", "req", "-new", "-subj", subject, "-key", private_key, "-nodes", "-utf8", "-out", out], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = log.communicate() if log.returncode != 0: raise IOError(stderr) return out # Creates RSA-based certificate # log = subprocess.Popen(["openssl", "req", "-new", # "-subj", subject, # "-newkey", "rsa:2048", # "-nodes", # "-utf8", # "-out", out, # "-keyout", private_key], # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # stdout, stderr = log.communicate() # if log.returncode != 0: # raise IOError(stderr) # return out
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/new_runtime
8,163
def new_domain(conf): """ Create new domain Certificate Authority Cert. Return path and filename of new domain certificate. Equivalent of: echo "Creating a certificate authority for a new domain." mkdir -p -m 700 $private_dir mkdir -p -m 700 $crl_dir chmod 700 $private_dir #Because mkdir -p -m is not recursive echo 1000 > $dir/serial touch $dir/index.txt openssl rand -out $private_dir/ca_password 20 openssl req -new -x509 -config $OPENSSL_CONF \ -keyout $private_key -out $certificate \ -passout file:$private_dir/ca_password """ outpath = conf.configuration["CA_default"]["new_certs_dir"] private = conf.configuration["CA_default"]["private_dir"] crlpath = conf.configuration["CA_default"]["crl_dir"] private_key = conf.configuration["CA_default"]["private_key"] out = conf.configuration["CA_default"]["certificate"] password_file = os.path.join(private, "ca_password") os.umask(0077) try: os.mkdir(crlpath, 0700) except OSError: pass try: os.mkdir(outpath, 0700) except OSError: pass try: os.mkdir(private, 0700) except __HOLE__: pass touch(conf.configuration["CA_default"]["database"]) serialfd = open(conf.configuration["CA_default"]["serial"], 'w') serialfd.write("1000") serialfd.close() organization = conf.domain commonname = conf.domain subject = "/O={}/CN={}".format(organization, commonname) log = subprocess.Popen(["openssl", "rand", "-out", password_file, "20"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = log.communicate() if log.returncode != 0: raise IOError(stderr) log = subprocess.Popen(["openssl", "req", "-new", "-config", conf.configfile, "-x509", "-utf8", "-subj", subject, "-passout", "file:{}".format(password_file), "-out", out, "-keyout", private_key], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = log.communicate() if log.returncode != 0: raise IOError(stderr) return out
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/new_domain
8,164
def sign_req(conf, req, name): """ Sign a certificate request. Conf is a Config object with a loaded openssl.conf configuration. Req is the name of a Certificate Signing Request in $new_certs_dir. Equivalent of: mkdir -p $certs openssl ca -in $new_certs_dir/$SIGN_REQ -config $OPENSSL_CONF -out $certs/runtime.pem -passin file:$private_dir/ca_password """ private = conf.configuration["CA_default"]["private_dir"] requestpath = conf.configuration["CA_default"]["new_certs_dir"] certspath = conf.configuration["CA_default"]["certs"] name_dir = os.path.join(conf.configuration["CA_default"]["runtimes_dir"], name) password_file = os.path.join(private, "ca_password") signed = os.path.join(certspath, "signed.pem") request = os.path.join(requestpath, req) os.umask(0077) try: os.mkdir(private, 0700) except __HOLE__: pass try: os.mkdir(certspath, 0700) except OSError: pass fname_lock = "{}.lock".format(conf.configuration["CA_default"]["serial"]) fdlock = None try: # Take primitive lock while True: try: fdlock = os.open(fname_lock, os.O_CREAT|os.O_EXCL|os.O_RDWR) except OSError: # Try again time.sleep(random.random()*0.2) continue break serial = incr(conf.configuration["CA_default"]["serial"]) log = subprocess.Popen(["openssl", "ca", "-in", request, "-utf8", "-config", conf.configfile, "-out", signed, "-passin", "file:" + password_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) log.stdin.write("y\r\n") stdout, stderr = log.communicate("y\r\n") if log.returncode != 0: raise IOError(stderr) fp = fingerprint(signed) newcert = "{}.pem".format(fp.replace(":", "")[-40:]) except: pass finally: # Release primitive lock if fdlock: try: os.close(fdlock) os.remove(fname_lock) except: pass try: os.makedirs(os.path.join(name_dir, "mine")) except OSError: pass try: os.makedirs(os.path.join(name_dir, "others")) except OSError: pass newkeyname = os.path.join(name_dir, "mine", newcert) print(signed) print(newkeyname) os.rename(signed, newkeyname) return newkeyname ########################################################### # Linking a runtime name on a host to a persistent node-id # This linkage is included in CSR and signed by CA ###########################################################
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/sign_req
8,165
def _request(self, command, json=True, opcode_name='command', fetch_list=False, **kwargs): kwargs.update({ 'apiKey': self.key, opcode_name: command, }) if json: kwargs['response'] = 'json' if 'page' in kwargs or fetch_list: kwargs.setdefault('pagesize', 500) kwarg = 'params' if self.method == 'get' else 'data' done = False final_data = [] page = 1 while not done: if fetch_list: kwargs['page'] = page kwargs = transform(kwargs) kwargs.pop('signature', None) kwargs['signature'] = self._sign(kwargs) response = getattr(requests, self.method)(self.endpoint, timeout=self.timeout, **{kwarg: kwargs}) try: data = response.json() except __HOLE__ as e: msg = "Make sure endpoint URL '%s' is correct." % self.endpoint raise CloudStackException( "HTTP {0} response from CloudStack".format( response.status_code), response, "%s. " % str(e) + msg ) [key] = data.keys() data = data[key] if response.status_code != 200: raise CloudStackException( "HTTP {0} response from CloudStack".format( response.status_code), response, data) if fetch_list: try: [key] = [k for k in data.keys() if k != 'count'] except ValueError: done = True else: final_data.extend(data[key]) page += 1 else: final_data = data done = True return final_data
ValueError
dataset/ETHPy150Open exoscale/cs/cs.py/CloudStack._request
8,166
def read_config(ini_group=None): if not ini_group: ini_group = os.environ.get('CLOUDSTACK_REGION', 'cloudstack') # Try env vars first os.environ.setdefault('CLOUDSTACK_METHOD', 'get') os.environ.setdefault('CLOUDSTACK_TIMEOUT', '10') keys = ['endpoint', 'key', 'secret', 'method', 'timeout'] env_conf = {} for key in keys: if 'CLOUDSTACK_{0}'.format(key.upper()) not in os.environ: break else: env_conf[key] = os.environ['CLOUDSTACK_{0}'.format(key.upper())] else: return env_conf # Config file: $PWD/cloudstack.ini or $HOME/.cloudstack.ini # Last read wins in configparser paths = ( os.path.join(os.path.expanduser('~'), '.cloudstack.ini'), os.path.join(os.getcwd(), 'cloudstack.ini'), ) # Look at CLOUDSTACK_CONFIG first if present if 'CLOUDSTACK_CONFIG' in os.environ: paths += (os.path.expanduser(os.environ['CLOUDSTACK_CONFIG']),) if not any([os.path.exists(c) for c in paths]): raise SystemExit("Config file not found. Tried {0}".format( ", ".join(paths))) conf = ConfigParser() conf.read(paths) try: return conf[ini_group] except __HOLE__: # python 2 return dict(conf.items(ini_group))
AttributeError
dataset/ETHPy150Open exoscale/cs/cs.py/read_config
8,167
def main(): parser = argparse.ArgumentParser(description='Cloustack client.') parser.add_argument('--region', metavar='REGION', help='Cloudstack region in ~/.cloudstack.ini', default=os.environ.get('CLOUDSTACK_REGION', 'cloudstack')) parser.add_argument('--post', action='store_true', default=False, help='use POST instead of GET') parser.add_argument('--async', action='store_true', default=False, help='do not wait for async result') parser.add_argument('command', metavar="COMMAND", help='Cloudstack API command to execute') def parse_option(x): if '=' not in x: raise ValueError("{!r} is not a correctly formatted " "option".format(x)) return x.split('=', 1) parser.add_argument('arguments', metavar="OPTION=VALUE", nargs='*', type=parse_option, help='Cloudstack API argument') options = parser.parse_args() command = options.command kwargs = defaultdict(set) for arg in options.arguments: key, value = arg kwargs[key].add(value.strip(" \"'")) try: config = read_config(ini_group=options.region) except NoSectionError: raise SystemExit("Error: region '%s' not in config" % options.region) if options.post: config['method'] = 'post' cs = CloudStack(**config) try: response = getattr(cs, command)(**kwargs) except CloudStackException as e: response = e.args[2] sys.stderr.write("Cloudstack error:\n") if 'Async' not in command and 'jobid' in response and not options.async: sys.stderr.write("Polling result... ^C to abort\n") while True: try: res = cs.queryAsyncJobResult(**response) if res['jobstatus'] != 0: response = res break time.sleep(3) except __HOLE__: sys.stderr.write("Result not ready yet.\n") break data = json.dumps(response, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): data = pygments.highlight(data, JsonLexer(), TerminalFormatter()) sys.stdout.write(data)
KeyboardInterrupt
dataset/ETHPy150Open exoscale/cs/cs.py/main
8,168
def test_noniterable(self): val = self.arr while True: try: val = val[0] except __HOLE__: break method = self.model.objects.create self.assertRaises(ValidationError, method, arr=val)
TypeError
dataset/ETHPy150Open ecometrica/django-dbarray/dbarray/tests/tests.py/ArrayTestMixin.test_noniterable
8,169
def flush(self): """Flushes the stream.""" try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, __HOLE__): pass else: stream.flush()
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/_cplogging.py/WSGIErrorHandler.flush
8,170
def emit(self, record): """Emit a record.""" try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (__HOLE__, KeyError): pass else: try: msg = self.format(record) fs = "%s\n" import types if not hasattr(types, "UnicodeType"): #if no unicode support... stream.write(fs % msg) else: try: stream.write(fs % msg) except UnicodeError: stream.write(fs % msg.encode("UTF-8")) self.flush() except: self.handleError(record)
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/_cplogging.py/WSGIErrorHandler.emit
8,171
def memoize(func): saved = {} def call(*args): try: return saved[args] except KeyError: res = func(*args) saved[args] = res return res except __HOLE__: # Unhashable argument return func(*args) call.__name__ = func.__name__ return call # -----------------------------------------------
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_decorators.py/memoize
8,172
def run(self, result): try: raise RuntimeError("error that occurs outside of a test") except __HOLE__: log.err(failure.Failure())
RuntimeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/test/test_runner.py/BreakingSuite.run
8,173
def testPythonSetupD(self): try: __import__('setuptools') except __HOLE__: raise testhelp.SkipTestException('Missing python-setuptools package') recipestr = r""" class Test(PackageRecipe): name = 'test' version = '0' clearBuildReqs() def setup(r): r.Create('blah/setupfoo.py', contents='\n'.join(( '#import disttools', 'file("%(destdir)s/disttools", "w").close()', ''))) r.PythonSetup(setupName='setupfoo.py', dir='blah', action='whatever', rootDir='') """ # missing buildreq, but test that it runs anyway trv = self.build(recipestr, "Test") self.verifyPackageFileList(trv, ['/disttools'])
ImportError
dataset/ETHPy150Open sassoftware/conary/conary_test/cvctest/buildtest/buildtest.py/PythonSetupTest.testPythonSetupD
8,174
def testPythonSetupNonPure(self): try: __import__('setuptools') except __HOLE__: raise testhelp.SkipTestException('Missing python-setuptools package') recipestr = r""" class Test(PackageRecipe): name = 'test' version = '0' clearBuildReqs() def setup(r): r.macros.lib = 'lib64' # test pre-existing python-specific multilib breakage r.Create('%(prefix)s/lib/python2.4/site-packages/a') r.Create('%(prefix)s/lib64/python2.4/site-packages/b') # test multilib breakage that purePython=False could help r.Create('setup.py', contents='\n'.join(( '#import setuptools', 'file("%(destdir)s%(prefix)s/lib/python2.4/site-packages/foo", "w").close()', 'file("%(destdir)s%(prefix)s/lib64/python2.4/site-packages/bar", "w").close()', ''))) r.PythonSetup() """ # missing buildreq, but test that it runs anyway self.logFilter.add() self.assertRaises(policy.PolicyError, self.buildRecipe, recipestr, "Test") self.logFilter.remove() assert(os.path.exists(util.joinPaths(self.buildDir, 'test/_ROOT_/usr/lib/python2.4/site-packages/foo'))) assert(os.path.exists(util.joinPaths(self.buildDir, 'test/_ROOT_/usr/lib64/python2.4/site-packages/bar'))) self.logFilter.regexpCompare([ r'error: Python and object files detected in different directories before PythonSetup\(\) instance on line 18', r'error: Python and object files detected in different directories on line 18; call all instances of PythonSetup\(\) with the purePython=False argument', 'error: NonMultilibComponent: .*', ])
ImportError
dataset/ETHPy150Open sassoftware/conary/conary_test/cvctest/buildtest/buildtest.py/TestMakeFIFO.testPythonSetupNonPure
8,175
def _str_datetime_now(self, x=None): """Return datetime string for use with time attributes Handling depends on input: 'now' - returns datetime for now number - assume datetime values, generate string other - no change, return same value """ if (x == 'now'): # Now, this is wht datetime_to_str() with no arg gives return( datetime_to_str() ) try: # Test for number junk = x + 0.0 return datetime_to_str(x) except __HOLE__: # Didn't look like a number, treat as string return x
TypeError
dataset/ETHPy150Open resync/resync/resync/resource_container.py/ResourceContainer._str_datetime_now
8,176
def status(self): status = { # summary = 'notfound', 'sleeping', 'on', or 'recording' 'summary': 'notfound', 'raw': {} } camActive = True # loop through different status URLs for cmd in self.statusMatrix: # stop sending requests if a previous request failed if camActive: url = self._statusURL(cmd) # attempt to contact the camera try: response = urlopen( url, timeout=self.timeout).read().encode('hex') status['raw'][cmd] = response # save raw response # loop through different parts we know how to translate for item in self.statusMatrix[cmd]: args = self.statusMatrix[cmd][item] if 'a' in args and 'b' in args: part = response[args['a']:args['b']] else: part = response # translate the response value if we know how if 'translate' in args: status[item] = self._translate( args['translate'], part) else: status[item] = part except (__HOLE__, URLError, socket.timeout) as e: logging.warning('{}{} - error opening {}: {}{}'.format( Fore.YELLOW, 'GoProHero.status()', url, e, Fore.RESET)) camActive = False # build summary if 'record' in status and status['record'] == 'on': status['summary'] = 'recording' elif 'power' in status and status['power'] == 'on': status['summary'] = 'on' elif 'power' in status and status['power'] == 'sleeping': status['summary'] = 'sleeping' logging.info('GoProHero.status() - result {}'.format(status)) return status
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.status
8,177
def image(self): try: # use OpenCV to capture a frame and store it in a numpy array stream = cv2.VideoCapture(self._previewURL()) success, numpyImage = stream.read() if success: # use Image to save the image to a file, but actually save it # to a string image = Image.fromarray(numpyImage) output = StringIO.StringIO() image.save(output, format='PNG') str = output.getvalue() output.close() logging.info('GoProHero.image() - success!') return 'data:image/png;base64,'+base64.b64encode(str) except NameError: logging.warning('{}{} - OpenCV not installed{}'.format( Fore.YELLOW, 'GoProHero.image()', Fore.RESET)) except __HOLE__ as e: logging.warning('{}{} - Pillow prereqs not installed: {}{}'.format( Fore.YELLOW, 'GoProHero.image()', e, Fore.RESET)) # catchall return statement return False
IOError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.image
8,178
def command(self, command, value=None): func_str = 'GoProHero.command({}, {})'.format(command, value) if command in self.commandMaxtrix: args = self.commandMaxtrix[command] # accept both None and '' for commands without a value if value == '': value = None # for commands with values, translate the value if value is not None and value in args['translate']: value = args['translate'][value] # build the final url url = self._commandURL(args['cmd'], value) # attempt to contact the camera try: urlopen(url, timeout=self.timeout).read() logging.info('{} - http success!'.format(func_str)) return True except (__HOLE__, URLError, socket.timeout) as e: logging.warning('{}{} - error opening {}: {}{}'.format( Fore.YELLOW, func_str, url, e, Fore.RESET)) # catchall return statement return False
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.command
8,179
def test(self, url, toHex=True): try: url = 'http://{}/{}'.format(self._ip, url) print(url) response = urlopen( url, timeout=self.timeout).read() if toHex: response = response.encode('hex') print(response) except (__HOLE__, URLError, socket.timeout) as e: print(e)
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.test
8,180
def __init__(self, connection): QTabWidget.__init__(self) self.connection = connection self.setupUi(self) self.tableProcessList.verticalHeader().hide() cur = self.connection.cursor() cur.execute("SHOW TABLES IN information_schema LIKE 'PROCESSLIST'") self.processListInInfoSchema = cur.rowcount if self.processListInInfoSchema: self.processListColumns = [] cur.execute("SHOW COLUMNS IN information_schema.PROCESSLIST") for column in cur.fetchall(): self.processListColumns.append(column[0]) try: self.processListColumns.remove("TIME_MS") idx_time = self.processListColumns.index("TIME") self.processListColumns[idx_time] = "TIME + TIME_MS/1000 AS TIME" except __HOLE__: pass else: self.chkShowIdle.hide() self.refresh() self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.on_spinSeconds_valueChanged(self.spinSeconds.value()) self.on_chkAutoRefresh_stateChanged()
ValueError
dataset/ETHPy150Open mtorromeo/sqlantaresia/sqlantaresia/ProcessListTab.py/ProcessListTab.__init__
8,181
@conserve_mpmath_dps def test_lambdify(): mpmath.mp.dps = 16 sin02 = mpmath.mpf("0.198669330795061215459412627") f = lambdify(x, sin(x), "numpy") prec = 1e-15 assert -prec < f(0.2) - sin02 < prec try: f(x) # if this succeeds, it can't be a numpy function assert False except __HOLE__: pass
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/external/tests/test_numpy.py/test_lambdify
8,182
@extensionclassmethod(Observable, alias=["from_", "from_list"]) def from_iterable(cls, iterable, scheduler=None): """Converts an array to an observable sequence, using an optional scheduler to enumerate the array. 1 - res = rx.Observable.from_iterable([1,2,3]) 2 - res = rx.Observable.from_iterable([1,2,3], rx.Scheduler.timeout) Keyword arguments: :param Observable cls: Observable class :param Scheduler scheduler: [Optional] Scheduler to run the enumeration of the input sequence on. :returns: The observable sequence whose elements are pulled from the given enumerable sequence. :rtype: Observable """ scheduler = scheduler or current_thread_scheduler lock = Lock() def subscribe(observer): iterator = iter(iterable) def action(action1, state=None): try: with lock: item = next(iterator) except __HOLE__: observer.on_completed() else: observer.on_next(item) action1(action) return scheduler.schedule_recursive(action) return AnonymousObservable(subscribe)
StopIteration
dataset/ETHPy150Open ReactiveX/RxPY/rx/linq/observable/fromiterable.py/from_iterable
8,183
def as_tuple(x, N, t=None): """ Coerce a value to a tuple of given length (and possibly given type). Parameters ---------- x : value or iterable N : integer length of the desired tuple t : type, optional required type for all elements Returns ------- tuple ``tuple(x)`` if `x` is iterable, ``(x,) * N`` otherwise. Raises ------ TypeError if `type` is given and `x` or any of its elements do not match it ValueError if `x` is iterable, but does not have exactly `N` elements """ try: X = tuple(x) except __HOLE__: X = (x,) * N if (t is not None) and not all(isinstance(v, t) for v in X): raise TypeError("expected a single value or an iterable " "of {0}, got {1} instead".format(t.__name__, x)) if len(X) != N: raise ValueError("expected a single value or an iterable " "with length {0}, got {1} instead".format(N, x)) return X
TypeError
dataset/ETHPy150Open Lasagne/Lasagne/lasagne/utils.py/as_tuple
8,184
def onDeleteBtn(self, event): """ :param event: :return: """ self.checkIfEditing() try: if self.selectedObject: if len(self.selectedObject) > 1: length = len(self.selectedObject) msg = GMD.GenericMessageDialog(None, 'Are you sure you want to delete %d items' % length, 'Clear items?', wx.YES_NO | wx.ICON_WARNING | wx.NO_DEFAULT) value = msg.ShowModal() if value == wx.ID_YES: self.customRemove(self.selectedObject) else: self.customRemove(self.selectedObject) except __HOLE__ as e: msg = GMD.GenericMessageDialog(None, 'Are you sure you want to delete your work?', 'Clear items?', wx.YES_NO | wx.ICON_WARNING | wx.NO_DEFAULT) value = msg.ShowModal() if value == wx.ID_YES: self.customRemove(self.selectedObject) #self.sb.SetStatusText("Removing %s" % self.sb.SetStatusText("Removing %s" % self.selectedObject.dataValue)) self.selectedObject = None event.Skip()
TypeError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/controller/frmAddPoints.py/AddPoints.onDeleteBtn
8,185
def onSelected(self, event): """ :param event: :return: """ obj = event.GetEventObject() object = obj.innerList[obj.FocusedItem] object = self.olv.GetSelectedObjects() try: if len(object) > 1: self.selectedObject = object else: self.selectedObject = object[0] except __HOLE__ as e: pass except IndexError as e: pass event.Skip()
TypeError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/controller/frmAddPoints.py/AddPoints.onSelected
8,186
def get_view(endpoint): """Returns the view for the endpoint. It will cache both positive and negative hits, so never pass untrusted values to it. If a view does not exist, `None` is returned. """ view = _resolved_views.get(endpoint) if view is not None: return view try: view = import_string('solace.views.' + endpoint) except (ImportError, __HOLE__): view = import_string(endpoint, silent=True) _resolved_views[endpoint] = view return view
AttributeError
dataset/ETHPy150Open mitsuhiko/solace/solace/application.py/get_view
8,187
def inject_lang_code(request, endpoint, values): """Returns a dict with the values for the given endpoint. You must not alter the dict because it might be shared. If the given endpoint does not exist `None` is returned. """ rv = values if 'lang_code' not in rv: try: if request.url_adapter.map.is_endpoint_expecting( endpoint, 'lang_code'): rv = values.copy() rv['lang_code'] = request.view_lang or str(request.locale) except __HOLE__: return return rv
KeyError
dataset/ETHPy150Open mitsuhiko/solace/solace/application.py/inject_lang_code
8,188
def _set_lang(self, gettext): lang = request.GET['lang'] try: set_lang(lang) except (LanguageError, __HOLE__), e: resp_unicode = gettext('Could not set language to "%(lang)s"') % {'lang': lang} else: session['lang'] = lang session.save() resp_unicode = gettext('Set language to "%(lang)s"') % {'lang': lang} return resp_unicode
IOError
dataset/ETHPy150Open Pylons/pylons/tests/test_webapps/filestotest/controller_sample.py/SampleController._set_lang
8,189
def emit(self, record): """Emit a record. This implementation is based on the implementation of StreamHandler.emit(). Args: record: A Python logging.LogRecord object. """ try: if features.IsEnabled("LogServiceWriteRecord"): logservice.write_record(self._AppLogsLevel(record.levelno), record.created, self.format(record), self._AppLogsLocation()) else: message = self._AppLogsMessage(record) if isinstance(message, unicode): message = message.encode("UTF-8") logservice.write(message) except (KeyboardInterrupt, __HOLE__, runtime.DeadlineExceededError): raise except: self.handleError(record)
SystemExit
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/app_logging.py/AppLogsHandler.emit
8,190
def test_change_attr(self): class Foo(object): def __init__(self): self.foo = 1 obj = Foo() self.assertEqual(obj.foo, 1) with self.changeAttr(obj, 'foo', 2): self.assertEqual(obj.foo, 2) self.assertEqual(obj.foo, 1) # Check that the attribute is restored when an exception happens. try: with self.changeAttr(obj, 'foo', 2): raise ValueError() except __HOLE__: pass self.assertEqual(obj.foo, 1)
ValueError
dataset/ETHPy150Open cjerdonek/open-rcv/openrcv/test/utiltest/test_helpers.py/UnitCaseTest.test_change_attr
8,191
def __cmp__(self,other): # only works for equal result = -1 try: result = cmp(self.name,other.name) or \ cmp(self.__class__, other.__class__) except __HOLE__: pass return result #---------------------------------------------------------------------------- # Module Converter #----------------------------------------------------------------------------
AttributeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/c_spec.py/common_base_converter.__cmp__
8,192
def _run_command_compare_to_string(self, command, exit_status, stdout_text=None, stderr_text=None): """ Compares stdout from the CLI to the given string """ try: main.parse_and_validate_commands(command) except __HOLE__ as e: self.assertEqual(e.code, exit_status) if stdout_text is not None: actual = self.test_stdout.getvalue() self.assertEqual(stdout_text, actual, self._format_expected_actual(stdout_text, actual)) if stderr_text is not None: actual = self.test_stderr.getvalue() self.assertEqual(stderr_text, self.test_stderr.getvalue(), self._format_expected_actual(stderr_text, actual))
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/BaseMainCase._run_command_compare_to_string
8,193
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) def test_hosts_on_cli_overrides_topology(self, unused_mock_load): try: main.main(['--hosts', 'master,slave1', 'topology', 'show']) except __HOLE__ as e: self.assertEqual(e.code, 0) self.assertDefaultRoledefs() self.assertEqual(main.state.env.hosts, ['master', 'slave1']) self.assertEqual(main.api.env.hosts, ['master', 'slave1'])
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_hosts_on_cli_overrides_topology
8,194
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) @patch('prestoadmin.main.getpass.getpass') def test_initial_password(self, pass_mock, unused_mock_load): try: main.parse_and_validate_commands(['-I', 'topology', 'show']) except __HOLE__ as e: self.assertEqual(0, e.code) pass_mock.assert_called_once_with('Initial value for env.password: ')
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_initial_password
8,195
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) def test_env_vars_persisted(self, unused_mock_load): try: main.main(['topology', 'show']) except __HOLE__ as e: self.assertEqual(e.code, 0) self.assertDefaultHosts()
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_env_vars_persisted
8,196
@patch('prestoadmin.main.load_config', side_effect=mock_empty_topology()) def test_topology_defaults_override_fabric_defaults( self, unused_mock_load): self.remove_runs_once_flag(topology.show) try: main.main(['topology', 'show']) except __HOLE__ as e: self.assertEqual(e.code, 0) self.assertEqual(['localhost'], main.state.env.hosts) self.assertEqual({'coordinator': ['localhost'], 'worker': ['localhost'], 'all': ['localhost']}, main.state.env.roledefs) self.assertEqual(22, main.state.env.port) self.assertEqual('root', main.state.env.user)
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_topology_defaults_override_fabric_defaults
8,197
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_has_args_expecting_none(self, crawl_mock, crawl_mock_main): def task(): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task state.env.nodeps = False try: main.run_tasks([('my task', ['arg1'], {}, [], [], [])]) except __HOLE__ as e: self.assertEqual(e.code, 2) self.assertEqual('Incorrect number of arguments to task.\n\n' 'Displaying detailed information for task ' '\'my task\':\n\n This is my task\n\n', self.test_stdout.getvalue())
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_has_args_expecting_none
8,198
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_too_few_args(self, crawl_mock, crawl_mock_main): def task(arg1): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task state.env.nodeps = False try: main.run_tasks([('my task', [], {}, [], [], [])]) except __HOLE__ as e: self.assertEqual(e.code, 2) self.assertEqual('Incorrect number of arguments to task.\n\n' 'Displaying detailed information for task ' '\'my task\':\n\n This is my task\n\n', self.test_stdout.getvalue())
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_few_args
8,199
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_too_many_args(self, crawl_mock, crawl_mock_main): def task(arg1): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task state.env.nodeps = False try: main.run_tasks([('my task', ['arg1', 'arg2'], {}, [], [], [])]) except __HOLE__ as e: self.assertEqual(e.code, 2) self.assertEqual('Incorrect number of arguments to task.\n\n' 'Displaying detailed information for task ' '\'my task\':\n\n This is my task\n\n', self.test_stdout.getvalue())
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_many_args