Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,500
def update_note(self, note): """ function to update a specific note object, if the note object does not have a "key" field, a new note is created Arguments - note (dict): note object to update Returns: A tuple `(note, status)` - note (dict): note ob...
IOError
dataset/ETHPy150Open cpbotha/nvpy/nvpy/simplenote.py/Simplenote.update_note
7,501
def get_note_list(self, qty=float("inf")): """ function to get the note list The function can be passed an optional argument to limit the size of the list returned. If omitted a list of all notes is returned. Arguments: - quantity (integer number): of notes to list ...
IOError
dataset/ETHPy150Open cpbotha/nvpy/nvpy/simplenote.py/Simplenote.get_note_list
7,502
def delete_note(self, note_id): """ method to permanently delete a note Arguments: - note_id (string): key of the note to trash Returns: A tuple `(note, status)` - note (dict): an empty dict or an error message - status (int): 0 on sucesss and -...
IOError
dataset/ETHPy150Open cpbotha/nvpy/nvpy/simplenote.py/Simplenote.delete_note
7,503
def verilog_to_pymtl( model, verilog_file, c_wrapper_file, lib_file, py_wrapper_file, vcd_en, lint, verilator_xinit ): model_name = model.class_name try: vlinetrace = model.vlinetrace except __HOLE__: vlinetrace = False # Verilate the model # TODO: clean this up verilate_mode...
AttributeError
dataset/ETHPy150Open cornell-brg/pymtl/pymtl/tools/translation/verilator_cffi.py/verilog_to_pymtl
7,504
def create_shared_lib( model_name, c_wrapper_file, lib_file, vcd_en, vlinetrace ): # We need to find out where the verilator include directories are # globally installed. We first check the PYMTL_VERILATOR_INCLUDE_DIR # environment variable, and if that does not exist then we fall back on ...
OSError
dataset/ETHPy150Open cornell-brg/pymtl/pymtl/tools/translation/verilator_cffi.py/create_shared_lib
7,505
def __eq__(self, cmd): """ Compare two command instances to each other by matching their key and aliases. Args: cmd (Command or str): Allows for equating both Command objects and their keys. Returns: equal (bool): If the commands are equa...
AttributeError
dataset/ETHPy150Open evennia/evennia/evennia/commands/command.py/Command.__eq__
7,506
def __ne__(self, cmd): """ The logical negation of __eq__. Since this is one of the most called methods in Evennia (along with __eq__) we do some code-duplication here rather than issuing a method-lookup to __eq__. """ try: return self._matchset.isdisj...
AttributeError
dataset/ETHPy150Open evennia/evennia/evennia/commands/command.py/Command.__ne__
7,507
def run(self): """ Run the command, infer time period to be used in metric analysis phase. :return: None """ cmd_args = shlex.split(self.run_cmd) logger.info('Local command RUN-STEP starting with rank %d', self.run_rank) logger.info('Running subprocess command with following args: ' + str(cm...
KeyboardInterrupt
dataset/ETHPy150Open linkedin/naarad/src/naarad/run_steps/local_cmd.py/Local_Cmd.run
7,508
def kill(self): """ If run_step needs to be killed, this method will be called :return: None """ try: logger.info('Trying to terminating run_step...') self.process.terminate() time_waited_seconds = 0 while self.process.poll() is None and time_waited_seconds < CONSTANTS.SECOND...
OSError
dataset/ETHPy150Open linkedin/naarad/src/naarad/run_steps/local_cmd.py/Local_Cmd.kill
7,509
def main(): parser = argparse.ArgumentParser() parser.add_argument('-k', '--key', default='name') parser.add_argument('-s', '--case-sensitive', default=False, action='store_true') parser.add_argument('-r', '--reverse', default=False, action='store_true') args = parser.parse_args() if sys.stdin....
ValueError
dataset/ETHPy150Open bittorrent/btc/btc/btc_sort.py/main
7,510
def main(): (opts, args) = getopts() if chkopts(opts) is True: return PROCERROR cf = readconf(opts.config) if cf is None: print >>sys.stderr, 'Failed to load the config file "%s". (%s)' % (opts.config, sys.argv[0]) return PROCERROR # conf parse if parse_conf(cf) is ...
KeyboardInterrupt
dataset/ETHPy150Open karesansui/pysilhouette/pysilhouette/asynperformer.py/main
7,511
def is_eager(self, backend_name): """Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A backend configures its eagerness by setting the backend configuration value ``router.celery.eager`` to True or False. The default...
KeyError
dataset/ETHPy150Open rapidsms/rapidsms/rapidsms/router/celery/router.py/CeleryRouter.is_eager
7,512
def default_interface(): """ Get default gateway interface. Some OSes return 127.0.0.1 when using socket.gethostbyname(socket.gethostname()), so we're attempting to get a kind of valid hostname here. """ try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except __HOLE...
KeyError
dataset/ETHPy150Open nils-werner/zget/zget/utils.py/default_interface
7,513
def ip_addr(interface): """ Get IP address from interface. """ try: return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] except __HOLE__: raise ValueError(_("You have selected an invalid interface"))
KeyError
dataset/ETHPy150Open nils-werner/zget/zget/utils.py/ip_addr
7,514
def unique_filename(filename, limit=maxsize): if not os.path.exists(filename): return filename path, name = os.path.split(filename) name, ext = os.path.splitext(name) def make_filename(i): return os.path.join(path, '%s_%d%s' % (name, i, ext)) for i in xrange(1, limit): uni...
NameError
dataset/ETHPy150Open nils-werner/zget/zget/utils.py/unique_filename
7,515
def urlretrieve( url, output=None, reporthook=None ): r = requests.get(url, stream=True) try: maxsize = int(r.headers['content-length']) except __HOLE__: maxsize = -1 if output is None: try: filename = re.findall( "filename=(\S+)", r.heade...
KeyError
dataset/ETHPy150Open nils-werner/zget/zget/utils.py/urlretrieve
7,516
def main(): try: locale.setlocale(locale.LC_ALL, '') py3 = Py3statusWrapper() py3.setup() except __HOLE__: py3.notify_user('Setup interrupted (KeyboardInterrupt).') sys.exit(0) except Exception: py3.report_exception('Setup error') sys.exit(2) try:...
KeyboardInterrupt
dataset/ETHPy150Open ultrabug/py3status/py3status/__init__.py/main
7,517
def snapshots_to_iterations(apps, schema_editor): Iteration = apps.get_model('orchestra', 'Iteration') Task = apps.get_model('orchestra', 'Task') TaskAssignment = apps.get_model('orchestra', 'TaskAssignment') for task in Task.objects.all(): task_snapshots = get_ordered_snapshots(task) f...
AssertionError
dataset/ETHPy150Open unlimitedlabs/orchestra/orchestra/migrations/0028_snapshots_to_iterations.py/snapshots_to_iterations
7,518
def _get_hadoop_bin(self, env): try: return env['HADOOP_BIN'] except __HOLE__: return os.path.join(get_run_root('ext/hadoop/hadoop'), 'bin', 'hadoop')
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/pseudo_hdfs4.py/PseudoHdfs4._get_hadoop_bin
7,519
def _get_mapred_bin(self, env): try: return env['MAPRED_BIN'] except __HOLE__: return os.path.join(get_run_root('ext/hadoop/hadoop'), 'bin', 'mapred')
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/pseudo_hdfs4.py/PseudoHdfs4._get_mapred_bin
7,520
def _get_yarn_bin(self, env): try: return env['YARN_BIN'] except __HOLE__: return os.path.join(get_run_root('ext/hadoop/hadoop'), 'bin', 'yarn')
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/pseudo_hdfs4.py/PseudoHdfs4._get_yarn_bin
7,521
def _get_hdfs_bin(self, env): try: return env['HDFS_BIN'] except __HOLE__: return os.path.join(get_run_root('ext/hadoop/hadoop'), 'bin', 'hdfs')
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/pseudo_hdfs4.py/PseudoHdfs4._get_hdfs_bin
7,522
def execute_command(command, working_dir=None): startupinfo = None # hide console window on windows if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW output = None try: output = subprocess.check_output( ...
AttributeError
dataset/ETHPy150Open Zeeker/sublime-GitConflictResolver/modules/util.py/execute_command
7,523
def read_one(self, num): pin_num = int(num) try: pin_config = self.pins[pin_num] return self.pin_response(pin_num, pin_config) except __HOLE__: return None
KeyError
dataset/ETHPy150Open projectweekend/Pi-GPIO-Server/pi_gpio/config/pins.py/PinManager.read_one
7,524
def update_value(self, num, value): pin_num = int(num) try: self.pins[pin_num] self.gpio.output(pin_num, value) return True except __HOLE__: return None
KeyError
dataset/ETHPy150Open projectweekend/Pi-GPIO-Server/pi_gpio/config/pins.py/PinManager.update_value
7,525
def decode(self, data): """ Decoder implementation of the Bencode algorithm @param data: The encoded data @type data: str @note: This is a convenience wrapper for the recursive decoding algorithm, C{_decodeRecursive} @return: The decoded ...
ValueError
dataset/ETHPy150Open lbryio/lbry/lbrynet/dht/encoding.py/Bencode.decode
7,526
@staticmethod def _decodeRecursive(data, startIndex=0): """ Actual implementation of the recursive Bencode algorithm Do not call this; use C{decode()} instead """ if data[startIndex] == 'i': endPos = data[startIndex:].find('e')+startIndex return (int(...
ValueError
dataset/ETHPy150Open lbryio/lbry/lbrynet/dht/encoding.py/Bencode._decodeRecursive
7,527
def __parse_version_from_changelog(): try: deb_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'debian', 'changelog') with open(deb_path, 'r') as changelog: regmatch = re.match(r'python-tortik \((.*)\).*', changelog.readline()) return regmatch...
AttributeError
dataset/ETHPy150Open glibin/tortik/tortik/version.py/__parse_version_from_changelog
7,528
def map_blocks(func, *args, **kwargs): """ Map a function across all blocks of a dask array Parameters ---------- func: callable Function to apply to every block in the array args: dask arrays or constants dtype: np.dtype Datatype of resulting array chunks: tuple (optional) ...
AttributeError
dataset/ETHPy150Open dask/dask/dask/array/core.py/map_blocks
7,529
def cache(self, store=None, **kwargs): """ Evaluate and cache array Parameters ---------- store: MutableMapping or ndarray-like Place to put computed and cached chunks kwargs: Keyword arguments to pass on to ``get`` function for scheduling Exampl...
ImportError
dataset/ETHPy150Open dask/dask/dask/array/core.py/Array.cache
7,530
def unpack_singleton(x): """ >>> unpack_singleton([[[[1]]]]) 1 >>> unpack_singleton(np.array(np.datetime64('2000-01-01'))) array(datetime.date(2000, 1, 1), dtype='datetime64[D]') """ while isinstance(x, (list, tuple)): try: x = x[0] except (__HOLE__, TypeError, K...
IndexError
dataset/ETHPy150Open dask/dask/dask/array/core.py/unpack_singleton
7,531
def elemwise(op, *args, **kwargs): """ Apply elementwise function across arguments Respects broadcasting rules Examples -------- >>> elemwise(add, x, y) # doctest: +SKIP >>> elemwise(sin, x) # doctest: +SKIP See Also -------- atop """ if not set(['name', 'dtype']).issupe...
AttributeError
dataset/ETHPy150Open dask/dask/dask/array/core.py/elemwise
7,532
def chunks_from_arrays(arrays): """ Chunks tuple from nested list of arrays >>> x = np.array([1, 2]) >>> chunks_from_arrays([x, x]) ((2, 2),) >>> x = np.array([[1, 2]]) >>> chunks_from_arrays([[x], [x]]) ((1, 1), (2,)) >>> x = np.array([[1, 2]]) >>> chunks_from_arrays([[x, x]]) ...
AttributeError
dataset/ETHPy150Open dask/dask/dask/array/core.py/chunks_from_arrays
7,533
def concatenate3(arrays): """ Recursive np.concatenate Input should be a nested list of numpy arrays arranged in the order they should appear in the array itself. Each array should have the same number of dimensions as the desired output and the nesting of the lists. >>> x = np.array([[1, 2]]) ...
AttributeError
dataset/ETHPy150Open dask/dask/dask/array/core.py/concatenate3
7,534
def splitquote(line, stopchar=None, lower=False, quotechars = '"\''): """ Fast LineSplitter. Copied from The F2Py Project. """ items = [] i = 0 while 1: try: char = line[i]; i += 1 except __HOLE__: break l = [] l_append = l.append ...
IndexError
dataset/ETHPy150Open pearu/pylibtiff/libtiff/utils.py/splitquote
7,535
def referer(pattern, accept=True, accept_missing=False, error=403, message='Forbidden Referer header.', debug=False): """Raise HTTPError if Referer header does/does not match the given pattern. pattern A regular expression pattern to test against the Referer. accept ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/cptools.py/referer
7,536
def __bind(self, name, invkind): """Bind (name, invkind) and return a FuncDesc instance or None. Results (even unsuccessful ones) are cached.""" # We could cache the info in the class instead of the # instance, but we would need an additional key for that: # self._iid tr...
KeyError
dataset/ETHPy150Open enthought/comtypes/comtypes/client/lazybind.py/Dispatch.__bind
7,537
def __getattr__(self, name): """Get a COM attribute.""" if name.startswith("__") and name.endswith("__"): raise AttributeError(name) # check for propget or method descr = self.__bind(name, DISPATCH_METHOD | DISPATCH_PROPERTYGET) if descr is None: raise Att...
TypeError
dataset/ETHPy150Open enthought/comtypes/comtypes/client/lazybind.py/Dispatch.__getattr__
7,538
def get_cached_mtimes(self, root_folder, use_files_relpaths, get_all=False): location = os.path.join(root_folder, ".git", "harpoon_cached_mtimes.json") sorted_use_files_relpaths = sorted(use_files_relpaths) result = [] if os.path.exists(location): try: result ...
TypeError
dataset/ETHPy150Open realestate-com-au/harpoon/harpoon/ship/context.py/ContextBuilder.get_cached_mtimes
7,539
def set_cached_mtimes(self, root_folder, first_commit, mtimes, use_files_relpaths): location = os.path.join(root_folder, ".git", "harpoon_cached_mtimes.json") sorted_use_files_relpaths = sorted(use_files_relpaths) current = self.get_cached_mtimes(root_folder, use_files_relpaths, get_all=True) ...
IOError
dataset/ETHPy150Open realestate-com-au/harpoon/harpoon/ship/context.py/ContextBuilder.set_cached_mtimes
7,540
def findstring(self, string): """Returns the Enum object given a name string.""" d = self.get_mapping() try: return d[string] except __HOLE__: raise ValueError("Enum string not found.") # common enumerations
KeyError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/Enums.findstring
7,541
def sgn(val): """Sign function. Returns -1 if val negative, 0 if zero, and 1 if positive. """ try: return val._sgn_() except __HOLE__: if val == 0: return 0 if val > 0: return 1 else: return -1 # Nice floating point range function ...
AttributeError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/sgn
7,542
def __getattr__(self, name): try: return self.__dict__["_attribs"][name] except __HOLE__: raise AttributeError("Invalid attribute %r" % (name,))
KeyError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/mapstr.__getattr__
7,543
def __getattr__(self, name): try: return self.__dict__["_attribs"][name] except __HOLE__: raise AttributeError("Invalid attribute %r" % (name,))
KeyError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/formatstr.__getattr__
7,544
def removedups(s): """Return a list of the elements in s, but without duplicates. Thanks to Tim Peters for fast method. """ n = len(s) if n == 0: return [] u = {} try: for x in s: u[x] = 1 except TypeError: del u # move on to the next method else:...
TypeError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/removedups
7,545
def Import(modname): """Improved __import__ function that returns fully initialized subpackages.""" try: return sys.modules[modname] except __HOLE__: pass __import__(modname) return sys.modules[modname]
KeyError
dataset/ETHPy150Open kdart/pycopia/aid/pycopia/aid.py/Import
7,546
def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname), 'r').read() except __HOLE__: return u''
IOError
dataset/ETHPy150Open arteria/django-hijack/setup.py/read
7,547
def repeat_until_consistent(self, f, *args, **kwargs): """ Repeatedly call a function with given arguments until AssertionErrors stop or configured number of repetitions are reached. Some backends are eventually consistent, which means results of listing volumes may not reflect ...
AssertionError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/testtools/_blockdevice.py/IBlockDeviceAPITestsMixin.repeat_until_consistent
7,548
def umount_all(root_path): """ Unmount all devices with mount points contained in ``root_path``. :param FilePath root_path: A directory in which to search for mount points. """ def is_under_root(path): try: FilePath(path).segmentsFrom(root_path) except __HOLE__: ...
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/testtools/_blockdevice.py/umount_all
7,549
def __init__(self, params): timeout = params.get('timeout', 300) try: timeout = int(timeout) except (__HOLE__, TypeError): timeout = 300 self.default_timeout = timeout
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/cache/backends/base.py/BaseCache.__init__
7,550
def main_loop(bots, config): if "LOGFILE" in config: logging.basicConfig(filename=config[ "LOGFILE"], level=logging.INFO, format='%(asctime)s %(message)s') try: for bot in bots: bot.init() while True: for bot in bots: # ...
KeyboardInterrupt
dataset/ETHPy150Open youknowone/slairck/slairck.py/main_loop
7,551
def main(): try: import clime except __HOLE__: clime = None if clime: clime.start({'calendar': git_calendar}) else: raise Exception("I need clime.")
ImportError
dataset/ETHPy150Open littleq0903/git-calendar/git_calendar/main.py/main
7,552
def __init__(self, name, value=None, schema=None): self.name = name self.value = value self.schema = schema self._status = self.PROPERTY_STATUS_DEFAULT self._required = self.PROPERTY_REQUIRED_DEFAULT # Validate required 'type' property exists try: sel...
KeyError
dataset/ETHPy150Open openstack/tosca-parser/toscaparser/elements/property_definition.py/PropertyDef.__init__
7,553
def validate_boards(ctx, param, value): # pylint: disable=W0613 unknown_boards = set(value) - set(get_boards().keys()) try: assert not unknown_boards return value except __HOLE__: raise click.BadParameter( "%s. Please search for the board types using " "`plat...
AssertionError
dataset/ETHPy150Open platformio/platformio/platformio/commands/init.py/validate_boards
7,554
def begin_site(self): in_production = self.site.config.mode.startswith('prod') if not in_production: self.logger.info('Generating draft posts as the site is' 'not in production mode.') return for resource in self.site.content.walk_resources(...
AttributeError
dataset/ETHPy150Open hyde/hyde/hyde/ext/plugins/blog.py/DraftsPlugin.begin_site
7,555
def get_actions_urls(model, url_name=None, **kwargs): """ Get automatically the actions urls for a model. """ from ionyweb.administration.actions.views import (ActionAdminListView, ActionAdminDetailView, ...
KeyError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/administration/actions/utils.py/get_actions_urls
7,556
def get_actions_for_object_model(obj, relation_id=None): # -- DEPRECATED -- # Only for backward compatibilty if hasattr(obj, 'get_actions'): # All app and plugin define a get_actions method, # so we check if the method is overloaded... get_actions = getattr(obj, 'get_actions') ...
AttributeError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/administration/actions/utils.py/get_actions_for_object_model
7,557
def __str__(self): try: return self.plugin_class.get_identifier(self) except __HOLE__: return str(self.image)
AttributeError
dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/mixins.py/ImagePropertyMixin.__str__
7,558
@property def image(self): if not hasattr(self, '_image_model'): try: Model = apps.get_model(*self.glossary['image']['model'].split('.')) self._image_model = Model.objects.get(pk=self.glossary['image']['pk']) except (__HOLE__, ObjectDoesNotExist): ...
KeyError
dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/mixins.py/ImagePropertyMixin.image
7,559
def __init__(self, swift_proxy=None, swift_proxy_storage_path=None, swift_proxy_cdn_path=None, attempts=5, eventlet=None, chunk_size=65536, verbose=None, verbose_id='', direct_object_ring=None): super(DirectClient, self).__init__() self.storage_path = s...
ImportError
dataset/ETHPy150Open gholt/swiftly/swiftly/client/directclient.py/DirectClient.__init__
7,560
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if query: path += '?' + '&'.join( ('%s=%s' % (quote(k), quote(v)) if v else ...
StopIteration
dataset/ETHPy150Open gholt/swiftly/swiftly/client/directclient.py/DirectClient.request
7,561
def _import(module, reload="False"): """ Creates a global translation dictionary for module. The argument module has to be one of the following strings: "math", "mpmath", "numpy", "sympy". These dictionaries map names of python functions to their equivalent in other modules. """ from sy...
KeyError
dataset/ETHPy150Open sympy/sympy/sympy/utilities/lambdify.py/_import
7,562
@doctest_depends_on(modules=('numpy')) def lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=True): """ Returns a lambda function for fast calculation of numerical values. If not specified differently by the user, SymPy functions are replaced as far as possible by eit...
ImportError
dataset/ETHPy150Open sympy/sympy/sympy/utilities/lambdify.py/lambdify
7,563
def separate_users(node, user_ids): """Separates users into ones with permissions and ones without given a list. :param node: Node to separate based on permissions :param user_ids: List of ids, will also take and return User instances :return: list of subbed, list of removed user ids """ remove...
TypeError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/notifications/utils.py/separate_users
7,564
def test_careduce(): """ test sum pattern 1, 11, 10, 01, 001, 010, 100, 110, 011, 111, 0011, 0101, 0111, 1011, 1111 test sum pattern implemented with reshape: 1000, 0100, 0010, 0001, 11111 others implemented by reshape that are not tested 0011,0101,0110,1001,1010,1100 1110,1101,1011 ...
NotImplementedError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/cuda/tests/test_basic_ops.py/test_careduce
7,565
def test_reshape(): a = tcn.CudaNdarrayType((False,))() b = tcn.CudaNdarrayType((False, False))() c = T.reshape(a, [2, 3]) # basic f = theano.function([a], c, mode=mode_with_gpu) fv = f(cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5], ...
ValueError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/cuda/tests/test_basic_ops.py/test_reshape
7,566
def test_elemwise_bad_broadcast(): x = cuda.fmatrix('x') y = cuda.fmatrix('y') f = theano.function([x, y], x * y, mode=mode_with_gpu) assert len(f.maker.fgraph.toposort()) == 2 assert isinstance(f.maker.fgraph.toposort()[0].op, cuda.GpuElemwise) assert f.maker.fgraph.toposort()[1].op == cuda.ho...
ValueError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/cuda/tests/test_basic_ops.py/test_elemwise_bad_broadcast
7,567
def test_gpujoin_assert_cndas(): # this will end up being an ndarray, as it's float64 _a = numpy.asarray([[1, 2], [3, 4]], dtype='float64') a = theano.shared(_a) try: c = cuda.basic_ops.gpu_join(1, a) # can't "assert False" here, as we want the assertion # error from gpu_join ...
TypeError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/cuda/tests/test_basic_ops.py/test_gpujoin_assert_cndas
7,568
def get_request_choices(self, request, tbl): """ Return a list of choices for this chooser, using a HttpRequest to build the context. """ from django.contrib.contenttypes.models import ContentType kw = {} # 20120202 if tbl.master_field is not None: ...
ValueError
dataset/ETHPy150Open lsaffre/lino/lino/utils/choosers.py/Chooser.get_request_choices
7,569
def handle(self, *args, **options): """Handle the command.""" if len(args) != 1: raise CommandError("You must specify a filename on the command " "line.") filename = args[0] if not os.path.exists(filename): raise CommandError("%s d...
ImportError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/admin/management/commands/loaddb.py/Command.handle
7,570
def collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): """ Averages data in collapsecol, keeping all unique items in keepcols (using unique, which keeps unique LISTS of column numbers), retaining the unique sets of values in keepcols, the mean for each. Setting fcn1 and/or fcn2 to poi...
TypeError
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/collapse
7,571
def recode (inlist,listmap,cols=None): """ Changes the values in a list to a new set of values (useful when you need to recode data from (e.g.) strings to numbers. cols defaults to None (meaning all columns are recoded). Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list Returns:...
ValueError
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/recode
7,572
def sortby(listoflists,sortcols): """ Sorts a list of lists on the column(s) specified in the sequence sortcols. Usage: sortby(listoflists,sortcols) Returns: sorted list, unchanged column ordering """ newlist = abut(colex(listoflists,sortcols),listoflists) newlist.sort() try: numco...
TypeError
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/sortby
7,573
def acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): """ Averages data in collapsecol, keeping all unique items in keepcols (using unique, which keeps unique LISTS of column numbers), retaining the unique sets of values in keepcols, the mean for each. If stderror or N of ...
TypeError
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/acollapse
7,574
def aunique(inarray): """ Returns unique items in the FIRST dimension of the passed array. Only works on arrays NOT including string items. Usage: aunique (inarray) """ uniques = N.array([inarray[0]]) if len(uniques.shape) == 1: # IF IT'S A 1D ARRAY ...
TypeError
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/aunique
7,575
def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1, client=None, target=None): # Client is mandatory. Perhaps move it farther up if we refactor assert client is not None self.__kind=kind if filename.split("://")[0].lower() in ('htt...
IOError
dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/image.py/MyImage.__init__
7,576
@classmethod def size_for_node(self, node, client): '''Given a docutils image node, returns the size the image should have in the PDF document, and what 'kind' of size that is. That involves lots of guesswork''' uri = str(node.get("uri")) if uri.split("://")[0].lower() not i...
IOError
dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/image.py/MyImage.size_for_node
7,577
def prepare(self): ''' Run the preparation sequence required to start a salt master server. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Master, self).prepare() try: if self.config['verify_env']: ...
OSError
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Master.prepare
7,578
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: ...
OSError
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Minion.prepare
7,579
def start(self): ''' Start the actual minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Minion, self).start() try: if check_user(self.c...
KeyboardInterrupt
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Minion.start
7,580
def call(self, cleanup_protecteds): ''' Start the actual minion as a caller minion. cleanup_protecteds is list of yard host addresses that should not be cleaned up this is to fix race condition when salt-caller minion starts up If sub-classed, don't **ever** forget to run: ...
KeyboardInterrupt
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Minion.call
7,581
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(ProxyMinion, self).prepare() if not self.values.proxyid: raise SaltS...
OSError
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/ProxyMinion.prepare
7,582
def start(self): ''' Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(ProxyMinion, self).start() try: if check_...
KeyboardInterrupt
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/ProxyMinion.start
7,583
def prepare(self): ''' Run the preparation sequence required to start a salt syndic minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Syndic, self).prepare() try: if self.config['verify_env']: ...
OSError
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Syndic.prepare
7,584
def start(self): ''' Start the actual syndic. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(Syndic, self).start() if check_user(self.config['user']): ...
KeyboardInterrupt
dataset/ETHPy150Open saltstack/salt/salt/cli/daemons.py/Syndic.start
7,585
def write(self, data): """Write data to the file. There is no return value. `data` can be either a string of bytes or a file-like object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data` can also be a :class:`unicode` (:class:`str` in python 3) i...
AttributeError
dataset/ETHPy150Open blynch/CloudMemeBackend/gridfs/grid_file.py/GridIn.write
7,586
def load_and_fix_json(json_path): """Tries to load a json object from a file. If that fails, tries to fix common errors (no or extra , at end of the line). """ with open(json_path) as f: json_str = f.read() log.debug('Configuration file %s read correctly', json_path) config = None ...
ValueError
dataset/ETHPy150Open maebert/jrnl/jrnl/util.py/load_and_fix_json
7,587
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key...
KeyError
dataset/ETHPy150Open pallets/flask/flask/debughelpers.py/attach_enctype_error_multidict
7,588
def FilterAlignedPairForPositions(seq1, seq2, method): """given the method, return a set of aligned sequences only containing certain positions. Available filters: all: do nothing. codon1,codon2,codon3: return 1st, 2nd, 3rd codon positions only. d4: only changes within fourfold-degenerat...
KeyError
dataset/ETHPy150Open CGATOxford/cgat/scripts/fasta2distances.py/FilterAlignedPairForPositions
7,589
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser( version="%prog version: $Id: fasta2distances.py 2781 2009-09-10 11:33:14Z andreas $") parser.add_option("--filte...
StopIteration
dataset/ETHPy150Open CGATOxford/cgat/scripts/fasta2distances.py/main
7,590
@respond_to("image me (?P<search_query>.*)$") def image_me(self, message, search_query): """image me ___ : Search google images for ___, and post a random one.""" data = { "q": search_query, "v": "1.0", "safe": "active", "rsz": "8" } r ...
TypeError
dataset/ETHPy150Open skoczen/will/will/plugins/productivity/images.py/ImagesPlugin.image_me
7,591
def _free(self, block): # free location and try to merge with neighbours (arena, start, stop) = block try: prev_block = self._stop_to_block[(arena, start)] except KeyError: pass else: start, _ = self._absorb(prev_block) try...
KeyError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/heap.py/Heap._free
7,592
def process_request (self, request): try: request.django_root except __HOLE__: request.django_root = '' login_url = settings.LOGIN_URL + '?next=%s' % request.path if request.path.startswith(request.django_root): path = request.path[len(request.django...
AttributeError
dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/middleware/sitelockdown.py/SiteLockDown.process_request
7,593
def processMessage(self, message): """Parse a message and post it as a metric.""" if self.factory.verbose: log.listener("Message received: %s" % (message,)) metric = message.routing_key for line in message.content.body.split("\n"): line = line.strip() ...
ValueError
dataset/ETHPy150Open tmm1/graphite/carbon/lib/carbon/amqp_listener.py/AMQPGraphiteProtocol.processMessage
7,594
def process_constraints(data, constraint_fields): """ Callback to move constrained fields from incoming data into a 'constraints' key. :param data: Incoming argument dict :param constraint_fields: Constrained fields to move into 'constraints' dict """ # Always use a list so...
KeyError
dataset/ETHPy150Open dropbox/pynsot/pynsot/commands/callbacks.py/process_constraints
7,595
def _enabled_item_name(enabled_item): """Returns the toggle item name Toggles are of the form: {namespace}:{toggle_item} or {toggle_item} The latter case is used occasionally if the namespace is "USER" """ try: return enabled_item.split(":")[1] except __HOLE__: return enabled_ite...
IndexError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/toggle_ui/views.py/_enabled_item_name
7,596
def get_connection(backend=None, template_prefix=None, template_suffix=None, fail_silently=False, **kwargs): """Load a templated e-mail backend and return an instance of it. If backend is None (default) settings.TEMPLATED_EMAIL_BACKEND is used. Both fail_silently and other keyword argum...
AttributeError
dataset/ETHPy150Open BradWhittington/django-templated-email/templated_email/__init__.py/get_connection
7,597
def load_settings_layer(self, file_name): try: return json.load(open(os.path.join(self.settings_dir, file_name))) except (IOError, __HOLE__): return {}
OSError
dataset/ETHPy150Open ohmu/poni/poni/core.py/Config.load_settings_layer
7,598
def add_config(self, config, parent=None, copy_dir=None): config_dir = os.path.join(self.path, CONFIG_DIR, config) if os.path.exists(config_dir): raise errors.UserError( "%s: config %r already exists" % (self.name, config)) if copy_dir: try: ...
OSError
dataset/ETHPy150Open ohmu/poni/poni/core.py/Node.add_config
7,599
def __init__(self, system, name, system_path, sub_count, extra=None): Item.__init__(self, "system", system, name, system_path, os.path.join(system_path, SYSTEM_CONF_FILE), extra) self["sub_count"] = sub_count try: self.update(json.load(open(self.conf_file))) ...
IOError
dataset/ETHPy150Open ohmu/poni/poni/core.py/System.__init__