Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
3,100 | def _get_max_io_ops_per_host(self, host_state, spec_obj):
aggregate_vals = utils.aggregate_values_from_key(
host_state,
'max_io_ops_per_host')
try:
value = utils.validate_num_values(
aggregate_vals, CONF.max_io_ops_per_host, cast_to=int)
except... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/scheduler/filters/io_ops_filter.py/AggregateIoOpsFilter._get_max_io_ops_per_host |
3,101 | def isSameTree(self, p, q):
"""
dfs
:param p: TreeNode
:param q: TreeNode
:return: boolean
"""
# trivial
if not p and not q:
return True
# dfs
try:
if p.val==q.val and self.isSameTree(p.left, q.left) ... | AttributeError | dataset/ETHPy150Open algorhythms/LeetCode/100 Same Tree.py/Solution.isSameTree |
3,102 | def _spectral_helper(x, y, fs=1.0, window='hann', nperseg=256,
noverlap=None, nfft=None, detrend='constant',
return_onesided=True, scaling='spectrum', axis=-1,
mode='psd'):
"""
Calculate various forms of windowed FFTs for PSD, CSD, etc.
This is a ... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/signal/spectral.py/_spectral_helper |
3,103 | def test_js_file(err, filename, data, line=0, context=None):
"Tests a JS file by parsing and analyzing its tokens"
# Don't even try to run files bigger than 1MB.
if len(data) > 1024 * 1024:
err.warning(
err_id=("js", "skip", "didnt_even_try"),
warning="Didn't even try to val... | RuntimeError | dataset/ETHPy150Open mozilla/app-validator/appvalidator/testcases/scripting.py/test_js_file |
3,104 | def __call__(self, request, *args, **kwargs):
try:
obj = self.get_object(request, *args, **kwargs)
except __HOLE__:
raise Http404('Feed object does not exist.')
feedgen = self.get_feed(obj, request)
response = HttpResponse(mimetype=feedgen.mime_type)
feedg... | ObjectDoesNotExist | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/syndication/views.py/Feed.__call__ |
3,105 | def item_link(self, item):
try:
return item.get_absolute_url()
except __HOLE__:
raise ImproperlyConfigured('Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class.' % item.__class__.__name__) | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/syndication/views.py/Feed.item_link |
3,106 | def __get_dynamic_attr(self, attname, obj, default=None):
try:
attr = getattr(self, attname)
except __HOLE__:
return default
if callable(attr):
# Check func_code.co_argcount rather than try/excepting the
# function and catching the TypeError, becau... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/syndication/views.py/Feed.__get_dynamic_attr |
3,107 | def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
from django.contrib.syndication.feeds import Feed as LegacyFeed
import warnings
warnings.warn('The syndication feed() view is deprecated. Please use the '
'new class based view API.',
... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/syndication/views.py/feed |
3,108 | def get_server_name():
try:
return settings.TRANSFER_SERVER
except __HOLE__:
raise ImproperlyConfigured('Please specify settings.TRANSFER_SERVER') | AttributeError | dataset/ETHPy150Open smartfile/django-transfer/django_transfer/__init__.py/get_server_name |
3,109 | def get_header_name():
server_name = get_server_name()
try:
return SERVER_HEADERS[server_name]
except __HOLE__:
raise ImproperlyConfigured('Invalid server name "%s" for '
'settings.TRANSFER_SERVER' % server_name) | KeyError | dataset/ETHPy150Open smartfile/django-transfer/django_transfer/__init__.py/get_header_name |
3,110 | def get_header_value(path):
if get_server_name() == SERVER_NGINX:
try:
mappings = settings.TRANSFER_MAPPINGS
except __HOLE__:
raise ImproperlyConfigured('Please specify settings.TRANSFER_MAPPINGS')
found = False
for root, location in mappings.items():
... | AttributeError | dataset/ETHPy150Open smartfile/django-transfer/django_transfer/__init__.py/get_header_value |
3,111 | def process_request(self, request):
if request.method != 'POST':
return
if not is_enabled():
return
if get_server_name() != SERVER_NGINX:
return
# Find uploads in request.POST and copy them to request.FILES. Such
# fields are expected to be nam... | KeyError | dataset/ETHPy150Open smartfile/django-transfer/django_transfer/__init__.py/TransferMiddleware.process_request |
3,112 | def yearFilter(queryset, querydict):
try:
year=int(querydict['year_covered'])
queryset = queryset.filter(Q(coverage_from_date__gte=date(year,1,1), coverage_to_date__lte=date(year,12,31)))
except (__HOLE__, ValueError):
pass
return queryset | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/yearFilter |
3,113 | def DWDistrictFilter(queryset, querydict):
try:
district_list=querydict['districts']
# if there's no commas, it's just a single district
if district_list.find(',') < 0:
queryset = queryset.filter(district__pk=district_list)
# if there's a comma, it's... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/DWDistrictFilter |
3,114 | def candidatedistrictFilter(queryset, querydict):
try:
id=int(querydict['district'])
queryset = queryset.filter(district__pk=id)
except (__HOLE__, ValueError):
pass
return queryset | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/candidatedistrictFilter |
3,115 | def districtIDFilter(queryset, querydict):
try:
id=int(querydict['pk'])
queryset = queryset.filter(pk=id)
except (__HOLE__, ValueError):
pass
return queryset | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/districtIDFilter |
3,116 | def weekFilter(queryset, querydict):
try:
week=querydict['week']
# if there's no commas, it's just a single district
if week.upper() == "NOW":
queryset = queryset.filter(cycle_week_number = get_week_number(date.today()) )
if week.upper() == "LAST":
queryset =... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/weekFilter |
3,117 | def periodTypeFilter(queryset, querydict):
try:
period_type=querydict['period_type']
if period_type.startswith('Q'):
if period_type == 'Q1':
queryset = queryset.filter(coverage_from_date__month=1, coverage_from_date__day=1, coverage_to_date__month=3, coverage_to_date__day... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/periodTypeFilter |
3,118 | def reportTypeFilter(queryset, querydict):
try:
report_type=querydict['report_type']
if report_type == 'monthly':
queryset = queryset.filter(form_type__in=['F3X', 'F3XN', 'F3XA', 'F3', 'F3A', 'F3N', 'F3P', 'F3PA', 'F3PN'])
elif report_type == 'ies':
query... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/reportTypeFilter |
3,119 | def orderingFilter(queryset, querydict, fields):
"""
Only works if the ordering hasn't already been set. Which it hasn't, but...
"""
try:
ordering=querydict['ordering']
if ordering.lstrip('-') in fields:
orderlist = [ordering]
queryset = queryset.order_by(*orderl... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/orderingFilter |
3,120 | def committeeSearchSlow(queryset, querydict):
"""
Table scan--maybe some sorta dropdown in front of this?
"""
try:
search_term = querydict['search_term']
queryset = queryset.filter(committee_name__icontains=search_term)
except __HOLE__:
pass
return queryset | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/committeeSearchSlow |
3,121 | def candidateidSearch(queryset, querydict):
try:
candidate_id = querydict['candidate_id']
authorized_committee_list = Authorized_Candidate_Committees.objects.filter(candidate_id=candidate_id)
committee_list = [x.get('committee_id') for x in authorized_committee_list.values('committee_id')]
... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/candidateidSearch |
3,122 | def filingTimeFilter(queryset, querydict):
try:
time_range=querydict['time_range']
if time_range == 'day':
today = date.today()
queryset = queryset.filter(filed_date=today)
elif time_range == 'week':
today = date.today()
one_week_ago = today-ti... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/filingTimeFilter |
3,123 | def multiCommitteeTypeFilter(queryset, querydict):
try:
committee_class = querydict['committee_class']
committee_class = committee_class.upper()
if committee_class == 'J':
queryset = queryset.filter(committee_designation=committee_class)
elif committee_class == 'L':
... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/multiCommitteeTypeFilter |
3,124 | def multiCTypeFilter(queryset, querydict):
try:
committee_class = querydict['committee_class']
committee_class = committee_class.upper()
if committee_class == 'J':
queryset = queryset.filter(designation=committee_class)
elif committee_class == 'L':
# a D commm... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/multiCTypeFilter |
3,125 | def candidateCommitteeSearchSlow(queryset, querydict):
"""
Table scan--maybe some sorta dropdown in front of this?
"""
try:
search_term = querydict['search_term']
queryset = queryset.filter(Q(name__icontains=search_term)|Q(curated_candidate__name__icontains=search_term))
ex... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/api/filters.py/candidateCommitteeSearchSlow |
3,126 | @staticmethod
def from_bundle(bundle_path):
"""Collect run data from two CSV files."""
run_data = RunData(None)
# load runs
runs_csv_path = os.path.join(bundle_path, "all_runs.csv.gz")
logger.info("reading run data from %s", runs_csv_path)
solver_names = set()
... | StopIteration | dataset/ETHPy150Open borg-project/borg/borg/storage.py/RunData.from_bundle |
3,127 | def _import_svn():
global fs, repos, core, delta, _kindmap, _svn_uri_canonicalize
from svn import fs, repos, core, delta
_kindmap = {core.svn_node_dir: Node.DIRECTORY,
core.svn_node_file: Node.FILE}
try:
_svn_uri_canonicalize = core.svn_uri_canonicalize # Subversion 1.7+
exc... | AttributeError | dataset/ETHPy150Open edgewall/trac/tracopt/versioncontrol/svn/svn_fs.py/_import_svn |
3,128 | def __init__(self):
self._version = None
try:
_import_svn()
except __HOLE__ as e:
self.error = e
self.log.info('Failed to load Subversion bindings', exc_info=True)
else:
self.log.debug("Subversion bindings imported")
version = (... | ImportError | dataset/ETHPy150Open edgewall/trac/tracopt/versioncontrol/svn/svn_fs.py/SubversionConnector.__init__ |
3,129 | def normalize_rev(self, rev):
"""Take any revision specification and produce a revision suitable
for the rest of the API
"""
if rev is None or isinstance(rev, basestring) and \
rev.lower() in ('', 'head', 'latest', 'youngest'):
return self.youngest_rev
... | TypeError | dataset/ETHPy150Open edgewall/trac/tracopt/versioncontrol/svn/svn_fs.py/SubversionRepository.normalize_rev |
3,130 | def get_annotations(self):
"""Return a list the last changed revision for each line.
(wraps ``client.blame2``)
"""
annotations = []
if self.isfile:
def blame_receiver(line_no, revision, author, date, line, pool):
annotations.append(revision)
... | AttributeError | dataset/ETHPy150Open edgewall/trac/tracopt/versioncontrol/svn/svn_fs.py/SubversionNode.get_annotations |
3,131 | @classmethod
def from_json(cls, json_thing):
"""
Given a JSON object or JSON string that was created by `self.to_json`,
return the corresponding markovify.Chain.
"""
# Python3 compatibility
try:
basestring
except __HOLE__:
basestring = str
... | NameError | dataset/ETHPy150Open jsvine/markovify/markovify/chain.py/Chain.from_json |
3,132 | def __getattr__(self, name):
# Now that we've intercepted __getattr__, we can't access our own
# attributes directly. Use __getattribute__ to access them.
obj = self.__getattribute__('_wrapped')
exceptions = self.__getattribute__('_exceptions')
if (obj is None) or (name in except... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/grizzled/grizzled/proxy.py/Forwarder.__getattr__ |
3,133 | def divide_gaussians(mean_precision_num, mean_precision_den):
"""
mean_precision_num are parameters of gaussian in the numerator
mean_precision_den are parameters of gaussian in the denominator
output is a valid gaussian only if the variance of ouput is non-negative
"""
precision_op = mean_preci... | AssertionError | dataset/ETHPy150Open balajiln/mondrianforest/src/utils.py/divide_gaussians |
3,134 | def assert_no_nan(mat, name='matrix'):
try:
assert(not any(np.isnan(mat)))
except __HOLE__:
print '%s contains NaN' % name
print mat
raise AssertionError | AssertionError | dataset/ETHPy150Open balajiln/mondrianforest/src/utils.py/assert_no_nan |
3,135 | def check_if_one(val):
try:
assert(np.abs(val - 1) < 1e-9)
except __HOLE__:
print 'val = %s (needs to be equal to 1)' % val
raise AssertionError | AssertionError | dataset/ETHPy150Open balajiln/mondrianforest/src/utils.py/check_if_one |
3,136 | def check_if_zero(val):
try:
assert(np.abs(val) < 1e-9)
except __HOLE__:
print 'val = %s (needs to be equal to 0)' % val
raise AssertionError | AssertionError | dataset/ETHPy150Open balajiln/mondrianforest/src/utils.py/check_if_zero |
3,137 | def sample_multinomial(prob):
try:
k = int(np.where(np.random.multinomial(1, prob, size=1)[0]==1)[0])
except __HOLE__:
print 'problem in sample_multinomial: prob = '
print prob
raise TypeError
except:
raise Exception
return k | TypeError | dataset/ETHPy150Open balajiln/mondrianforest/src/utils.py/sample_multinomial |
3,138 | def main():
"""
Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response
"""
try:
# Open serial port
ser = serial.Serial('/dev/ttyUSB0', 9600)
# Create XBee Series 1 object
xbee = XBee(ser)
... | KeyboardInterrupt | dataset/ETHPy150Open thom-nic/python-xbee/examples/serial_example_series_1.py/main |
3,139 | def createQuestionWindow(self):
""" Create a question window (well, duh) """
try:
questionArray = self.questionBank[self.questionPointer]
questionArrayLength = len(questionArray) - 3
#### QUESTION WINDOW FONTS
defaultfont = tkFont.Font(root=self.master, ... | KeyError | dataset/ETHPy150Open christabella/pokepython/gamelib/gui.py/applicationGUI.createQuestionWindow |
3,140 | def write_error(self, status_code, **kwargs):
try:
log_message = kwargs.get('exc_info')[1].log_message
except (TypeError, AttributeError, __HOLE__):
log_message = 'unknown reason'
self.finish(log_message+'\r\n') | IndexError | dataset/ETHPy150Open EnigmaCurry/curlbomb/curlbomb/server.py/CurlbombBaseRequestHandler.write_error |
3,141 | def run_server(settings):
settings['state'] = {'num_gets': 0, 'num_posts': 0, 'num_posts_in_progress': 0}
curlbomb_args = dict(
resource=settings['resource'],
state=settings['state'],
allowed_gets=settings['num_gets'],
knock=settings['knock'],
mime_type=settings['mime_typ... | KeyboardInterrupt | dataset/ETHPy150Open EnigmaCurry/curlbomb/curlbomb/server.py/run_server |
3,142 | def _await_socket(self, timeout):
"""Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout."""
with safe_open(self._ng_stdout, 'r') as ng_stdout:
start_time = time.time()
while 1:
readable, _, _ = select.select([ng_stdout], [], [], self._SELECT_WAIT)
... | AttributeError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/java/nailgun_executor.py/NailgunExecutor._await_socket |
3,143 | def __init__(self, formats=None, content_types=None, datetime_formatting=None):
self.supported_formats = []
self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601')
if formats is not None:
self.formats = formats
if content_types is not None:
... | KeyError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/serializers.py/Serializer.__init__ |
3,144 | def get_mime_for_format(self, format):
"""
Given a format, attempts to determine the correct MIME type.
If not available on the current ``Serializer``, returns
``application/json`` by default.
"""
try:
return self.content_types[format]
except __HOLE__... | KeyError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/serializers.py/Serializer.get_mime_for_format |
3,145 | def AskUser(text, choices=None):
"""Ask the user a question.
@param text: the question to ask
@param choices: list with elements tuples (input_char, return_value,
description); if not given, it will default to: [('y', True,
'Perform the operation'), ('n', False, 'Do no do the operation')];
not... | IOError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/AskUser |
3,146 | def GenericMain(commands, override=None, aliases=None,
env_override=frozenset()):
"""Generic main function for all the gnt-* commands.
@param commands: a dictionary with a special structure, see the design doc
for command line handling.
@param override: if not None, we expect a... | IOError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/GenericMain |
3,147 | def ParseNicOption(optvalue):
"""Parses the value of the --net option(s).
"""
try:
nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
except (TypeError, __HOLE__), err:
raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
errors.ECODE_INVAL)
nics = [... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/ParseNicOption |
3,148 | def FixHvParams(hvparams):
# In Ganeti 2.8.4 the separator for the usb_devices hvparam was changed from
# comma to space because commas cannot be accepted on the command line
# (they already act as the separator between different hvparams). Still,
# RAPI should be able to accept commas for backwards compatibili... | KeyError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/FixHvParams |
3,149 | def GenericInstanceCreate(mode, opts, args):
"""Add an instance to the cluster via either creation or import.
@param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the new i... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/GenericInstanceCreate |
3,150 | def GenerateTable(headers, fields, separator, data,
numfields=None, unitfields=None,
units=None):
"""Prints a table with headers and different fields.
@type headers: dict
@param headers: dictionary mapping field names to headers for
the table
@type fields: list
@para... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/GenerateTable |
3,151 | def FormatResultError(status, verbose):
"""Formats result status other than L{constants.RS_NORMAL}.
@param status: The result status
@type verbose: boolean
@param verbose: Whether to return the verbose text
@return: Text of result status
"""
assert status != constants.RS_NORMAL, \
"FormatResult... | KeyError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/FormatResultError |
3,152 | def ParseTimespec(value):
"""Parse a time specification.
The following suffixed will be recognized:
- s: seconds
- m: minutes
- h: hours
- d: day
- w: weeks
Without any suffix, the value will be taken to be in seconds.
"""
value = str(value)
if not value:
raise errors.OpPrereqErr... | TypeError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/ParseTimespec |
3,153 | def _ToStream(stream, txt, *args):
"""Write a message to a stream, bypassing the logging system
@type stream: file object
@param stream: the file to which we should write
@type txt: str
@param txt: the message
"""
try:
if args:
args = tuple(args)
stream.write(txt % args)
else:
... | IOError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/_ToStream |
3,154 | def _InitISpecsFromSplitOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count,
ispecs_disk_count, ispecs_disk_size,
ispecs_nic_count, group_ipolicy, fill_all):
try:
if ispecs_mem_size:
ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
if ispecs_disk_s... | TypeError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/_InitISpecsFromSplitOpts |
3,155 | def _ParseSpecUnit(spec, keyname):
ret = spec.copy()
for k in [constants.ISPEC_DISK_SIZE, constants.ISPEC_MEM_SIZE]:
if k in ret:
try:
ret[k] = utils.ParseUnit(ret[k])
except (__HOLE__, ValueError, errors.UnitParseError), err:
raise errors.OpPrereqError(("Invalid parameter %s (%s) in... | TypeError | dataset/ETHPy150Open ganeti/ganeti/lib/cli.py/_ParseSpecUnit |
3,156 | def _prep_values(self, values=None, kill_inf=True, how=None):
if values is None:
values = getattr(self._selected_obj, 'values', self._selected_obj)
# GH #12373 : rolling functions error on float32 data
# make sure the data is coerced to float64
if com.is_float_dtype(values.... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/_Window._prep_values |
3,157 | def validate(self):
super(Window, self).validate()
window = self.window
if isinstance(window, (list, tuple, np.ndarray)):
pass
elif com.is_integer(window):
try:
import scipy.signal as sig
except __HOLE__:
raise ImportEr... | ImportError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/Window.validate |
3,158 | def _apply_window(self, mean=True, how=None, **kwargs):
"""
Applies a moving window of type ``window_type`` on the data.
Parameters
----------
mean : boolean, default True
If True computes weighted mean, else weighted sum
how : string, default to None (DEPREC... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/Window._apply_window |
3,159 | def _apply(self, func, name=None, window=None, center=None,
check_minp=None, how=None, **kwargs):
"""
Rolling statistical measure using supplied function. Designed to be
used with passed-in Cython array-based functions.
Parameters
----------
func : string/... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/_Rolling._apply |
3,160 | def count(self):
obj = self._convert_freq()
window = self._get_window()
window = min(window, len(obj)) if not self.center else window
blocks, obj = self._create_blocks(how=None)
results = []
for b in blocks:
if com.needs_i8_conversion(b.values):
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/_Rolling_and_Expanding.count |
3,161 | def _apply(self, func, how=None, **kwargs):
"""Rolling statistical measure using supplied function. Designed to be
used with passed-in Cython array-based functions.
Parameters
----------
func : string/callable to apply
how : string, default to None (DEPRECATED)
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/window.py/EWM._apply |
3,162 | def render(input, saltenv='base', sls='', argline='', **kws):
gen_start_state = False
no_goal_state = False
implicit_require = False
def process_sls_data(data, context=None, extract=False):
sls_dir = ospath.dirname(sls.replace('.', ospath.sep)) if '.' in sls else sls
ctx = dict(sls_dir=... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/renderers/stateconf.py/render |
3,163 | def add_implicit_requires(data):
def T(sid, state): # pylint: disable=C0103
return '{0}:{1}'.format(sid, state_name(state))
states_before = set()
states_after = set()
for sid in data:
for state in data[sid]:
states_after.add(T(sid, state))
prev_state = (None, None) ... | StopIteration | dataset/ETHPy150Open saltstack/salt/salt/renderers/stateconf.py/add_implicit_requires |
3,164 | def get_version_delta_info(self, block_version):
if block_version.time == -1:
return None
try:
return self._dev_versions[block_version]
except __HOLE__:
pass
assert block_version.time is not None
try:
delta = self._store.get_delta_... | KeyError | dataset/ETHPy150Open biicode/client/api/biiapi_proxy.py/BiiAPIProxy.get_version_delta_info |
3,165 | def qs_delete(self, *keys):
'''Delete value from QuerySet MultiDict'''
query = self.query.copy()
for key in set(keys):
try:
del query[key]
except __HOLE__:
pass
return self._copy(query=query) | KeyError | dataset/ETHPy150Open SmartTeleMax/iktomi/iktomi/web/url.py/URL.qs_delete |
3,166 | def _get_range(self, dim, start, end):
"""Create a :class:`Range` for the :class:`Chart`.
Args:
dim (str): the name of the dimension, which is an attribute of the builder
start: the starting value of the range
end: the ending value of the range
Returns:
... | AttributeError | dataset/ETHPy150Open bokeh/bokeh/bokeh/charts/builder.py/XYBuilder._get_range |
3,167 | def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and use it to
fill in 'self.filelist', the list of files to include in the source
distribution.
"""
log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest, 'rbU')
... | UnicodeDecodeError | dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/command/sdist.py/sdist.read_manifest |
3,168 | def __init__(self, bulk_insert=1000, **kwargs):
try:
mysql = __import__('MySQLdb')
filterwarnings('ignore', category=mysql.Warning)
self.to_buffer = lambda buf: buf
except __HOLE__:
try:
mysql = __import__('pymysql')
self.to... | ImportError | dataset/ETHPy150Open chriso/gauged/gauged/drivers/mysql.py/MySQLDriver.__init__ |
3,169 | def preexec_setpgid_setrlimit(memory_limit):
if resource is not None:
def _preexec():
os.setpgid(0, 0)
try:
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
except __HOLE__:
pass # No permission
if memory_limit:
try:
(soft, hard) = resource.getrlimit(reso... | ValueError | dataset/ETHPy150Open jansel/opentuner/opentuner/measurement/interface.py/preexec_setpgid_setrlimit |
3,170 | def goodwait(p):
"""
python doesn't check if its system calls return EINTR, retry if it does
"""
while True:
try:
rv = p.wait()
return rv
except __HOLE__, e:
if e.errno != errno.EINTR:
raise | OSError | dataset/ETHPy150Open jansel/opentuner/opentuner/measurement/interface.py/goodwait |
3,171 | def optimizeTextures(mesh):
previous_images = []
for cimg in mesh.images:
previous_images.append(cimg.path)
pilimg = cimg.pilimage
#PIL doesn't support DDS, so if loading failed, try and load it as a DDS with panda3d
if pilimg is None:
imgdata ... | IOError | dataset/ETHPy150Open pycollada/meshtool/meshtool/filters/optimize_filters/optimize_textures.py/optimizeTextures |
3,172 | def on_mouse_motion(self, x, y, dx, dy):
cx, cy = x//hw, y//hh
try:
if (self.play_field[cx, cy] or self.play_field[cx+1, cy] or
self.play_field[cx, cy+1] or self.play_field[cx+1, cy+1]):
self.show_highlight = False
return True
excep... | KeyError | dataset/ETHPy150Open ardekantur/pyglet/contrib/spryte/dtd/dtd.py/Game.on_mouse_motion |
3,173 | def body_complete(self):
"""
Called when the body of the message is complete
NOINDEX
"""
try:
self.body = _decode_encoded(self._data_obj.body,
self._encoding_type)
except __HOLE__:
# Screw handling it gracef... | IOError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/http.py/HTTPMessage.body_complete |
3,174 | @property
def saved(self):
"""
If the request is saved in the data file
:getter: Returns True if the request is saved in the data file
:type: Bool
"""
if self.reqid is None:
return False
try:
_ = int(self.reqid)
return True... | ValueError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/http.py/Request.saved |
3,175 | @defer.inlineCallbacks
def async_save(self, cust_dbpool=None, cust_cache=None):
"""
async_save()
Save/update the request in the data file. Returns a twisted deferred which
fires when the save is complete.
:rtype: twisted.internet.defer.Deferred
"""
from .papp... | ValueError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/http.py/Request.async_save |
3,176 | @staticmethod
@defer.inlineCallbacks
def load_request(to_load, allow_special=True, use_cache=True, cust_dbpool=None, cust_cache=None):
"""
load_request(to_load)
Load a request with the given request id and return it.
Returns a deferred which calls back with the request when compl... | TypeError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/http.py/Request.load_request |
3,177 | @defer.inlineCallbacks
def async_save(self, cust_dbpool=None, cust_cache=None):
"""
async_save()
Save/update the just request in the data file. Returns a twisted deferred which
fires when the save is complete. It is suggested that you use
:func: `~pappyproxy.http.Request.asyn... | TypeError | dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/http.py/Response.async_save |
3,178 | def run(self):
print 'JPGVisLoadingThread.run called'
while not self.is_timed_out():
with self.state.lock:
if self.state.quit:
break
#print 'JPGVisLoadingThread.run: caffe_net_state is:', self.state.caffe_net_state
... | IOError | dataset/ETHPy150Open yosinski/deep-visualization-toolbox/caffevis/jpg_vis_loading_thread.py/JPGVisLoadingThread.run |
3,179 | def curve_to_lut(colorspace, gamma, outlutfile, out_type=None, out_format=None,
input_range=None, output_range=None, out_bit_depth=None,
out_cube_size=None, verbose=False, direction=Direction.ENCODE,
preset=None, overwrite_preset=False,
process_input_r... | KeyError | dataset/ETHPy150Open mikrosimage/ColorPipe-tools/lutLab/curve_to_lut.py/curve_to_lut |
3,180 | @classmethod
def from_uri(cls, uri):
# TODO(termie): very simplistic
#m = cls._re_jid.search(uri)
node, rest = uri.split('@', 1)
try:
host, rest = rest.split('/', 1)
resource = '/' + rest
except __HOLE__:
host = rest
resource = '/'
return cls(node, host, resource) | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/common/protocol/xmpp.py/JID.from_uri |
3,181 | def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scal... | IndexError | dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/complex_hardware/transformations.py/scale_from_matrix |
3,182 | def euler_matrix(ai, aj, ak, axes='sxyz'):
"""Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> numpy.allclose(numpy.sum(R[0]),... | KeyError | dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/complex_hardware/transformations.py/euler_matrix |
3,183 | def euler_from_matrix(matrix, axes='sxyz'):
"""Return Euler angles from rotation matrix for specified axis sequence.
axes : One of 24 axis sequences as string or encoded tuple
Note that many Euler angle triplets can describe one matrix.
>>> R0 = euler_matrix(1, 2, 3, 'syxz')
>>> al, be, ga = eule... | AttributeError | dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/complex_hardware/transformations.py/euler_from_matrix |
3,184 | def quaternion_from_euler(ai, aj, ak, axes='sxyz'):
"""Return quaternion from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
>>> numpy.allclose(q, [0.435953, 0... | AttributeError | dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/complex_hardware/transformations.py/quaternion_from_euler |
3,185 | def _import_module(name, package=None, warn=True, prefix='_py_', ignore='_'):
"""Try import all public attributes from module into global namespace.
Existing attributes with name clashes are renamed with prefix.
Attributes starting with underscore are ignored by default.
Return True on successful impo... | ImportError | dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/complex_hardware/transformations.py/_import_module |
3,186 | def safe_finish(self):
"""Finish session. If it will blow up - connection was set to Keep-Alive and
client dropped connection, ignore any IOError or socket error."""
try:
self.finish()
except (socket.error, __HOLE__):
# We don't want to raise IOError exception if ... | IOError | dataset/ETHPy150Open benoitc/gaffer/gaffer/sockjs/basehandler.py/BaseHandler.safe_finish |
3,187 | def oauth2_callback(request):
""" View that handles the user's return from OAuth2 provider.
This view verifies the CSRF state and OAuth authorization code, and on
success stores the credentials obtained in the storage provider,
and redirects to the return_url specified in the authorize view and
sto... | KeyError | dataset/ETHPy150Open google/oauth2client/oauth2client/contrib/django_util/views.py/oauth2_callback |
3,188 | def _command(self, name, *args):
if self.state not in Commands[name]:
self.literal = None
raise self.error("command %s illegal in state %s, "
"only allowed in states %s" %
(name, self.state,
'... | OSError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/imaplib.py/IMAP4._command |
3,189 | def on_done(self, s):
self._restore_sel()
try:
SearchImpl(self.view, s, start_sel=self.original_sel).search()
ex_commands.VintageExState.search_buffer_type = 'pattern_search'
except __HOLE__, e:
if 'parsing' in str(e):
print "VintageEx: ... | RuntimeError | dataset/ETHPy150Open SublimeText/VintageEx/ex_search_cmd.py/ViSearch.on_done |
3,190 | def on_change(self, s):
if s in ("/", "?"):
return
self._restore_sel()
try:
SearchImpl(self.view, s, remember=False,
start_sel=self.original_sel).search()
except __HOLE__, e:
if 'parsing' in str(e):
print... | RuntimeError | dataset/ETHPy150Open SublimeText/VintageEx/ex_search_cmd.py/ViSearch.on_change |
3,191 | def _handle_callback(self, message):
if self.host_id == message.get('host_id'):
try:
sid = message['sid']
namespace = message['namespace']
id = message['id']
args = message['args']
except __HOLE__:
return
... | KeyError | dataset/ETHPy150Open miguelgrinberg/python-socketio/socketio/pubsub_manager.py/PubSubManager._handle_callback |
3,192 | def set(self, key, value):
key = make_md5(make_hashable(key))
self.cache[key] = value
try:
self.keys.remove(key)
except __HOLE__:
pass
self.keys.append(key)
# limit cache to the given capacity
to_delete = self.keys[0:max(0, len(self.keys)-... | ValueError | dataset/ETHPy150Open miracle2k/webassets/src/webassets/cache.py/MemoryCache.set |
3,193 | def get(self, key):
filename = path.join(self.directory, '%s' % make_md5(self.V, key))
try:
f = open(filename, 'rb')
except __HOLE__ as e:
if e.errno != errno.ENOENT:
raise
return None
try:
result = f.read()
finally:... | IOError | dataset/ETHPy150Open miracle2k/webassets/src/webassets/cache.py/FilesystemCache.get |
3,194 | def fetch_command(self, global_options, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"uliweb") if it can't be found.
"""
commands = self.get_commands(global_options)
... | KeyError | dataset/ETHPy150Open limodou/uliweb/uliweb/core/commands.py/CommandManager.fetch_command |
3,195 | def do_command(self, args, global_options):
try:
subcommand = args[0]
except __HOLE__:
subcommand = 'help' # Display help if no arguments were given.
if subcommand == 'help':
if len(args) > 1:
command = self.fetch_command(global_op... | IndexError | dataset/ETHPy150Open limodou/uliweb/uliweb/core/commands.py/CommandManager.do_command |
3,196 | def __read_id(self):
'''
Read the next ID number and do the appropriate task with it.
Returns nothing.
'''
try:
# float32 -- ID of the first data sequence
objid = np.fromfile(self._fsrc, dtype=np.float32, count=1)[0]
except __HOLE__:
#... | IndexError | dataset/ETHPy150Open NeuralEnsemble/python-neo/neo/io/brainwaref32io.py/BrainwareF32IO.__read_id |
3,197 | def RunTest():
try:
arcpy.AddMessage("Starting Test: TestLocalPeaks")
#TEST_IMPLEMENTED = False
#
#if not TEST_IMPLEMENTED :
# arcpy.AddWarning("***Test Not Yet Implemented***")
# return
# TODO: once model has a version that works with local surface da... | ImportError | dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/test/test_maot/TestModelLocalPeaks.py/RunTest |
3,198 | def _convert(self, n):
# n is the native node produced by the ast module
if n is None:
return None # but some node attributes can be None
assert isinstance(n, ast.AST)
# Get converter function
type = n.__class__.__name__
try:
con... | AttributeError | dataset/ETHPy150Open zoofIO/flexx/flexx/pyscript/commonast.py/NativeAstConverter._convert |
3,199 | def __get__(self, instance, model):
# override TaggableManager's requirement for instance to have a primary key
# before we can access its tags
try:
manager = _ClusterTaggableManager(
through=self.through, model=model, instance=instance, prefetch_cache_name=self.name
... | TypeError | dataset/ETHPy150Open torchbox/django-modelcluster/modelcluster/contrib/taggit.py/ClusterTaggableManager.__get__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.