code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if len(p)==4: if p[2] == Symbols.EQUIVALENCE.value: p[0] = PLEquivalence([p[1], p[3]]) elif p[2] == Symbols.IMPLIES.value: p[0] = PLImplies([p[1], p[3]]) elif p[2] == Symbols.OR.value: p[0] = PLOr([p[1], p[3]]) ...
def p_propositional(self, p)
propositional : propositional EQUIVALENCE propositional | propositional IMPLIES propositional | propositional OR propositional | propositional AND propositional | NOT propositional | FALSE ...
1.834715
1.778027
1.031882
primary_domain = config['domain'] domains = set(config.get('aliases', [])) | set((primary_domain,)) domain_patterns = compile_regexes(domains) redirect_domains = set(config.get('redirects', [])) redirect_domain_patterns = compile_regexes(redirect_domains) url = yurl.URL(current_url) if ...
def get_redirect_url(current_url, config, https=None)
priorities are (primary domain and aliases are treated the same): exact redirect match > exact alias match > pattern redirect match > pattern alias match :param current_url: the url that is being called :param config: redirect configuration for this url :param want_https: whether redirects should go...
2.708823
2.516032
1.076625
if self.callback is not None: loop = asyncio.get_event_loop() return loop.run_until_complete(self.async_invoke(ctx))
def invoke(self, ctx)
Given a context, this invokes the attached callback (if it exists) in the right way.
3.301273
2.964413
1.113635
help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return def show_help(ctx, param, value): import abot.bot if value and not ctx.resilient_parsing: event: abot.bot.MessageEvent = abot.bot.c...
def get_help_option(self, ctx)
Returns the help option object.
3.610598
3.392309
1.064348
size_class = 'size-{0}'.format(self.num_inputs) if 'class' in attrs: attrs['class'] += ' {0}'.format(size_class) else: attrs['class'] = size_class
def get_widget_css_class(self, attrs)
Gets the class for the widget.
3.300015
3.205986
1.029329
r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = PLLexer.reserved.get(t.value, 'ATOM') # Check for reserved words return t
def t_ATOM(self, t)
r'[a-zA-Z_][a-zA-Z_0-9]*
4.224628
4.144888
1.019238
if p[1]==Symbols.TRUE.value: p[0] = PLTrue() elif p[1]==Symbols.FALSE.value: p[0] = PLFalse() else: p[0] = PLAtomic(Symbol(p[1]))
def p_formula_atom(self, p)
formula : ATOM | TRUE | FALSE
3.101299
3.246527
0.955267
try: if prefetch_related: query_set = self.prefetch_related(*prefetch_related) elif select_related == True: query_set = self.select_related() elif isinstance(select_related, (list, tuple)): query_set = self.select_relat...
def get_or_none(self, prefetch_related=None, select_related=False, **kwargs)
Gets a single object based on kwargs or None if one is not found. :param prefetch_related: list or tuple of fields to prefetch for an object. This takes precedence over select_related. Example: >> get_or_none(prefetch_related=['some_field', ... ...
1.786487
2.004931
0.891046
obj = self.get_by_id(id=id, **kwargs) if obj: return obj raise Http404
def get_by_id_or_404(self, id, **kwargs)
Gets by a instance instance r raises a 404 is one isn't found.
3.414376
3.142038
1.086675
if hasattr(self.model, 'save_prep'): # Method from AbstractBaseModel. If the model class doesn't # subclass AbstractBaseModel, then don't call this. self.model.save_prep(instance_or_instances=objs) return super(CommonManager, self).bulk_create(objs=objs, ...
def bulk_create(self, objs, *args, **kwargs)
Insert many object at once.
6.495905
6.044319
1.074713
try: self.filter(id__in=ids).delete() return True except self.model.DoesNotExist: return False
def delete_by_ids(self, ids)
Delete objects by ids. :param ids: list of objects ids to delete. :return: True if objects were deleted. Otherwise, return False if no objects were found or the delete was not successful.
3.14723
3.5754
0.880246
try: self.get(slug=slug, **kwargs) return False except self.model.DoesNotExist: return True
def is_slug_available(self, slug, **kwargs)
Checks to see if a slug is available. If the slug is already being used this method returns False. Otherwise, return True.
2.414327
2.403891
1.004341
original_slug = slug = slugify(slug) count = 0 while not self.is_slug_available(slug=slug, **kwargs): count += 1 slug = '{0}-{1}'.format(original_slug, count) return slug
def get_next_slug(self, slug, **kwargs)
Gets the next available slug. :param slug: the slug to slugify :param kwargs: additional filter criteria to check for when looking for a unique slug. Example: if the value "my-slug" is already taken, this method will append "-n" to the end of the slug until the nex...
2.78756
3.424221
0.814071
return self.get_available_tokens(count=1, token_length=length, **kwargs)[0]
def get_next_token(self, length=15, **kwargs)
Gets the next available token. :param length: length of the token :param kwargs: additional filter criteria to check for when looking for a unique token.
8.512221
8.675132
0.981221
# This is the number of extra tokens to try and retrieve so calls to # the db can be limited token_buffer = int(math.ceil(count * .05)) if token_buffer < 5: token_buffer = 5 available = set([]) while True: tokens = [random_alphanum(leng...
def get_available_tokens(self, count=10, token_length=15, **kwargs)
Gets a list of available tokens. :param count: the number of tokens to return. :param token_length: the length of the tokens. The higher the number the easier it will be to return a list. If token_length == 1 there's a strong probability that the enough tokens will exist in ...
4.020823
4.01135
1.002361
if content_object: kwargs['content_type'] = ContentType.objects.get_for_model( content_object ) kwargs['object_id'] = content_object.id return self.create(**kwargs)
def create_generic(self, content_object=None, **kwargs)
Create a generic object. :param content_object: the content object to create a new object for.
2.209585
2.515527
0.878379
if content_object: kwargs['content_type'] = ContentType.objects.get_for_model( content_object ) kwargs['object_id'] = content_object.id return self.filter(**kwargs)
def filter_generic(self, content_object=None, **kwargs)
Filter by a generic object. :param content_object: the content object to filter on.
2.210132
2.717448
0.813312
if content_object: kwargs['content_type'] = ContentType.objects.get_for_model( content_object ) kwargs['object_id'] = content_object.id return self.get_or_create(**kwargs)
def get_or_create_generic(self, content_object=None, **kwargs)
Gets or creates a generic object. This is a wrapper for get_or_create(...) when you need to get or create a generic object. :param obj: the object to get or create :param kwargs: any other kwargs that the model accepts.
2.181239
2.446594
0.891541
content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type)
def get_by_model(self, model)
Gets all object by a specific model.
2.784296
2.372483
1.173579
if not obj or not hasattr(obj, attr): return '' return getattr(obj, attr, '')
def attr(obj, attr)
Does the same thing as getattr. getattr(obj, attr, '')
3.911752
3.481009
1.123741
if not obj: return tuple() if isinstance(obj, (list, tuple, set)): return obj return (obj,)
def make_iterable(obj)
Make an object iterable. >>> make_iterable(obj='hello') ('hello',) >>> make_iterable(obj=None) ()
3.422886
4.260448
0.80341
kwargs = super(ApiFormView, self).get_form_kwargs() kwargs['data'] = kwargs.get('initial') return kwargs
def get_form_kwargs(self)
Add the 'data' to the form args so you can validate the form data on a get request.
4.137799
3.209733
1.289141
if not context: context = {} context['errors'] = form.errors return super(ApiFormView, self).render_to_response(context=context, status=400)
def form_invalid(self, form, context=None, **kwargs)
This will return the request with form errors as well as any additional context.
3.616916
3.465849
1.043587
if not value: return False regex = re.compile(HEX_COLOR_REGEX) return bool(regex.match(value))
def is_valid_hex(value)
Boolean indicating of the value is a valid hex value.
3.986939
3.828185
1.04147
if not value: return False regex = re.compile(RGB_COLOR_REGEX) return bool(regex.match(value))
def is_valid_rgb_color(value)
Checks whether the value is a valid rgb or rgba color string. Valid colors consist of: - rgb(255, 255, 255) - rgba(23, 34, 45, .5)
3.496983
4.848174
0.721299
min_length = 7 if len(value) < min_length: raise ValidationError(_('Password must be at least {0} characters ' 'long.').format(min_length)) # check for digit if not any(char.isdigit() for char in value): raise ValidationError(_('Password must contai...
def validate_password_strength(value)
Validates that a password is as least 7 characters long and has at least 1 digit and 1 letter.
1.875808
1.772452
1.058312
def wrapper(cls): orig_vars = cls.__dict__.copy() orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
def add_metaclass(metaclass)
Class decorator for creating a class with a metaclass.
1.536749
1.576439
0.974823
if not value: return None # if any value exists, then add "0" as a placeholder to the remaining # values. if isinstance(value, list) and any(value): for i, item in enumerate(value): if not item: value[i] = '0' ...
def clean(self, value)
Validates that the input can be converted to a list of decimals.
4.506302
4.298501
1.048343
if not value: return None if isinstance(value, list): for index, position_val in enumerate(value): val = super(MultipleDecimalField, self).to_python(position_val) value[index] = val return value
def to_python(self, value)
Validates that the input can be converted to a list of decimals.
4.087191
3.444104
1.186721
character_set = ALPHANUM_LOWER if lower_only else ALPHANUM sample_size = 5 chars = random.sample(character_set, sample_size) while len(chars) < length: chars += random.sample(character_set, sample_size) random.shuffle(chars) return ''.join(chars[:length])
def random_alphanum(length=10, lower_only=False)
Gets a random alphanumeric value using both letters and numbers. :param length: size of the random alphanumeric string. :param lower_only: boolean indicating if only lower case letters should be used. :return: alphanumeric string size of length This function uses all number except for: * ...
2.762313
3.628545
0.761273
return random_alphanum(length=randint(7, 10), lower_only=lower_only)
def generate_key(low=7, high=10, lower_only=False)
Gets a random alphanumeric key between low and high characters in length.
6.369509
6.380137
0.998334
if text is None: text = self.get_link_text() return build_link(href=self.get_absolute_url(), text=text, cls=cls, icon_class=icon_class, **attrs)
def get_absolute_url_link(self, text=None, cls=None, icon_class=None, **attrs)
Gets the html link for the object.
2.434995
2.357306
1.032957
if text is None: text = 'Edit' return build_link(href=self.get_edit_url(), text=text, cls=cls, icon_class=icon_class, **attrs)
def get_edit_url_link(self, text=None, cls=None, icon_class=None, **attrs)
Gets the html edit link for the object.
2.672087
2.635074
1.014046
if text is None: text = 'Delete' return build_link(href=self.get_delete_url(), text=text, cls=cls, icon_class=icon_class, **attrs)
def get_delete_url_link(self, text=None, cls=None, icon_class=None, **attrs)
Gets the html delete link for the object.
2.533864
2.48415
1.020013
if not email_address: # no email(s) provided. Nothing to do. return None if isinstance(email_address, (set, list, tuple)): email_address = [e.strip() for e in set(email_address) if e and e.strip()] # make sure there...
def expire_by_email(self, email_address, **kwargs)
Expires tokens for an email address or email addresses. :param email_address: the string email address or emails addresses to expire tokens for. :param reason: the codified reason for the tokens. If explicitly set to None, this will expire all tokens for the email provided.
3.559075
3.391452
1.049425
if (not self.query_key_mapper or self.request.method == 'POST'): # Nothing to map, don't do anything. # return self.request.POST return {} keys = list(self.query_key_mapper.keys()) return {self.query_key_mapper.get(k) if k in keys else k...
def map_query_string(self)
Maps the GET query string params the the query_key_mapper dict and updates the request's GET QueryDict with the mapped keys.
4.144009
3.269145
1.267612
# Make the cloning directory and change directories into it. tmp_dir = tempfile.mkdtemp(dir=os.getcwd()) # Iterate through each repository. for owner, repo_name in REPOS_TO_CHANGE: repo_url = REPO_URL_FORMAT.format(owner, repo_name) gh = GitHubApiUtils(owner, repo_name) o...
def bump_repos_version(module_name, new_version, local_only)
Changes the pinned version number in the requirements files of all repos which have the specified Python module as a dependency. This script assumes that GITHUB_TOKEN is set for GitHub authentication.
3.02868
2.965082
1.021449
url = self.SLACK_RPC_PREFIX + method data = FormData() data.add_fields(MultiDict(token=self.bot_token, charset='utf-8', **params)) response_body = await self.request( method='POST', url=url, data=data ) if 'warning' in response...
async def call(self, method, **params)
Call an Slack Web API method :param method: Slack Web API method to call :param params: {str: object} parameters to method :return: dict()
4.055293
3.951952
1.026149
message = json.loads(ws_message.data) if 'reply_to' in message: reply_to = message['reply_to'] future = self.response_futures.pop(reply_to, None) if future is None: logger.error(f'This should not happen, received reply to unknown message! {mes...
def rtm_handler(self, ws_message)
Handle a message, processing it internally if required. If it's a message that should go outside the bot, this function will return True :param message: :return: Boolean if message should be yielded
2.816498
3.008983
0.93603
r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = LTLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words return t
def t_ATOM(self, t)
r'[a-zA-Z_][a-zA-Z_0-9]*
4.09864
4.026663
1.017875
if len(p) == 2: if p[1] == Symbols.TRUE.value: p[0] = LTLfTrue() elif p[1] == Symbols.FALSE.value: p[0] = LTLfFalse() else: p[0] = LTLfAtomic(Symbol(p[1])) elif len(p) == 3: if p[1] == Symbols.NEXT.v...
def p_formula(self, p)
formula : formula EQUIVALENCE formula | formula IMPLIES formula | formula OR formula | formula AND formula | formula UNTIL formula | formula RELEASE formula | EVENTUALLY formula | ALWAYS ...
1.507378
1.393922
1.081393
if instance is None and hasattr(self, 'instance'): instance = self.instance if instance and instance.id is not None: # it's an existing instance, use the instance prefix instance_prefix = self.default_instance_prefix if instance_prefix is None: ...
def get_default_prefix(self, instance=None)
Gets the prefix for this form. :param instance: the form model instance. When calling this method directly this should almost always stay None so it looks for self.instance.
3.033264
2.996127
1.012395
# If username is an email address, then try to pull it up user = self.get_by_username_or_email(username) if not user: return None if user.check_password(password): return user return None
def authenticate(self, username, password)
:param username: this is the email or username to check
3.89581
3.960184
0.983745
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" combs = _powerset(iterable) res = frozenset(frozenset(x) for x in combs) # res = map(frozenset, combs) return res
def powerset(iterable) -> FrozenSet
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
2.630949
2.296202
1.145783
if hasattr(obj, 'get_edit_url_link'): return obj.get_edit_url_link(**kwargs) edit_url = obj.get_edit_url() return build_link(href=edit_url, **kwargs)
def edit_url_link(obj, **kwargs)
This method assumes that the "get_delete_url_link" method has been implemented on the obj.
3.046291
2.977272
1.023182
if hasattr(obj, 'get_delete_url_link'): return obj.get_delete_url_link(**kwargs) delete_url = obj.get_delete_url() return build_link(href=delete_url, **kwargs)
def delete_url_link(obj, **kwargs)
This method assumes that the "get_delete_url_link" method has been implemented on the obj.
3.275401
3.035586
1.079001
defaults = { 'form_class': form_class or self.get_form_class() } defaults.update(kwargs) return super(ListField, self).formfield(**defaults)
def formfield(self, form_class=None, choices_form_class=None, **kwargs)
Make the default formfield a CommaSeparatedListField.
2.880669
2.482202
1.16053
self.get_choices_form_class().validate(value, model_instance, **kwargs)
def validate(self, value, model_instance, **kwargs)
This follows the validate rules for choices_form_class field used.
6.295131
2.780937
2.263673
if isinstance(value, dict): return value if self.blank and not value: return None if isinstance(value, string_types): try: return json.loads(value) except Exception as e: raise ValidationError(str(e)) ...
def to_python(self, value)
Convert the input JSON value into python structures, raises django.core.exceptions.ValidationError if the data can't be converted.
2.867209
2.588511
1.107667
try: return json.dumps(value, cls=DjangoJSONEncoder) except Exception as e: raise ValidationError(str(e))
def get_prep_value(self, value)
Convert value to JSON string before save
3.228398
2.645138
1.220503
assert isinstance(a, GenericMeta) while a.__origin__ is not None: a = a.__origin__ return a
def _gorg(a)
Return the farthest origin of a generic class (internal helper).
4.622325
2.80851
1.645828
next_in_mro = object # Look for the last occurrence of Generic or Generic[...]. for i, c in enumerate(cls.__mro__[:-1]): if isinstance(c, GenericMeta) and _gorg(c) is Generic: next_in_mro = cls.__mro__[i + 1] return next_in_mro
def _next_in_mro(cls)
Helper for Generic.__new__. Returns the class after the last occurrence of Generic or Generic[...] in cls.__mro__.
4.192859
3.411077
1.229189
if isinstance(cls.__extra__, abc.ABCMeta): # The logic mirrors that of ABCMeta.__subclasscheck__. # Registered classes need not be checked here because # cls and its extra share the same _abc_registry. def __extrahook__(cls, subclass): res = cls.__extra__.__subclassh...
def _make_subclasshook(cls)
Construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls.
5.095109
4.612236
1.104694
if self.authorization is not None: return self.authorization auth_class = self.get_authorization_class() auth_user = self.get_authorization_user() auth_kwargs = { 'token': self.get_authorization_token(**kwargs) } if auth_user and auth_us...
def get_authorization(self, **kwargs)
Gets the authorization object for the view.
2.795637
2.613566
1.069664
if self.authorization_user is not None: return self.authorization_user self.authorization_user = self.request.user return self.request.user
def get_authorization_user(self, **kwargs)
Gets the user the authorization object is for.
3.140218
2.917516
1.076333
# type: (Type[dict]) -> Dict[str, Any] pairs = tuple((k, serialize_object(getattr(self, k), dict_cls)) for k in self.call_types) if self.typeid: d = dict_cls((("typeid", self.typeid),) + pairs) else: d = dict_cls(pairs) retur...
def to_dict(self, dict_cls=FrozenOrderedDict)
Create a dictionary representation of object attributes Returns: OrderedDict serialised version of self
4.179545
5.075258
0.823514
if is_legit_next_url(next_url): return redirect(next_url) if default: return redirect(default) return redirect('/')
def safe_redirect(next_url, default=None)
Makes sure it's a legit site to redirect to. :param default: this is the default url or named url to redirect to in the event where next_url is not legit.
3.792163
4.031842
0.940553
if '?' not in url: return url parsed_url = urlparse(url) query = dict(parse_qsl(parsed_url.query)) query.update(replace_vals) return '{0}?{1}'.format(url.split('?')[0], urlencode(query))
def replace_url_query_values(url, replace_vals)
Replace querystring values in a url string. >>> url = 'http://helloworld.com/some/path?test=5' >>> replace_vals = {'test': 10} >>> replace_url_query_values(url=url, replace_vals=replace_vals) 'http://helloworld.com/some/path?test=10'
2.217359
2.768567
0.800905
if not url or '?' not in url: # no query params return None parsed_url = urlparse(url) query = dict(parse_qsl(parsed_url.query)) if keys is None: return query if isinstance(keys, string_types): return query.get(keys) return {k: query.get(k) for k in keys}
def get_query_values_from_url(url, keys=None)
Gets query string values from a url. if a list of keys are provided, then a dict will be returned. If only a single string key is provided, then only a single value will be returned. >>> url = 'http://helloworld.com/some/path?test=5&hello=world&john=doe' >>> get_query_values_from_url(url=url, keys='t...
2.240774
2.602367
0.861052
# Don't care to return a django form or view in the response here. # Remove those from the context. if isinstance(content, dict): response_content = {k: deepcopy(v) for k, v in content.items() if k not in ('form', 'view') or k in ('form', 'vi...
def get_json_response(self, content, **kwargs)
Returns a json response object.
3.66702
3.600771
1.018399
self.object = self.get_object() success_url = self.get_success_url() self.object.delete() if self.request.is_ajax(): return JSONResponseMixin.render_to_response(self, context={}) return HttpResponseRedirect(success_url)
def delete(self, request, *args, **kwargs)
Calls the delete() method on the fetched object and then redirects to the success URL.
2.699446
2.38383
1.132399
f = formula res = set() if isinstance(formula, PLFormula): res = formula.find_atomics() # elif isinstance(f, PLNot): # res = res.union(find_atomics(f.f)) # elif isinstance(f, PLBinaryOperator): # for subf in f.formulas: # res = res.union(find_atomics(subf)) ...
def find_atomics(formula: Formula) -> Set[PLAtomic]
Finds all the atomic formulas
2.573795
2.525964
1.018935
t = type(f) if t == PLNot: return PLNot(_transform_delta(f, formula2AtomicFormula)) # elif isinstance(f, PLBinaryOperator): #PLAnd, PLOr, PLImplies, PLEquivalence elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence: return t([_transform_delta(subf, formula2AtomicFor...
def _transform_delta(f:Formula, formula2AtomicFormula)
From a Propositional Formula to a Propositional Formula with non-propositional subformulas replaced with a "freezed" atomic formula.
2.896092
2.769835
1.045583
has_default = 'default' in kwargs default_val = kwargs.get('default') try: if has_default: return getattr(settings, key, default_val) else: return getattr(settings, key) except Exception as e: raise ImproperlyConfigured( _('"{0}" setting ...
def get_setting(key, **kwargs)
Gets a settings key or raises an improperly configured error. :param key: the settings key to get. :param default: the default value to return if no value is found
2.727532
3.262957
0.835908
cls_path = getattr(settings, settings_key, None) if not cls_path: raise NotImplementedError() try: # First check to see if it's an installed model return get_model_from_settings(settings_key=settings_key) except: try: # Next, check from installed apps ...
def get_class_from_settings(settings_key)
Gets a class from a setting key. This will first check loaded models, then look in installed apps, then fallback to import from lib. :param settings_key: the key defined in settings to the value for
3.188554
3.341298
0.954286
cls_path = getattr(settings, settings_key, None) if not cls_path: raise NotImplementedError() try: app_label, model_name = cls_path.split('.') except ValueError: raise ImproperlyConfigured("{0} must be of the form " "'app_label.model_name'...
def get_model_from_settings(settings_key)
Return the django model from a settings key. This is the same pattern user for django's "get_user_model()" method. To allow you to set the model instance to a different model subclass. :param settings_key: the key defined in settings to the value for
2.08016
2.181162
0.953693
cls_path = getattr(settings, settings_key, None) if not cls_path: raise NotImplementedError() try: app_label = cls_path.split('.')[-2] model_name = cls_path.split('.')[-1] except ValueError: raise ImproperlyConfigured("{0} must be of the form " ...
def get_class_from_settings_from_apps(settings_key)
Try and get a class from a settings path by lookin in installed apps.
2.358903
2.326232
1.014044
cls_path = getattr(settings, settings_key, None) if not cls_path: raise NotImplementedError() try: module_name, class_name = cls_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("{0} must be of the form " "'some.path.modu...
def get_class_from_settings_full_path(settings_key)
Get a class from it's full path. Example: some.path.module.MyClass
2.67138
2.717383
0.983071
renderer_func_str = getattr(settings, settings_key, None) if not renderer_func_str: return None module_str, renderer_func_name = renderer_func_str.rsplit('.', 1) try: mod = importlib.import_module(module_str) return getattr(mod, renderer_func_name) except Exception: ...
def get_function_from_settings(settings_key)
Gets a function from the string path defined in a settings file. Example: # my_app/my_file.py def some_function(): # do something pass # settings.py SOME_FUNCTION = 'my_app.my_file.some_function' > get_function_from_settings('SOME_FUNCTION') <function my_app.my_file.some_...
2.406119
2.678553
0.898291
# type: () -> Dict try: raise ValueError except ValueError: _, _, tb = sys.exc_info() assert tb, "Can't get traceback, this shouldn't happen" caller_frame = tb.tb_frame.f_back.f_back return caller_frame.f_locals
def caller_locals()
Return the frame object for the caller's stack frame.
3.848442
3.872185
0.993868
# type: (object, Sequence[str]) -> str arg_str = ", ".join( "%s=%r" % (a, getattr(inst, a)) for a in attrs if hasattr(inst, a)) repr_str = "%s(%s)" % (inst.__class__.__name__, arg_str) return repr_str
def make_repr(inst, attrs)
Create a repr from an instance of a class Args: inst: The class instance we are generating a repr of attrs: The attributes that should appear in the repr
2.275045
3.644529
0.624236
pkg = mod.rsplit('-python')[0] pkg = pkg.replace('_', '-').replace('.', '-').lower() if not pkg.startswith('python-'): pkg = 'python-' + pkg py2pkg = pkg py3pkg = re.sub('python', 'python3', pkg) return (pkg, py2pkg, py3pkg)
def default_rdo_tr(mod)
Default translation function for Fedora/RDO based systems
4.524299
4.105875
1.101909
pkg = 'python-%s' % mod.lower() py2pkg = pkg py3pkg = 'python3-%s' % mod.lower() return (pkg, py2pkg, py3pkg)
def default_ubuntu_tr(mod)
Default translation function for Ubuntu based systems
4.21698
3.939547
1.070423
pkg = 'python-%s' % mod py2pkg = 'python2-%s' % mod py3pkg = 'python3-%s' % mod return (pkg, py2pkg, py3pkg)
def default_suse_tr(mod)
Default translation function for openSUSE, SLES, and other SUSE based systems Returns a tuple of 3 elements - the unversioned name, the python2 versioned name and the python3 versioned name.
3.334514
2.81059
1.186411
if not pkg_map: pkg_map = get_pkg_map(dist) for rule in pkg_map: pkglist = rule(mod, dist) if pkglist: break else: tr_func = get_default_tr_func(dist) pkglist = tr_func(mod) output = [] for v in py_vers: if v == 'py': outp...
def module2package(mod, dist, pkg_map=None, py_vers=('py',))
Return a corresponding package name for a python module. mod: python module name dist: a linux distribution as returned by `platform.linux_distribution()[0]` pkg_map: a custom package mapping. None means autodetected based on the given dist parameter py_vers: a list of python ver...
2.759615
2.59865
1.061942
for rule in OPENSTACK_UPSTREAM_PKG_MAP: pkglist = rule(mod, dist=None) if pkglist: return pkglist[0] return mod
def module2upstream(mod)
Return a corresponding OpenStack upstream name for a python module. mod -- python module name
10.635734
8.58942
1.238236
parser = argparse.ArgumentParser(description='Python module name to' 'package name') group = parser.add_mutually_exclusive_group() group.add_argument('--dist', help='distribution style ' '(default: %(default)s)', default...
def main()
for resolving names from command line
3.701306
3.511464
1.054064
orig_page_num = self.page_num orig_page_size = self.page_size try: page_num = int(self.request.GET.get(self.page_kwarg or 'p')) if page_num < 1: page_num = orig_page_num except: page_num = orig_page_num try: ...
def get_paging(self)
Gets the paging values passed through the query string params. * "p" for "page number" and * "ps" for "page size". :returns: tuple with the page being the first part and the page size being the second part.
1.957871
1.973831
0.991914
# type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno] arg_spec = getargspec(f) args = [k for k in arg_spec.args if k != "self"] defaults = {} # type: Dict[str, Any] if arg_spec.defaults: default_args = args[-len(arg_spec.defaults):] for a, default in zip(default_args, arg_s...
def make_call_types(f, globals_d)
Make a call_types dictionary that describes what arguments to pass to f Args: f: The function to inspect for argument names (without self) globals_d: A dictionary of globals to lookup annotation definitions in
2.586753
2.78756
0.927963
# type: (Callable, Dict) -> Dict[str, Any] locals_d = {} # type: Dict[str, Any] if globals_d is None: # If not given a globals_d then we should just populate annotations with # the strings in the type comment. globals_d = {} # The current approach is to use eval, which ...
def make_annotations(f, globals_d=None)
Create an annotations dictionary from Python2 type comments http://mypy.readthedocs.io/en/latest/python2.html Args: f: The function to examine for type comments globals_d: The globals dictionary to get type idents from. If not specified then make the annotations dict contain string...
4.320149
4.36624
0.989444
if hasattr(self, 'object') and self.object: return self.object obj = super(CommonSingleObjectViewMixin, self).get_object(**kwargs) self.object = obj return obj
def get_object(self, **kwargs)
Sometimes preprocessing of a view need to happen before the object attribute has been set for a view. In this case, just return the object if it has already been set when it's called down the road since there's no need to make another query.
3.463206
2.739088
1.264365
if not hex_timestamp.startswith('0x'): hex_timestamp = '0x{0}'.format(hex_timestamp) return datetime.fromtimestamp(int(hex_timestamp, 16))
def hex_timestamp_to_datetime(hex_timestamp)
Converts hex timestamp to a datetime object. >>> hex_timestamp_to_datetime('558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> hex_timestamp_to_datetime('0x558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> datetime.fromtimestamp(0x558BBCF9) datetime.datetime(2015, 6, 25, 8, 34, 1)
2.286868
3.046268
0.750711
if isinstance(tz, string_types): tz = pytz.timezone(tz) if ignoretz: return datetime.now(tz).replace(tzinfo=None) return datetime.now(tz)
def now_by_tz(tz='US/Central', ignoretz=True)
Gets the current datetime object by timezone. :param tz: is the timezone to get the date for. tz can be passed as a string or as a timezone object. (i.e. 'US/Central' or pytz.timezone('US/Central'), etc) :param ignoretz: will ignore the timezone portion of the datetime object and tzinf...
2.363845
3.673778
0.643437
if isinstance(tz, string_types): tz = pytz.timezone(tz) dt = tz.localize(dt) dt = datetime.astimezone(dt, pytz.timezone('UTC')) if ignoretz: return dt.replace(tzinfo=None) return dt
def tz_to_utc(dt, tz, ignoretz=True)
Converts a datetime object from the specified timezone to a UTC datetime. :param tz: the timezone the datetime is currently in. tz can be passed as a string or as a timezone object. (i.e. 'US/Central' or pytz.timezone('US/Central'), etc) :param ignoretz: will ignore the timezone portion of the...
2.367538
4.419158
0.535744
if isinstance(tz, string_types): tz = pytz.timezone(tz) dt = pytz.utc.localize(dt) dt = dt.astimezone(tz) if ignoretz: return dt.replace(tzinfo=None) return dt
def utc_to_tz(dt, tz, ignoretz=True)
Converts UTC datetime object to the specific timezone. :param dt: the UTC datetime object to convert. :param tz: the timezone to convert the UTC datetime object info. tz can be passed as a string or as a timezone object. (i.e. 'US/Central' or pytz.timezone('US/Central'), etc) ...
1.939215
3.669744
0.528433
dttm = parse_datetime(dt, ignoretz=ignoretz) return None if dttm is None else dttm.date()
def parse_date(dt, ignoretz=True, as_tz=None)
:param dt: string datetime to convert into datetime object. :return: date object if the string can be parsed into a date. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_date('2011-12-30') datetime.date(2011, 12, 30) >>> parse_date('12/30/2011') ...
3.723
5.048879
0.737391
try: return parse(dt, ignoretz=ignoretz, **kwargs) except: return None
def parse_datetime(dt, ignoretz=True, **kwargs)
:param dt: string datetime to convert into datetime object. :return: datetime object if the string can be parsed into a datetime. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_datetime('2011-12-30 13:45:12 CDT') 2011-12-30 13:45:12 >>> parse_dateti...
3.167277
4.165789
0.760307
# Dummy email backend so no emails are sent. EMAIL_BACKEND_DUMMY = 'django.core.mail.backends.dummy.EmailBackend' def decorated(request, *args, **kwargs): orig_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = EMAIL_BACKEND_DUMMY response = view_func(request, *a...
def turn_emails_off(view_func)
Turns emails off so no emails will be sent.
2.482242
2.322363
1.068843
md5 = hashlib.md5() while True: data = file.read(md5.block_size) if not data: break md5.update(data) return md5.hexdigest()
def get_md5_for_file(file)
Get the md5 hash for a file. :param file: the file to get the md5 hash for
2.11818
2.631363
0.804975
with open(path, encoding=encoding) as data_file: return json.loads(data_file.read())
def get_dict_from_json_file(path, encoding='utf-8')
Gets a dict of data form a json file. :param path: the absolute path to the file :param encoding: the encoding the file is in
2.620712
3.410947
0.768324
if isinstance(value, string_types) and '\n' in value: return linebreaks_filter(value, autoescape=autoescape) return value
def linebreaks_safe(value, autoescape=True)
Adds linebreaks only for text that has a newline character.
3.281101
3.179462
1.031967
# transpose if axis<>0 if axis is not 0: x = x.T # read dimensions and n, c = x.shape # check if enough variables provided if c < 2: raise Exception( "Only " + str(c) + " variables provided. Min. 2 required.") # allocate variables r = np.ones((c, c)) ...
def kendall(x, axis=0)
Kendall' tau (Rank) Correlation Matrix (for ordinal data) Parameters ---------- x : ndarray data set axis : int, optional Variables as columns is the default (axis=0). If variables are in the rows use axis=1 Returns ------- r : ndarray Correlation Matrix (K...
3.072143
2.96873
1.034834
existing_sub_resources = self.resources.get(sub_resource.RELATIVE_PATH_TEMPLATE, defaultdict(list)) existing_sub_resources[relative_id].append(sub_resource) self.resources.update({sub_resource.RELATIVE_PATH_TEMPLATE: existing_sub_resources})
def add_sub_resource(self, relative_id, sub_resource)
Add sub resource
2.831129
2.85069
0.993138
if self.shell_name: return "{shell_name}.{resource_model}".format(shell_name=self.shell_name, resource_model=self.RESOURCE_MODEL.replace(" ", "")) else: return self.RESOURCE_MODEL
def cloudshell_model_name(self)
Return the name of the CloudShell model
3.860409
3.683756
1.047954
if ydim is 1: return ( r[1:, :1].reshape(-1, ), pval[1:, :1].reshape(-1, ), r[1:, 1:], pval[1:, 1:]) else: return ( r[ydim:, :ydim], pval[ydim:, :ydim], r[ydim:, ydim:], pval[ydim:, ydim:])
def slice_yx(r, pval, ydim=1)
slice a correlation and p-value matrix of a (y,X) dataset into a (y,x_i) vector and (x_j, x_k) matrices Parameters ---------- r : ndarray Correlation Matrix of a (y,X) dataset pval : ndarray p-values ydim : int Number of target variables y, i.e. the first ydim-th colum...
2.304677
2.335948
0.986613
'''Returns tuple with expression type and expression body''' if not is_expression(source): msg = 'Expression is not valid. Expression should be matched with regular expression: {0}'\ .format(EXPRESSION_REGEX) raise ExpressionError(msg, source) if not source.startswith('{'): ...
def parse_expression(source: str) -> ExpressionSource
Returns tuple with expression type and expression body
5.37461
4.740552
1.133752
''' Returns list of servers that have not errored in the last five minutes. If all servers have errored in the last five minutes, returns list with one item, the server that errored least recently. ''' whitelist = [] for server in self.servers: if (ser...
def _server_whitelist(self)
Returns list of servers that have not errored in the last five minutes. If all servers have errored in the last five minutes, returns list with one item, the server that errored least recently.
4.535429
2.312517
1.961252
result = GenericNetworkingResource(shell_name=shell_name, name=context.resource.name, supported_os=supported_os) result.address = context.resource.address result.family = context.resource.family result.fullname = context.resource.fullname result.attributes = dict(context.resource.attributes) ...
def create_networking_resource_from_context(shell_name, supported_os, context)
Creates an instance of Networking Resource by given context :param shell_name: Shell Name :type shell_name: str :param supported_os: list of supported OS :type supported_os: list :param context: cloudshell.shell.core.driver_context.ResourceCommandContext :type context: cloudshell.shell.core.driv...
3.609733
3.238201
1.114734
# convert to lists n = len(rho) r = list(np.abs(rho)) p = list(pval) i = list(range(n)) # check m if m > n: warnings.warn( 'm is bigger than the available correlations in rho and pval.') m = n # selected indicies selected = list() # (1) pick the...
def find_worst(rho, pval, m=1, rlim=.10, plim=.35)
Find the N "worst", i.e. insignificant/random and low, correlations Parameters ---------- rho : ndarray, list 1D array with correlation coefficients pval : ndarray, list 1D array with p-values m : int The desired number of indicies to return (How many "worst" corre...
2.762435
2.684204
1.029145
value = value.lstrip() if not value or value[0] not in _bracket_strings: return None return json.loads(value)
def _parse_array(value)
Coerce value into an list. :param str value: Value to parse. :returns: list or None if the value is not a JSON array :raises: TypeError or ValueError if value appears to be an array but can't be parsed as JSON.
5.891216
7.020317
0.839167