uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d44e3098b072492cf4dcc3e1 | train | class | class ModelChoiceIterator:
def __init__(self, field):
self.field = field
self.queryset = field.queryset
def __iter__(self):
if self.field.empty_label is not None:
yield ("", self.field.empty_label)
queryset = self.queryset.all()
# Can't use iterator() when qu... | class ModelChoiceIterator:
| def __init__(self, field):
self.field = field
self.queryset = field.queryset
def __iter__(self):
if self.field.empty_label is not None:
yield ("", self.field.empty_label)
queryset = self.queryset.all()
# Can't use iterator() when queryset uses prefetch_relate... | )
else:
orig = self.parent_instance.pk
if force_text(value) != force_text(orig):
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
return self.parent_instance
def has_changed(self, initial, data):
return False
class ModelChoi... | 64 | 64 | 159 | 5 | 58 | zalmoxis/django | django/forms/models.py | Python | ModelChoiceIterator | ModelChoiceIterator | 1,100 | 1,119 | 1,100 | 1,100 | 7fa7dd98713adf4ca7212e2dd5a24781d4109d89 | bigcode/the-stack | train |
2785169d9ae05e3100c35f77 | train | class | class ModelFormOptions:
def __init__(self, options=None):
self.model = getattr(options, 'model', None)
self.fields = getattr(options, 'fields', None)
self.exclude = getattr(options, 'exclude', None)
self.widgets = getattr(options, 'widgets', None)
self.localized_fields = geta... | class ModelFormOptions:
| def __init__(self, options=None):
self.model = getattr(options, 'model', None)
self.fields = getattr(options, 'fields', None)
self.exclude = getattr(options, 'exclude', None)
self.widgets = getattr(options, 'widgets', None)
self.localized_fields = getattr(options, 'localized_... | OrderedDict(field_list)
if fields:
field_dict = OrderedDict(
[(f, field_dict.get(f)) for f in fields
if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored)]
)
return field_dict
class ModelFormOptions:
| 64 | 64 | 133 | 5 | 58 | zalmoxis/django | django/forms/models.py | Python | ModelFormOptions | ModelFormOptions | 187 | 197 | 187 | 187 | ce36a94eb27fc39136a297ec1d670b82ce830fce | bigcode/the-stack | train |
5989fce9bd15de9c6b109f82 | train | function | def inlineformset_factory(parent_model, model, form=ModelForm,
formset=BaseInlineFormSet, fk_name=None,
fields=None, exclude=None, extra=3, can_order=False,
can_delete=True, max_num=None, formfield_callback=None,
wid... | def inlineformset_factory(parent_model, model, form=ModelForm,
formset=BaseInlineFormSet, fk_name=None,
fields=None, exclude=None, extra=3, can_order=False,
can_delete=True, max_num=None, formfield_callback=None,
wid... | """
Returns an ``InlineFormSet`` for the given kwargs.
You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
to ``parent_model``.
"""
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
# enforce a max_num=1 when the foreign key to the parent model is unique.
... | ._meta.label,
)
)
return fk
def inlineformset_factory(parent_model, model, form=ModelForm,
formset=BaseInlineFormSet, fk_name=None,
fields=None, exclude=None, extra=3, can_order=False,
can_delete=True, max_num=... | 107 | 107 | 359 | 95 | 11 | zalmoxis/django | django/forms/models.py | Python | inlineformset_factory | inlineformset_factory | 1,015 | 1,054 | 1,015 | 1,021 | cb6517aab5c2100f38eaf46561e21ebb8027dea5 | bigcode/the-stack | train |
596ca87bb9a287da81645de5 | train | function | def fields_for_model(model, fields=None, exclude=None, widgets=None,
formfield_callback=None, localized_fields=None,
labels=None, help_texts=None, error_messages=None,
field_classes=None):
"""
Returns a ``OrderedDict`` containing form fields for the... | def fields_for_model(model, fields=None, exclude=None, widgets=None,
formfield_callback=None, localized_fields=None,
labels=None, help_texts=None, error_messages=None,
field_classes=None):
| """
Returns a ``OrderedDict`` containing form fields for the given model.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned fields.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded fr... | _to_dict(instance, fields=None, exclude=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclud... | 240 | 240 | 801 | 43 | 196 | zalmoxis/django | django/forms/models.py | Python | fields_for_model | fields_for_model | 97 | 184 | 97 | 100 | 949cfb15068c7fe62cb8a154095c54968eb1a94e | bigcode/the-stack | train |
e18cff6bc63765c6d1a5a342 | train | function | def modelform_defines_fields(form_class):
return (form_class is not None and (
hasattr(form_class, '_meta') and
(form_class._meta.fields is not None or
form_class._meta.exclude is not None)
))
| def modelform_defines_fields(form_class):
| return (form_class is not None and (
hasattr(form_class, '_meta') and
(form_class._meta.fields is not None or
form_class._meta.exclude is not None)
))
| = []
if len(initial) != len(data):
return True
initial_set = set(force_text(value) for value in self.prepare_value(initial))
data_set = set(force_text(value) for value in data)
return data_set != initial_set
def modelform_defines_fields(form_class):
| 64 | 64 | 54 | 10 | 53 | zalmoxis/django | django/forms/models.py | Python | modelform_defines_fields | modelform_defines_fields | 1,322 | 1,327 | 1,322 | 1,322 | add34471de4bb67c4fb9c34ab2ee70d86642a923 | bigcode/the-stack | train |
a53f978844a7998723c4440f | train | function | def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet, extra=1, can_delete=False,
can_order=False, max_num=None, fields=None, exclude=None,
widgets=None, validate_max=False, localized_fields=None,
... | def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet, extra=1, can_delete=False,
can_order=False, max_num=None, fields=None, exclude=None,
widgets=None, validate_max=False, localized_fields=None,
... | """
Returns a FormSet class for the given Django model class.
"""
meta = getattr(form, 'Meta', None)
if (getattr(meta, 'fields', fields) is None and
getattr(meta, 'exclude', exclude) is None):
raise ImproperlyConfigured(
"Calling modelformset_factory without defining ... | , index)
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet, extra=1, can_delete=False,
can_order=False, max_num=None, fields=None, exclude=None,
widgets=None, validate_max=False, localized_fields=N... | 91 | 91 | 305 | 88 | 3 | zalmoxis/django | django/forms/models.py | Python | modelformset_factory | modelformset_factory | 827 | 853 | 827 | 832 | e7ab8befd7d03f40d4e24c671962120f68073169 | bigcode/the-stack | train |
7d4f4323f73dee705a68fc58 | train | class | class BaseModelForm(BaseForm):
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, instance=None, use_required_attribute=None):
opts = self._meta
if opts.model is None... | class BaseModelForm(BaseForm):
| def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, instance=None, use_required_attribute=None):
opts = self._meta
if opts.model is None:
raise ValueError(... | "
"needs updating." % name
)
if opts.fields == ALL_FIELDS:
# Sentinel for fields_for_model to indicate "get the list of
# fields from the model"
opts.fields = None
fields = fields_for_model(opts.model, opts.fi... | 256 | 256 | 1,565 | 7 | 248 | zalmoxis/django | django/forms/models.py | Python | BaseModelForm | BaseModelForm | 271 | 456 | 271 | 271 | 0a00076c71ba2989c9edb6930fdd26ff35f598ca | bigcode/the-stack | train |
57a45a3c37f3a2f483c43039 | train | function | def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
"""
Finds and returns the ForeignKey from model to parent if there is one
(returns None if can_fail is True and no such field exists). If fk_name is
provided, assume it is the name of the ForeignKey field. Unless can_fail is
Tr... | def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
| """
Finds and returns the ForeignKey from model to parent if there is one
(returns None if can_fail is True and no such field exists). If fk_name is
provided, assume it is the name of the ForeignKey field. Unless can_fail is
True, an exception is raised if there is no ForeignKey from model to
pa... | .adding:
if kwargs.get('to_field') is not None:
to_field = self.instance._meta.get_field(kwargs['to_field'])
else:
to_field = self.instance._meta.pk
if to_field.has_default():
setattr(self.instance, to_field.attname, None)
form... | 144 | 144 | 482 | 19 | 125 | zalmoxis/django | django/forms/models.py | Python | _get_foreign_key | _get_foreign_key | 960 | 1,012 | 960 | 960 | f544da0e866602863492d8bc8df1c8dbb63acb2b | bigcode/the-stack | train |
83f74dadc72e8bbd80e1011b | train | class | class InlineForeignKeyField(Field):
"""
A basic integer field that deals with validating the given value to a
given parent instance in an inline.
"""
widget = HiddenInput
default_error_messages = {
'invalid_choice': _('The inline foreign key did not match the parent instance primary key.... | class InlineForeignKeyField(Field):
| """
A basic integer field that deals with validating the given value to a
given parent instance in an inline.
"""
widget = HiddenInput
default_error_messages = {
'invalid_choice': _('The inline foreign key did not match the parent instance primary key.'),
}
def __init__(self, pa... | validate_min': validate_min,
'validate_max': validate_max,
'localized_fields': localized_fields,
'labels': labels,
'help_texts': help_texts,
'error_messages': error_messages,
'field_classes': field_classes,
}
FormSet = modelformset_factory(model, **kwargs)
For... | 95 | 95 | 319 | 7 | 87 | zalmoxis/django | django/forms/models.py | Python | InlineForeignKeyField | InlineForeignKeyField | 1,059 | 1,097 | 1,059 | 1,059 | c7378a7d891474f990f0a67e61c0af9bacf8119d | bigcode/the-stack | train |
9e566301bdce5798e4d67548 | train | class | class BaseModelFormSet(BaseFormSet):
"""
A ``FormSet`` for editing a queryset and/or adding new objects to it.
"""
model = None
# Set of fields that must be unique among forms of this set.
unique_fields = set()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
... | class BaseModelFormSet(BaseFormSet):
| """
A ``FormSet`` for editing a queryset and/or adding new objects to it.
"""
model = None
# Set of fields that must be unique among forms of this set.
unique_fields = set()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
queryset=None, **kwargs):
... | if field_classes is not None:
attrs['field_classes'] = field_classes
# If parent form class already has an inner Meta, the Meta we're
# creating needs to inherit from the parent's inner meta.
bases = (form.Meta,) if hasattr(form, 'Meta') else ()
Meta = type('Meta', bases, attrs)
if formfie... | 256 | 256 | 2,532 | 9 | 247 | zalmoxis/django | django/forms/models.py | Python | BaseModelFormSet | BaseModelFormSet | 546 | 824 | 546 | 546 | bd1cae278d75e70b3b8e79360b260da2207d3c68 | bigcode/the-stack | train |
735953635b7e58c55adea8bc | train | class | class ModelMultipleChoiceField(ModelChoiceField):
"""A MultipleChoiceField whose choices are a model QuerySet."""
widget = SelectMultiple
hidden_widget = MultipleHiddenInput
default_error_messages = {
'list': _('Enter a list of values.'),
'invalid_choice': _('Select a valid choice. %(val... | class ModelMultipleChoiceField(ModelChoiceField):
| """A MultipleChoiceField whose choices are a model QuerySet."""
widget = SelectMultiple
hidden_widget = MultipleHiddenInput
default_error_messages = {
'list': _('Enter a list of values.'),
'invalid_choice': _('Select a valid choice. %(value)s is not one of the'
... | choices = property(_get_choices, ChoiceField._set_choices)
def prepare_value(self, value):
if hasattr(value, '_meta'):
if self.to_field_name:
return value.serializable_value(self.to_field_name)
else:
return value.pk
return super(ModelChoiceFi... | 226 | 226 | 754 | 9 | 217 | zalmoxis/django | django/forms/models.py | Python | ModelMultipleChoiceField | ModelMultipleChoiceField | 1,229 | 1,319 | 1,229 | 1,229 | 211879c57e987080ad6da29e090e8416eee76c41 | bigcode/the-stack | train |
2e2a20d615baa5b4c9a240fb | train | function | def construct_instance(form, instance, fields=None, exclude=None):
"""
Constructs and returns a model instance from the bound ``form``'s
``cleaned_data``, but does not save the returned instance to the
database.
"""
from django.db import models
opts = instance._meta
cleaned_data = form.... | def construct_instance(form, instance, fields=None, exclude=None):
| """
Constructs and returns a model instance from the bound ``form``'s
``cleaned_data``, but does not save the returned instance to the
database.
"""
from django.db import models
opts = instance._meta
cleaned_data = form.cleaned_data
file_field_list = []
for f in opts.fields:
... | ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
'ModelChoiceField', 'ModelMultipleChoiceField', 'ALL_FIELDS',
'BaseModelFormSet', 'modelformset_factory', 'BaseInlineFormSet',
'inlineformset_factory', 'modelform_factory',
)
ALL_FIELDS = '__all__'
def construct_instance(form, instance, fiel... | 88 | 88 | 296 | 13 | 75 | zalmoxis/django | django/forms/models.py | Python | construct_instance | construct_instance | 33 | 67 | 33 | 33 | 356096b95a41e762b64f6679b098021368bd1654 | bigcode/the-stack | train |
92e13c46f6605db04756104d | train | class | class ModelChoiceField(ChoiceField):
"""A ChoiceField whose choices are a model QuerySet."""
# This class is a subclass of ChoiceField for purity, but it doesn't
# actually use any of ChoiceField's implementation.
default_error_messages = {
'invalid_choice': _('Select a valid choice. That choice... | class ModelChoiceField(ChoiceField):
| """A ChoiceField whose choices are a model QuerySet."""
# This class is a subclass of ChoiceField for purity, but it doesn't
# actually use any of ChoiceField's implementation.
default_error_messages = {
'invalid_choice': _('Select a valid choice. That choice is not one of'
... |
# ensure the we compare the values as equal types.
if self.to_field:
orig = getattr(self.parent_instance, self.to_field)
else:
orig = self.parent_instance.pk
if force_text(value) != force_text(orig):
raise ValidationError(self.error_messages['invalid_... | 256 | 256 | 900 | 8 | 248 | zalmoxis/django | django/forms/models.py | Python | ModelChoiceField | ModelChoiceField | 1,122 | 1,226 | 1,122 | 1,122 | 8c85404de2dbe9885abfab06df0d1018e1f24657 | bigcode/the-stack | train |
c4616c4a2ac718779d5954e7 | train | function | def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
formfield_callback=None, widgets=None, localized_fields=None,
labels=None, help_texts=None, error_messages=None,
field_classes=None):
"""
Returns a ModelForm containing form ... | def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
formfield_callback=None, widgets=None, localized_fields=None,
labels=None, help_texts=None, error_messages=None,
field_classes=None):
| """
Returns a ModelForm containing form fields for the given model.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned fields. If omitted or '__all__',
all fields will be used.
``exclude`` is an optional list of field names. If pr... | if self.errors:
raise ValueError(
"The %s could not be %s because the data didn't validate." % (
self.instance._meta.object_name,
'created' if self.instance._state.adding else 'changed',
)
)
if commit:
... | 210 | 210 | 702 | 49 | 160 | zalmoxis/django | django/forms/models.py | Python | modelform_factory | modelform_factory | 463 | 541 | 463 | 466 | f639b2407076c7227d4057a083eb4fc4ebd4fe41 | bigcode/the-stack | train |
413af9065df013254949a3a0 | train | class | class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
pass
| class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
| pass
| not committing, add a method to the form to allow deferred
# saving of m2m data.
self.save_m2m = self._save_m2m
return self.instance
save.alters_data = True
class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
| 64 | 64 | 18 | 15 | 48 | zalmoxis/django | django/forms/models.py | Python | ModelForm | ModelForm | 459 | 460 | 459 | 459 | ae2b1686baa8e702adc5fe5c389ef9ba77281738 | bigcode/the-stack | train |
9f662a20b751e7cfb0a4a26f | train | class | class BaseInlineFormSet(BaseModelFormSet):
"""A formset for child objects related to a parent."""
def __init__(self, data=None, files=None, instance=None,
save_as_new=False, prefix=None, queryset=None, **kwargs):
if instance is None:
self.instance = self.fk.remote_field.mode... | class BaseInlineFormSet(BaseModelFormSet):
| """A formset for child objects related to a parent."""
def __init__(self, data=None, files=None, instance=None,
save_as_new=False, prefix=None, queryset=None, **kwargs):
if instance is None:
self.instance = self.fk.remote_field.model()
else:
self.instance... | help_texts=None, error_messages=None,
min_num=None, validate_min=False, field_classes=None):
"""
Returns a FormSet class for the given Django model class.
"""
meta = getattr(form, 'Meta', None)
if (getattr(meta, 'fields', fields) is None and
getattr(meta, 'exclu... | 256 | 256 | 1,023 | 10 | 246 | zalmoxis/django | django/forms/models.py | Python | BaseInlineFormSet | BaseInlineFormSet | 858 | 957 | 858 | 858 | 0c731695a789b456378faaf908fad36a54b51b24 | bigcode/the-stack | train |
7caa054ab1b3728162a443bc | train | class | class ModelFormMetaclass(DeclarativeFieldsMetaclass):
def __new__(mcs, name, bases, attrs):
base_formfield_callback = None
for b in bases:
if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'):
base_formfield_callback = b.Meta.formfield_callback
... | class ModelFormMetaclass(DeclarativeFieldsMetaclass):
| def __new__(mcs, name, bases, attrs):
base_formfield_callback = None
for b in bases:
if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'):
base_formfield_callback = b.Meta.formfield_callback
break
formfield_callback = attrs.pop('formfie... | (f)) for f in fields
if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored)]
)
return field_dict
class ModelFormOptions:
def __init__(self, options=None):
self.model = getattr(options, 'model', None)
self.fields = getattr(options, 'fields', None)
... | 181 | 181 | 606 | 12 | 169 | zalmoxis/django | django/forms/models.py | Python | ModelFormMetaclass | ModelFormMetaclass | 200 | 268 | 200 | 200 | ba2978d348eeca8d58ea9c387767362d15e13403 | bigcode/the-stack | train |
1a632f663524e489ed870191 | train | function | def model_to_dict(instance, fields=None, exclude=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
... | def model_to_dict(instance, fields=None, exclude=None):
| """
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If prov... | ):
file_field_list.append(f)
else:
f.save_form_data(instance, cleaned_data[f.name])
for f in file_field_list:
f.save_form_data(instance, cleaned_data[f.name])
return instance
# ModelForms #################################################################
def model_to_d... | 64 | 64 | 199 | 12 | 52 | zalmoxis/django | django/forms/models.py | Python | model_to_dict | model_to_dict | 72 | 94 | 72 | 72 | c62b8200d8ddcb7b99c708f904d92e592a4873e5 | bigcode/the-stack | train |
e1849dc98206f81900fd7c5f | train | function | def lcs(X, Y):
# find the length of the strings
m = len(X)
n = len(Y)
# declaring the array for storing the dp values
L = [[None]*(n + 1) for i in range(m + 1)]
"""Following steps build L[m + 1][n + 1] in bottom up fashion
Note: L[i][j] contains length of LCS of X[0..i-1]
a... | def lcs(X, Y):
# find the length of the strings
| m = len(X)
n = len(Y)
# declaring the array for storing the dp values
L = [[None]*(n + 1) for i in range(m + 1)]
"""Following steps build L[m + 1][n + 1] in bottom up fashion
Note: L[i][j] contains length of LCS of X[0..i-1]
and Y[0..j-1]"""
for i in range(m + 1):
fo... | def lcs(X, Y):
# find the length of the strings
| 17 | 87 | 293 | 17 | 0 | MubeenKodvavi/CS302_Algo_Project | algorithms/LongestCommonSubSequence.py | Python | lcs | lcs | 1 | 26 | 1 | 2 | dc622252be98c9c4ca30e4f7b8f8477ccc0c0c9f | bigcode/the-stack | train |
7f05223156c4a2fc03d22ad1 | train | function | def _run(runner, command, output, accepted_returns=None):
accepted_returns = accepted_returns or [0, ]
output.info("Running: %s" % command)
if runner(command, True) not in accepted_returns:
raise ConanException("Command '%s' failed" % command)
| def _run(runner, command, output, accepted_returns=None):
| accepted_returns = accepted_returns or [0, ]
output.info("Running: %s" % command)
if runner(command, True) not in accepted_returns:
raise ConanException("Command '%s' failed" % command)
| , arch_names):
if arch_names is None:
arch_names = {"x86": "i586"}
if arch in arch_names:
return "%s.%s" % (arch_names[arch], package)
return package
def _run(runner, command, output, accepted_returns=None):
| 64 | 64 | 63 | 14 | 49 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | _run | _run | 387 | 391 | 387 | 387 | 7a70e921b0683cf3387f074362ca59e28020696e | bigcode/the-stack | train |
fa483f0204add93e5e837460 | train | class | class YumTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("YumTool::add_repository not implemented")
def update(self):
_run(self._runner, "%syum check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def inst... | class YumTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("YumTool::add_repository not implemented")
def update(self):
_run(self._runner, "%syum check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def install(self, package_name):
... | "ppc64le": "ppc64el",
"armv7": "arm",
"armv7hf": "armhf",
"armv8": "arm64",
"s390x": "s390x"}
if arch in arch_names:
return "%s:%s" % (package, arch_names[arch])
retur... | 87 | 87 | 291 | 6 | 80 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | YumTool | YumTool | 234 | 262 | 234 | 234 | d1cf82991913e413f9c952236c9a4354bc3a92c6 | bigcode/the-stack | train |
5f6c2b5ff40ace85d19e1f83 | train | class | class PkgUtilTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PkgUtilTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkgutil --catalog" % self._sudo_str, output=self._output)
def install(self, package_name):
_... | class PkgUtilTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("PkgUtilTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkgutil --catalog" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spkgutil ... | -y %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("pkg info %s" % package_name, None)
return exit_code == 0
class PkgUtilTool(BaseTool):
| 64 | 64 | 148 | 8 | 55 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | PkgUtilTool | PkgUtilTool | 309 | 322 | 309 | 309 | 9c0bba69eac696f40470c94d78d22e86c2e5af3e | bigcode/the-stack | train |
4c2742976bf23a0e8bf32ecd | train | class | class SystemPackageTool(object):
def __init__(self, runner=None, os_info=None, tool=None, recommends=False, output=None, conanfile=None):
output = output if output else conanfile.output if conanfile else None
self._output = default_output(output, 'conans.client.tools.system_pm.SystemPackageTool')
... | class SystemPackageTool(object):
| def __init__(self, runner=None, os_info=None, tool=None, recommends=False, output=None, conanfile=None):
output = output if output else conanfile.output if conanfile else None
self._output = default_output(output, 'conans.client.tools.system_pm.SystemPackageTool')
os_info = os_info or OSInfo... | import os
import sys
from conans.client.runner import ConanRunner
from conans.client.tools.oss import OSInfo, cross_building, get_cross_building_settings
from conans.client.tools.files import which
from conans.errors import ConanException
from conans.util.env_reader import get_env
from conans.util.fallbacks import def... | 80 | 256 | 1,344 | 6 | 73 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | SystemPackageTool | SystemPackageTool | 12 | 164 | 12 | 13 | d54a626f24c82254ac991154e3835d68eed5dee6 | bigcode/the-stack | train |
942c50f16e6a45ee0253b882 | train | class | class DnfTool(YumTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("DnfTool::add_repository not implemented")
def update(self):
_run(self._runner, "%sdnf check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def insta... | class DnfTool(YumTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("DnfTool::add_repository not implemented")
def update(self):
_run(self._runner, "%sdnf check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def install(self, package_name):
... | ": "armv7hl",
"armv8": "aarch64",
"s390x": "s390x"}
if arch in arch_names:
return "%s.%s" % (package, arch_names[arch])
return package
class DnfTool(YumTool):
| 64 | 64 | 114 | 8 | 55 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | DnfTool | DnfTool | 265 | 275 | 265 | 265 | f1ec694a8c77d674efd58c885e2533f6945dfe30 | bigcode/the-stack | train |
15194fb2b0baa959137b722a | train | class | class NullTool(BaseTool):
def add_repository(self, repository, repo_key=None):
pass
def update(self):
pass
def install(self, package_name):
self._output.warn("Only available for linux with apt-get, yum, or pacman or OSX with brew or"
" FreeBSD with pkg or ... | class NullTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
pass
def update(self):
pass
def install(self, package_name):
self._output.warn("Only available for linux with apt-get, yum, or pacman or OSX with brew or"
" FreeBSD with pkg or Solaris with pkgutil")
... | :param arch: Host arch from Conanfile.settings
:param arch_names: Dictionary with suffix/prefix names e.g {"x86_64": "amd64"}
:return: Package name for Tool e.g. libusb-dev:i386
"""
return package
class NullTool(BaseTool):
| 64 | 64 | 86 | 6 | 57 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | NullTool | NullTool | 182 | 194 | 182 | 182 | 22ec54f70b952642fd5d731744ad41a17f89cc37 | bigcode/the-stack | train |
60222f8a1107d765508c5891 | train | class | class PkgTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PkgTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkg update" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runne... | class PkgTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("PkgTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkg update" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spkg install -y %s" ... | "brew install %s" % package_name, output=self._output)
def installed(self, package_name):
exit_code = self._runner('test -n "$(brew ls --versions %s)"' % package_name, None)
return exit_code == 0
class PkgTool(BaseTool):
| 64 | 64 | 135 | 7 | 56 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | PkgTool | PkgTool | 293 | 306 | 293 | 293 | 7f248abaa787965b393f4e5ec22a48dc7190dc97 | bigcode/the-stack | train |
ed4e8d9b4eeffc0bbffdf7e5 | train | class | class AptTool(BaseTool):
def add_repository(self, repository, repo_key=None):
_run(self._runner, "%sapt-add-repository %s" % (self._sudo_str, repository),
output=self._output)
if repo_key:
_run(self._runner, "wget -qO - %s | %sapt-key add -" % (repo_key, self._sudo_str),
... | class AptTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
_run(self._runner, "%sapt-add-repository %s" % (self._sudo_str, repository),
output=self._output)
if repo_key:
_run(self._runner, "wget -qO - %s | %sapt-key add -" % (repo_key, self._sudo_str),
output=self... | : Package name for Tool e.g. libusb-dev:i386
"""
return package
class NullTool(BaseTool):
def add_repository(self, repository, repo_key=None):
pass
def update(self):
pass
def install(self, package_name):
self._output.warn("Only available for linux with apt-get, yu... | 112 | 112 | 374 | 6 | 105 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | AptTool | AptTool | 197 | 231 | 197 | 197 | a170b9837fe6c593379eb306a4c70edbd658d3de | bigcode/the-stack | train |
a25b897b526e376fbe50f5fb | train | class | class PacManTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PacManTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spacman -Syyu --noconfirm" % self._sudo_str, output=self._output)
def install(self, package_name):
... | class PacManTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("PacManTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spacman -Syyu --noconfirm" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spa... | =self._output)
def installed(self, package_name):
exit_code = self._runner('choco search --local-only --exact %s | '
'findstr /c:"1 packages installed."' % package_name, None)
return exit_code == 0
class PacManTool(BaseTool):
| 64 | 64 | 210 | 7 | 56 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | PacManTool | PacManTool | 341 | 361 | 341 | 341 | f42689689c6b99ee34ec3d9b7b21e57aaa683a71 | bigcode/the-stack | train |
ee1fb7b27681fbc927c310a8 | train | class | class BaseTool(object):
def __init__(self, output=None):
self._output = default_output(output, 'conans.client.tools.system_pm.BaseTool')
def get_package_name(self, package, arch, arch_names):
""" Retrieve package name to installed according the target arch.
:param package: Regular pack... | class BaseTool(object):
| def __init__(self, output=None):
self._output = default_output(output, 'conans.client.tools.system_pm.BaseTool')
def get_package_name(self, package, arch, arch_names):
""" Retrieve package name to installed according the target arch.
:param package: Regular package name e.g libusb-dev
... | (packages) == 1:
return self._tool.install(packages[0])
for pkg in packages:
try:
return self._tool.install(pkg)
except ConanException:
pass
raise ConanException("Could not install any of %s" % packages)
class BaseTool(object):
| 64 | 64 | 133 | 5 | 59 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | BaseTool | BaseTool | 167 | 179 | 167 | 167 | 889cd37eb25e175485cbaeaca6b8a0cbccfb3b52 | bigcode/the-stack | train |
9477063886fe503cbc8f5a6a | train | class | class ChocolateyTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("ChocolateyTool::add_repository not implemented")
def update(self):
_run(self._runner, "choco outdated", output=self._output)
def install(self, package_name):
_run(self._runner... | class ChocolateyTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("ChocolateyTool::add_repository not implemented")
def update(self):
_run(self._runner, "choco outdated", output=self._output)
def install(self, package_name):
_run(self._runner, "choco install --yes %s" % pac... | (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner('test -n "`pkgutil --list %s`"' % package_name, None)
return exit_code == 0
class ChocolateyTool(BaseTool):
| 64 | 64 | 141 | 7 | 56 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | ChocolateyTool | ChocolateyTool | 325 | 338 | 325 | 325 | 7a9c5ddda61aa83d3c09dd892ce0fb69ba76b115 | bigcode/the-stack | train |
c6c494e0653e8d5ba81fb425 | train | class | class ZypperTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("ZypperTool::add_repository not implemented")
def update(self):
_run(self._runner, "%szypper --non-interactive ref" % self._sudo_str, output=self._output)
def install(self, package_name):
... | class ZypperTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("ZypperTool::add_repository not implemented")
def update(self):
_run(self._runner, "%szypper --non-interactive ref" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "... | _name(self, package, arch, arch_names):
if arch_names is None:
arch_names = {"x86": "lib32"}
if arch in arch_names:
return "%s-%s" % (arch_names[arch], package)
return package
class ZypperTool(BaseTool):
| 64 | 64 | 207 | 8 | 55 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | ZypperTool | ZypperTool | 364 | 384 | 364 | 364 | ad2cf3d33e25a1bbe550a72a199be6f870247ca8 | bigcode/the-stack | train |
f89e9b262aff92ebd97a3bd5 | train | class | class BrewTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("BrewTool::add_repository not implemented")
def update(self):
_run(self._runner, "brew update", output=self._output)
def install(self, package_name):
_run(self._runner, "brew install... | class BrewTool(BaseTool):
| def add_repository(self, repository, repo_key=None):
raise ConanException("BrewTool::add_repository not implemented")
def update(self):
_run(self._runner, "brew update", output=self._output)
def install(self, package_name):
_run(self._runner, "brew install %s" % package_name, outpu... | ._sudo_str, accepted_returns=[0, 100],
output=self._output)
def install(self, package_name):
_run(self._runner, "%sdnf install -y %s" % (self._sudo_str, package_name),
output=self._output)
class BrewTool(BaseTool):
| 64 | 64 | 125 | 6 | 58 | akemimadoka/conan | conans/client/tools/system_pm.py | Python | BrewTool | BrewTool | 278 | 290 | 278 | 278 | 38fad68595a85298ec58600bf444f9d0f8f9ef7e | bigcode/the-stack | train |
9d17c00a1cae7cb9b7ad227d | train | function | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Pilight Binary Sensor."""
disarm = config.get(CONF_DISARM_AFTER_TRIGGER)
if disarm:
add_entities([PilightTriggerSensor(
hass=hass,
name=config.get(CONF_NAME),
variable=config.get(CONF_V... | def setup_platform(hass, config, add_entities, discovery_info=None):
| """Set up Pilight Binary Sensor."""
disarm = config.get(CONF_DISARM_AFTER_TRIGGER)
if disarm:
add_entities([PilightTriggerSensor(
hass=hass,
name=config.get(CONF_NAME),
variable=config.get(CONF_VARIABLE),
payload=config.get(CONF_PAYLOAD),
o... | (
cv.positive_int, cv.small_float, cv.string),
vol.Optional(CONF_DISARM_AFTER_TRIGGER, default=False): cv.boolean,
vol.Optional(CONF_RESET_DELAY_SEC, default=30): cv.positive_int
})
def setup_platform(hass, config, add_entities, discovery_info=None):
| 64 | 64 | 186 | 15 | 49 | kdschlosser/home-assistant | homeassistant/components/pilight/binary_sensor.py | Python | setup_platform | setup_platform | 49 | 70 | 49 | 49 | 154f7013d54dedce92e91bafd4d9e4e76d999c74 | bigcode/the-stack | train |
3159a382b76e27f7d383d9ae | train | class | class PilightTriggerSensor(BinarySensorDevice):
"""Representation of a binary sensor that can be updated using Pilight."""
def __init__(
self,
hass,
name,
variable,
payload,
on_value,
off_value,
rst_dly_sec=30):
... | class PilightTriggerSensor(BinarySensorDevice):
| """Representation of a binary sensor that can be updated using Pilight."""
def __init__(
self,
hass,
name,
variable,
payload,
on_value,
off_value,
rst_dly_sec=30):
"""Initialize the sensor."""
self._... | """
# Check if received code matches defined playoad
# True if payload is contained in received code dict
payload_ok = True
for key in self._payload:
if key not in call.data:
payload_ok = False
continue
if self._payload[key]... | 140 | 140 | 469 | 9 | 131 | kdschlosser/home-assistant | homeassistant/components/pilight/binary_sensor.py | Python | PilightTriggerSensor | PilightTriggerSensor | 122 | 190 | 122 | 122 | 6fa131d1252bbaa2dfdb99ae8c9fc4a26b25f3e5 | bigcode/the-stack | train |
dc981c56931249fcb75e1e50 | train | class | class PilightBinarySensor(BinarySensorDevice):
"""Representation of a binary sensor that can be updated using Pilight."""
def __init__(self, hass, name, variable, payload, on_value, off_value):
"""Initialize the sensor."""
self._state = False
self._hass = hass
self._name = name
... | class PilightBinarySensor(BinarySensorDevice):
| """Representation of a binary sensor that can be updated using Pilight."""
def __init__(self, hass, name, variable, payload, on_value, off_value):
"""Initialize the sensor."""
self._state = False
self._hass = hass
self._name = name
self._variable = variable
self.... | off_value=config.get(CONF_PAYLOAD_OFF),
rst_dly_sec=config.get(CONF_RESET_DELAY_SEC),
)])
else:
add_entities([PilightBinarySensor(
hass=hass,
name=config.get(CONF_NAME),
variable=config.get(CONF_VARIABLE),
payload=config.get(CONF_PAYLOAD),... | 102 | 102 | 341 | 9 | 93 | kdschlosser/home-assistant | homeassistant/components/pilight/binary_sensor.py | Python | PilightBinarySensor | PilightBinarySensor | 73 | 119 | 73 | 73 | 48f5749bc78d84bf6e2f666e2f6f201d7df9c0cd | bigcode/the-stack | train |
8773ac6a9cca1d6cae1de6e5 | train | class | class PandaPlayInsertTrayPlusPickPlaceXYZState(PandaPlayGeneric):
# Same as PandaPlayInsertTrayXYZState, but with added Pick and Place main task
#
# obs space is 65, act space is 4
# obs indices:
# - pos: 0:3
# - vel: 3:6
# - grip_pos: 6:8
# -... | class PandaPlayInsertTrayPlusPickPlaceXYZState(PandaPlayGeneric):
# Same as PandaPlayInsertTrayXYZState, but with added Pick and Place main task
#
# obs space is 65, act space is 4
# obs indices:
# - pos: 0:3
# - vel: 3:6
# - grip_pos: 6:8
# -... | def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='pick_and_place_01', force_pb_direct=True, **kwargs):
super().__init__('None', False, dense_reward, max_real_time=max_real_time, n_substeps=n_substeps,
action_mu... | , action_multiplier, main_task,
gripper_control_method='dp', grip_multiplier=0.25)
class PandaPlayInsertTrayPlusPickPlaceXYZState(PandaPlayGeneric):
# Same as PandaPlayInsertTrayXYZState, but with added Pick and Place main task
#
# obs space is 65, act space is 4
# obs indices:
... | 256 | 256 | 1,316 | 234 | 22 | utiasSTARS/manipulator_learning | manipulator_learning/sim/envs/panda_play.py | Python | PandaPlayInsertTrayPlusPickPlaceXYZState | PandaPlayInsertTrayPlusPickPlaceXYZState | 447 | 536 | 447 | 460 | a4cbd7aa699d3992e43b44f7fc0822cb6584aa56 | bigcode/the-stack | train |
92263857096a764215ceca2e | train | class | class PandaPlayInsertTrayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# obs indices:
# - pos: 0:3
# - vel: 3:6
# - grip_pos: 6:8
# - prev_grip_pos: 8:12
# - obj_pos: 12:26
# - obj_vel: 26:38
# - ob... | class PandaPlayInsertTrayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# obs indices:
# - pos: 0:3
# - vel: 3:6
# - grip_pos: 6:8
# - prev_grip_pos: 8:12
# - obj_pos: 12:26
# - obj_vel: 26:38
# - ob... | def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='insert', force_pb_direct=True, **kwargs):
# main_task='unstack_stack_0', force_pb_direct=True, **kwargs):
super().__init__('None', False, dense_reward, max_real_time=ma... | **kwargs)
class PandaPlayInsertTrayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# obs indices:
# - pos: 0:3
# - vel: 3:6
# - grip_pos: 6:8
# - prev_grip_pos: 8:12
# - obj_pos: 12:26
# - ... | 176 | 176 | 588 | 172 | 4 | utiasSTARS/manipulator_learning | manipulator_learning/sim/envs/panda_play.py | Python | PandaPlayInsertTrayXYZState | PandaPlayInsertTrayXYZState | 404 | 437 | 404 | 415 | 841f0c1912773461e58859f2a3f889332e300559 | bigcode/the-stack | train |
c80e701c35294ee9f44bb977 | train | class | class PandaPlayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# n_substeps of 5 plus action multiplier of .002 means action mag of 1.0 moves desired position 2mm*5 = 1cm
def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='... | class PandaPlayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# n_substeps of 5 plus action multiplier of .002 means action mag of 1.0 moves desired position 2mm*5 = 1cm
| def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='stack_01', force_pb_direct=True, **kwargs):
super().__init__('None', False, dense_reward, max_real_time=max_real_time, n_substeps=n_substeps,
action_multiplier=... | return reward, done_success, done_failure
class PandaPlayXYZState(PandaPlayGeneric):
# obs space is 59, act space is 4
# n_substeps of 5 plus action multiplier of .002 means action mag of 1.0 moves desired position 2mm*5 = 1cm
| 69 | 69 | 232 | 59 | 9 | utiasSTARS/manipulator_learning | manipulator_learning/sim/envs/panda_play.py | Python | PandaPlayXYZState | PandaPlayXYZState | 390 | 401 | 390 | 392 | 5b7c0e6f3f82c0ee6cb3ce6095ddaba4b191fc5c | bigcode/the-stack | train |
e720b32e59a76928bbeb6ea3 | train | class | class PandaPlayGeneric(ManipulatorEnv):
VALID_AUX_TASKS = ['open_action',
'close_action',
'stack_0', 'stack_1',
'insert', 'insert_0', 'insert_1',
'bring', 'bring_0', 'bring_1',
'lift_0', 'lift_1',
... | class PandaPlayGeneric(ManipulatorEnv):
| VALID_AUX_TASKS = ['open_action',
'close_action',
'stack_0', 'stack_1',
'insert', 'insert_0', 'insert_1',
'bring', 'bring_0', 'bring_1',
'lift_0', 'lift_1',
'reach_0', 'reach_1',... | """ A set of environments with a shared observation/state space for multi-task and transfer learning """
import numpy as np
import copy
from manipulator_learning.sim.envs.manipulator_env_generic import ManipulatorEnv
from manipulator_learning.sim.envs.configs.panda_default import CONFIG as DEF_CONFIG
import manipulat... | 207 | 256 | 4,519 | 8 | 199 | utiasSTARS/manipulator_learning | manipulator_learning/sim/envs/panda_play.py | Python | PandaPlayGeneric | PandaPlayGeneric | 20 | 387 | 20 | 20 | e1bea268b48f3c79f1edc4cf41a3c92ed2ccaec3 | bigcode/the-stack | train |
29e400a266d7582214bb275f | train | class | class PandaPlayInsertTrayDPGripXYZState(PandaPlayInsertTrayXYZState):
def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='insert', **kwargs):
super().__init__(max_real_time, n_substeps, dense_reward, action_multiplier, main_task,
... | class PandaPlayInsertTrayDPGripXYZState(PandaPlayInsertTrayXYZState):
| def __init__(self, max_real_time=18, n_substeps=5, dense_reward=True, action_multiplier=0.002,
main_task='insert', **kwargs):
super().__init__(max_real_time, n_substeps, dense_reward, action_multiplier, main_task,
gripper_control_method='dp', grip_multiplier=0.25)
| .075, .5, .135]]), # relative to robot base frame
bring_goal_poss=np.array([[.075, .5, .145], [-.075, .5, .145]])
)
class PandaPlayInsertTrayDPGripXYZState(PandaPlayInsertTrayXYZState):
| 64 | 64 | 93 | 17 | 47 | utiasSTARS/manipulator_learning | manipulator_learning/sim/envs/panda_play.py | Python | PandaPlayInsertTrayDPGripXYZState | PandaPlayInsertTrayDPGripXYZState | 440 | 444 | 440 | 440 | 4494a1fc210d7b0ea5cc886fe67933c2d8fe5a23 | bigcode/the-stack | train |
09ba40986d8c65ac708df18e | train | function | def xform_name(name, sep='_', _xform_cache=_xform_cache):
"""Convert camel case to a "pythonic" name.
If the name contains the ``sep`` character, then it is
returned unchanged.
"""
if sep in name:
# If the sep is in the name, assume that it's already
# transformed and return the st... | def xform_name(name, sep='_', _xform_cache=_xform_cache):
| """Convert camel case to a "pythonic" name.
If the name contains the ``sep`` character, then it is
returned unchanged.
"""
if sep in name:
# If the sep is in the name, assume that it's already
# transformed and return the string unchanged.
return name
key = (name, sep)
... | __))
# Used to specify anonymous (unsigned) request signature
class UNSIGNED(object):
def __copy__(self):
return self
def __deepcopy__(self, memodict):
return self
UNSIGNED = UNSIGNED()
def xform_name(name, sep='_', _xform_cache=_xform_cache):
| 69 | 69 | 233 | 18 | 51 | frivas/alexa-mixed-polly | lambda/py/lambda_upload/botocore/__init__.py | Python | xform_name | xform_name | 71 | 92 | 71 | 71 | 1edf74f6386d78b9baaa6327c1da083b06a4a50a | bigcode/the-stack | train |
24d8ce5ce49152f4b8aad30a | train | class | class UNSIGNED(object):
def __copy__(self):
return self
def __deepcopy__(self, memodict):
return self
| class UNSIGNED(object):
| def __copy__(self):
return self
def __deepcopy__(self, memodict):
return self
| fixed without having to call out each
# individual case.
ScalarTypes = ('string', 'integer', 'boolean', 'timestamp', 'float', 'double')
BOTOCORE_ROOT = os.path.dirname(os.path.abspath(__file__))
# Used to specify anonymous (unsigned) request signature
class UNSIGNED(object):
| 64 | 64 | 32 | 5 | 58 | frivas/alexa-mixed-polly | lambda/py/lambda_upload/botocore/__init__.py | Python | UNSIGNED | UNSIGNED | 60 | 65 | 60 | 60 | 1e1f8fa11ecfcfaf51ceb32f5f8b27e69bdf1616 | bigcode/the-stack | train |
231c507aa546eb6ad2224729 | train | class | class NullHandler(logging.Handler):
def emit(self, record):
pass
| class NullHandler(logging.Handler):
| def emit(self, record):
pass
| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import re
import logging
__version__ = '1.12.137'
class NullHandler(logging.Handler):
| 64 | 64 | 16 | 6 | 58 | frivas/alexa-mixed-polly | lambda/py/lambda_upload/botocore/__init__.py | Python | NullHandler | NullHandler | 22 | 24 | 22 | 22 | 7f33bbce5d634afba1f0fff359644f288dcf671e | bigcode/the-stack | train |
2f87c61c7bbfa9460b69ef67 | train | class | class TripleRewardsAction(Action):
def __repr__(self):
return f"TripleRewards()"
def apply(self, player: 'Player'):
player.play_triple_rewards()
def valid(self, player: 'Player') -> bool:
return player.validate_triple_rewards()
| class TripleRewardsAction(Action):
| def __repr__(self):
return f"TripleRewards()"
def apply(self, player: 'Player'):
player.play_triple_rewards()
def valid(self, player: 'Player') -> bool:
return player.validate_triple_rewards()
| ()
class HeroPowerAction(Action):
def __repr__(self):
return f"HeroPower()"
def apply(self, player: 'Player'):
player.hero_power()
def valid(self, player: 'Player') -> bool:
return player.validate_hero_power()
class TripleRewardsAction(Action):
| 64 | 64 | 59 | 6 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | TripleRewardsAction | TripleRewardsAction | 131 | 139 | 131 | 131 | 22156b96039d39f68fc0613912190c3282399f16 | bigcode/the-stack | train |
ab724609e58a60ec7b5f4657 | train | class | class Action:
def apply(self, player: 'Player'):
pass
def valid(self, player: 'Player') -> bool:
return False
| class Action:
| def apply(self, player: 'Player'):
pass
def valid(self, player: 'Player') -> bool:
return False
| import typing
from typing import List, Optional, Generator
from hearthstone.player import StoreIndex, HandIndex, BoardIndex
if typing.TYPE_CHECKING:
from hearthstone.cards import Card, MonsterCard
from hearthstone.hero import Hero
from hearthstone.tavern import Player
class Action:
| 64 | 64 | 33 | 3 | 60 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | Action | Action | 12 | 17 | 12 | 12 | ca9a475a309add3e63a07c790aee0d500b8f6217 | bigcode/the-stack | train |
ad62ff05361c53c85f8ee904 | train | function | def generate_all_actions(player: 'Player') -> Generator[Action, None, None]:
yield TripleRewardsAction()
yield HeroPowerAction()
yield TavernUpgradeAction()
yield RerollAction()
yield EndPhaseAction(True)
yield EndPhaseAction(False)
for index in range(len(player.hand)):
yield SellFro... | def generate_all_actions(player: 'Player') -> Generator[Action, None, None]:
| yield TripleRewardsAction()
yield HeroPowerAction()
yield TavernUpgradeAction()
yield RerollAction()
yield EndPhaseAction(True)
yield EndPhaseAction(False)
for index in range(len(player.hand)):
yield SellFromHandAction(HandIndex(index))
for index in range(len(player.in_play)):
... | :param ranking: Integer index 0 to 7 of where the agent placed
:return:
"""
pass
def generate_valid_actions(player: 'Player') -> Generator[Action, None, None]:
return (action for action in generate_all_actions(player) if action.valid(player))
def generate_all_actions(player: 'Player') -> G... | 79 | 79 | 265 | 18 | 61 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | generate_all_actions | generate_all_actions | 199 | 224 | 199 | 199 | 7aa90af90a66de701175212af668ce8b5421fd38 | bigcode/the-stack | train |
655f51bd3e2c43d771e6ae00 | train | class | class TavernUpgradeAction(Action):
def __repr__(self):
return f"TavernUpgrade()"
def apply(self, player: 'Player'):
player.upgrade_tavern()
def valid(self, player: 'Player') -> bool:
return player.validate_upgrade_tavern()
| class TavernUpgradeAction(Action):
| def __repr__(self):
return f"TavernUpgrade()"
def apply(self, player: 'Player'):
player.upgrade_tavern()
def valid(self, player: 'Player') -> bool:
return player.validate_upgrade_tavern()
| ollAction(Action):
def __repr__(self):
return f"Reroll()"
def apply(self, player: 'Player'):
player.reroll_store()
def valid(self, player: 'Player') -> bool:
return player.validate_reroll()
class TavernUpgradeAction(Action):
| 64 | 64 | 62 | 6 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | TavernUpgradeAction | TavernUpgradeAction | 109 | 117 | 109 | 109 | 3684a7304ee2c7a37ed95fd42c3ee2e0409e1a27 | bigcode/the-stack | train |
1e10fe51428905f1b6ce4c1f | train | class | class BuyAction(Action):
def __init__(self, index: StoreIndex):
self.index = index
def __repr__(self):
return f"Buy({self.index})"
def apply(self, player: 'Player'):
player.purchase(self.index)
def valid(self, player: 'Player'):
return player.validate_purchase(self.in... | class BuyAction(Action):
| def __init__(self, index: StoreIndex):
self.index = index
def __repr__(self):
return f"Buy({self.index})"
def apply(self, player: 'Player'):
player.purchase(self.index)
def valid(self, player: 'Player'):
return player.validate_purchase(self.index)
| stone.cards import Card, MonsterCard
from hearthstone.hero import Hero
from hearthstone.tavern import Player
class Action:
def apply(self, player: 'Player'):
pass
def valid(self, player: 'Player') -> bool:
return False
class BuyAction(Action):
| 64 | 64 | 74 | 5 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | BuyAction | BuyAction | 20 | 32 | 20 | 21 | a380e9d4733200c9b40b1c6c199fa8e2f7a51c8f | bigcode/the-stack | train |
7d02c97ad145b042ac84892f | train | class | class SellFromHandAction(Action):
def __init__(self, index: HandIndex):
self.index: HandIndex = index
def __repr__(self):
return f"SellFromHand({self.index})"
def apply(self, player: 'Player'):
player.sell_hand_minion(self.index)
def valid(self, player: 'Player') -> bool:
... | class SellFromHandAction(Action):
| def __init__(self, index: HandIndex):
self.index: HandIndex = index
def __repr__(self):
return f"SellFromHand({self.index})"
def apply(self, player: 'Player'):
player.sell_hand_minion(self.index)
def valid(self, player: 'Player') -> bool:
return player.validate_sell_ha... | }, {self.targets})"
def apply(self, player: 'Player'):
player.summon_from_hand(self.index, self.targets)
def valid(self, player: 'Player') -> bool:
return player.validate_summon_from_hand(self.index, self.targets)
class SellFromHandAction(Action):
| 64 | 64 | 90 | 7 | 57 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | SellFromHandAction | SellFromHandAction | 52 | 64 | 52 | 53 | 7ac62bb5a0eec16639495073e845e3fbe8863a4a | bigcode/the-stack | train |
3d35f33cc837148670477277 | train | function | def generate_valid_actions(player: 'Player') -> Generator[Action, None, None]:
return (action for action in generate_all_actions(player) if action.valid(player))
| def generate_valid_actions(player: 'Player') -> Generator[Action, None, None]:
| return (action for action in generate_all_actions(player) if action.valid(player))
| Notifies the agent that the game is over and the agent has achieved a given rank
:param ranking: Integer index 0 to 7 of where the agent placed
:return:
"""
pass
def generate_valid_actions(player: 'Player') -> Generator[Action, None, None]:
| 64 | 64 | 35 | 18 | 45 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | generate_valid_actions | generate_valid_actions | 195 | 196 | 195 | 195 | 0068dc08e653e60edc61f3a835c9acaeacf2d9e0 | bigcode/the-stack | train |
9a2b66bfb829cc12052f540e | train | class | class EndPhaseAction(Action):
def __init__(self, freeze: bool):
self.freeze: bool = freeze
def __repr__(self):
return f"EndPhase({self.freeze})"
def apply(self, player: 'Player'):
if self.freeze:
player.freeze()
def valid(self, player: 'Player') -> bool:
r... | class EndPhaseAction(Action):
| def __init__(self, freeze: bool):
self.freeze: bool = freeze
def __repr__(self):
return f"EndPhase({self.freeze})"
def apply(self, player: 'Player'):
if self.freeze:
player.freeze()
def valid(self, player: 'Player') -> bool:
return True
| __(self):
return f"SellFromBoard({self.index})"
def apply(self, player: 'Player'):
player.sell_board_minion(self.index)
def valid(self, player: 'Player') -> bool:
return player.validate_sell_board_minion(self.index)
class EndPhaseAction(Action):
| 64 | 64 | 79 | 6 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | EndPhaseAction | EndPhaseAction | 82 | 95 | 82 | 83 | dec325716d117ddc3dce322bf900c25e8de2eae3 | bigcode/the-stack | train |
9a72a3e9523aebc7a9b626e8 | train | class | class Agent:
def hero_choice_action(self, player: 'Player') -> 'Hero':
return player.hero_options[0]
def rearrange_cards(self, player: 'Player') -> List['Card']:
"""
here the player selects a card arangement one time per combat directly preceeding combat
Args:
playe... | class Agent:
| def hero_choice_action(self, player: 'Player') -> 'Hero':
return player.hero_options[0]
def rearrange_cards(self, player: 'Player') -> List['Card']:
"""
here the player selects a card arangement one time per combat directly preceeding combat
Args:
player: The player... | def apply(self, player: 'Player'):
player.hero_power()
def valid(self, player: 'Player') -> bool:
return player.validate_hero_power()
class TripleRewardsAction(Action):
def __repr__(self):
return f"TripleRewards()"
def apply(self, player: 'Player'):
player.play_triple... | 98 | 98 | 327 | 3 | 95 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | Agent | Agent | 142 | 193 | 142 | 142 | b224260555b872c15a869a67666f002bb431e668 | bigcode/the-stack | train |
47ec767f457d8e304fae13f9 | train | class | class SummonAction(Action):
def __init__(self, index: HandIndex, targets: Optional[List[BoardIndex]] = None):
if targets is None:
targets = []
self.index = index
self.targets = targets
def __repr__(self):
return f"Summon({self.index}, {self.targets})"
def apply(... | class SummonAction(Action):
| def __init__(self, index: HandIndex, targets: Optional[List[BoardIndex]] = None):
if targets is None:
targets = []
self.index = index
self.targets = targets
def __repr__(self):
return f"Summon({self.index}, {self.targets})"
def apply(self, player: 'Player'):
... | ):
self.index = index
def __repr__(self):
return f"Buy({self.index})"
def apply(self, player: 'Player'):
player.purchase(self.index)
def valid(self, player: 'Player'):
return player.validate_purchase(self.index)
class SummonAction(Action):
| 64 | 64 | 124 | 6 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | SummonAction | SummonAction | 35 | 49 | 35 | 35 | cc84cc7b42d68e6acb6ecf5a02fbf0770a070fff | bigcode/the-stack | train |
054c8a646f744b2bf7a88f05 | train | class | class RerollAction(Action):
def __repr__(self):
return f"Reroll()"
def apply(self, player: 'Player'):
player.reroll_store()
def valid(self, player: 'Player') -> bool:
return player.validate_reroll()
| class RerollAction(Action):
| def __repr__(self):
return f"Reroll()"
def apply(self, player: 'Player'):
player.reroll_store()
def valid(self, player: 'Player') -> bool:
return player.validate_reroll()
| = freeze
def __repr__(self):
return f"EndPhase({self.freeze})"
def apply(self, player: 'Player'):
if self.freeze:
player.freeze()
def valid(self, player: 'Player') -> bool:
return True
class RerollAction(Action):
| 64 | 64 | 61 | 7 | 56 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | RerollAction | RerollAction | 98 | 106 | 98 | 98 | 2c8959ba5b7f82583cb8e834bb029bd9d2bd21cf | bigcode/the-stack | train |
ae20b255e2e8f79389e602de | train | class | class SellFromBoardAction(Action):
def __init__(self, index: BoardIndex):
self.index: BoardIndex = index
def __repr__(self):
return f"SellFromBoard({self.index})"
def apply(self, player: 'Player'):
player.sell_board_minion(self.index)
def valid(self, player: 'Player') -> bool... | class SellFromBoardAction(Action):
| def __init__(self, index: BoardIndex):
self.index: BoardIndex = index
def __repr__(self):
return f"SellFromBoard({self.index})"
def apply(self, player: 'Player'):
player.sell_board_minion(self.index)
def valid(self, player: 'Player') -> bool:
return player.validate_sel... | self):
return f"SellFromHand({self.index})"
def apply(self, player: 'Player'):
player.sell_hand_minion(self.index)
def valid(self, player: 'Player') -> bool:
return player.validate_sell_hand_minion(self.index)
class SellFromBoardAction(Action):
| 64 | 64 | 90 | 7 | 57 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | SellFromBoardAction | SellFromBoardAction | 67 | 79 | 67 | 68 | bbd583b9522e23f6e447388cb51ab45027d0c13d | bigcode/the-stack | train |
d11610b8509a43e490ee71f6 | train | class | class HeroPowerAction(Action):
def __repr__(self):
return f"HeroPower()"
def apply(self, player: 'Player'):
player.hero_power()
def valid(self, player: 'Player') -> bool:
return player.validate_hero_power()
| class HeroPowerAction(Action):
| def __repr__(self):
return f"HeroPower()"
def apply(self, player: 'Player'):
player.hero_power()
def valid(self, player: 'Player') -> bool:
return player.validate_hero_power()
| (Action):
def __repr__(self):
return f"TavernUpgrade()"
def apply(self, player: 'Player'):
player.upgrade_tavern()
def valid(self, player: 'Player') -> bool:
return player.validate_upgrade_tavern()
class HeroPowerAction(Action):
| 64 | 64 | 57 | 6 | 58 | dianarvp/stone_ground_hearth_battles | hearthstone/agent.py | Python | HeroPowerAction | HeroPowerAction | 120 | 128 | 120 | 120 | 68a17c6184f2ebd0b3b95feff33321d9dc3cce50 | bigcode/the-stack | train |
ddb4e15694aa86065d492d22 | train | function | @main.app_errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
| @main.app_errorhandler(500)
def internal_server_error(e):
| return render_template('500.html'), 500
| 8 14:43
# @Author : Li Fu
from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@main.app_errorhandler(500)
def internal_server_error(e):
| 64 | 64 | 25 | 14 | 49 | ChrisLeeUnderTree/test | app/main/errors.py | Python | internal_server_error | internal_server_error | 14 | 16 | 14 | 15 | e83e646ebb0aa7f752842c56e6f7ec25bbda7680 | bigcode/the-stack | train |
9a9cc247e2928520d97479d8 | train | function | @main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
| @main.app_errorhandler(404)
def page_not_found(e):
| return render_template('404.html'), 404
| # -*- coding: utf-8 -*-
# @Time : 2019/7/8 14:43
# @Author : Li Fu
from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
| 58 | 64 | 25 | 14 | 43 | ChrisLeeUnderTree/test | app/main/errors.py | Python | page_not_found | page_not_found | 9 | 11 | 9 | 10 | ada0d7fc07bba3a845b55197549671e70b8f4ee1 | bigcode/the-stack | train |
b98708356c577057156c671f | train | function | def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
... | def pick_word(probabilities, int_to_vocab):
| """
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
return int_to_vocab[np.random.choice(range... | loaded_graph.get_tensor_by_name("final_state:0")
ProbsTensor = loaded_graph.get_tensor_by_name("probs:0")
# TODO: Implement Function
return (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
def pick_word(probabilities, int_to_vocab):
| 64 | 64 | 97 | 10 | 54 | yoyoismee/Sarkhans-Constitution-Generator | draft.py | Python | pick_word | pick_word | 31 | 39 | 31 | 31 | 88c0b27b1f9a905d81f46daa738404b59a5108bb | bigcode/the-stack | train |
72cbbc20b441ec44f9ad981c | train | function | def get_tensors(loaded_graph):
InputTensor = loaded_graph.get_tensor_by_name("input:0")
InitialStateTensor = loaded_graph.get_tensor_by_name("initial_state:0")
FinalStateTensor = loaded_graph.get_tensor_by_name("final_state:0")
ProbsTensor = loaded_graph.get_tensor_by_name("probs:0")
# TODO: Implem... | def get_tensors(loaded_graph):
| InputTensor = loaded_graph.get_tensor_by_name("input:0")
InitialStateTensor = loaded_graph.get_tensor_by_name("initial_state:0")
FinalStateTensor = loaded_graph.get_tensor_by_name("final_state:0")
ProbsTensor = loaded_graph.get_tensor_by_name("probs:0")
# TODO: Implement Function
return (InputTe... | default = "ประชาชน")
args = parser.parse_args()
_, vocab_to_int, int_to_vocab, token_dict = pickle.load(open('data.pj', mode='rb'))
seq_length, load_dir = pickle.load(open('params.pj', mode='rb'))
def get_tensors(loaded_graph):
| 63 | 64 | 99 | 8 | 55 | yoyoismee/Sarkhans-Constitution-Generator | draft.py | Python | get_tensors | get_tensors | 22 | 29 | 22 | 23 | ba80791d380a14c173443c85dc485556f8b8392d | bigcode/the-stack | train |
4dc5668601268558557fcacb | train | function | def test_load_points_from_multi_sweeps():
np.random.seed(0)
file_client_args = dict(backend='disk')
load_points_from_multi_sweeps_1 = LoadPointsFromMultiSweeps(
sweeps_num=9,
use_dim=[0, 1, 2, 3, 4],
file_client_args=file_client_args)
load_points_from_multi_sweeps_2 = LoadPoint... | def test_load_points_from_multi_sweeps():
| np.random.seed(0)
file_client_args = dict(backend='disk')
load_points_from_multi_sweeps_1 = LoadPointsFromMultiSweeps(
sweeps_num=9,
use_dim=[0, 1, 2, 3, 4],
file_client_args=file_client_args)
load_points_from_multi_sweeps_2 = LoadPointsFromMultiSweeps(
sweeps_num=9,
... | import numpy as np
from mmdet3d.datasets.pipelines.loading import LoadPointsFromMultiSweeps
def test_load_points_from_multi_sweeps():
| 33 | 225 | 751 | 10 | 22 | Shudeng/hgnn_mmdet | tests/test_pipeline/test_load_points_from_multi_sweeps.py | Python | test_load_points_from_multi_sweeps | test_load_points_from_multi_sweeps | 6 | 67 | 6 | 6 | e9f624fecd720cb18956047b43f85dfb3c66435d | bigcode/the-stack | train |
3aee543225a9b613c9eafaf3 | train | class | class EngineAPIDimensionsHelperTest(unittest.TestCase):
__SCRAPE_PACKAGE = 'google.datacatalog_connectors.qlik.scrape'
__BASE_CLASS = f'{__SCRAPE_PACKAGE}.base_engine_api_helper' \
f'.BaseEngineAPIHelper'
__HELPER_CLASS = f'{__SCRAPE_PACKAGE}.engine_api_dimensions_helper' \
... | class EngineAPIDimensionsHelperTest(unittest.TestCase):
| __SCRAPE_PACKAGE = 'google.datacatalog_connectors.qlik.scrape'
__BASE_CLASS = f'{__SCRAPE_PACKAGE}.base_engine_api_helper' \
f'.BaseEngineAPIHelper'
__HELPER_CLASS = f'{__SCRAPE_PACKAGE}.engine_api_dimensions_helper' \
f'.EngineAPIDimensionsHelper'
def setUp(self... | #!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 185 | 256 | 1,094 | 12 | 172 | Parkman328/datacatalog-connectors-bi | google-datacatalog-qlik-connector/tests/google/datacatalog_connectors/qlik/scrape/engine_api_dimensions_helper_test.py | Python | EngineAPIDimensionsHelperTest | EngineAPIDimensionsHelperTest | 27 | 153 | 27 | 27 | b50aed615b2168eab018b7fa26ecf671c624e285 | bigcode/the-stack | train |
763d91088551a6cf2b1ac736 | train | function | def dna_complement(str):
dna = {'A':'T','T':'A','G':'C','C':'G'}
result = ''
if str is None or str == '':
return None
for i in str:
c = i.upper()
if c not in dna:
return None
else:
result += dna[c]
return result
| def dna_complement(str):
| dna = {'A':'T','T':'A','G':'C','C':'G'}
result = ''
if str is None or str == '':
return None
for i in str:
c = i.upper()
if c not in dna:
return None
else:
result += dna[c]
return result
| def dna_complement(str):
| 6 | 64 | 79 | 6 | 0 | TangJiahui/cs107_system_devlopment | homework/HW2/HW2-final/P2.py | Python | dna_complement | dna_complement | 1 | 12 | 1 | 1 | dd85173d676da734fb2aad02888f0efb2e256bf2 | bigcode/the-stack | train |
69b54ca8ef3f49ae1619e844 | train | function | def _get_metadata(package_name):
try:
return json.loads(
pkg_resources.get_distribution(
package_name).get_metadata('pbr.json'))
except pkg_resources.DistributionNotFound:
raise Exception('Package {0} not installed'.format(package_name))
except Exception:
... | def _get_metadata(package_name):
| try:
return json.loads(
pkg_resources.get_distribution(
package_name).get_metadata('pbr.json'))
except pkg_resources.DistributionNotFound:
raise Exception('Package {0} not installed'.format(package_name))
except Exception:
return None
| BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
import json
import sys
import pkg_resources
import pbr.version
def _get_metadata(package_name):
| 64 | 64 | 64 | 7 | 56 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | _get_metadata | _get_metadata | 25 | 33 | 25 | 25 | c9d3520db71b2509d079b44bb15252e94472c4ac | bigcode/the-stack | train |
df48923d7a688f0c44ae387b | train | function | def _get_info(name):
metadata = _get_metadata(name)
version = pkg_resources.get_distribution(name).version
if metadata:
if metadata['is_release']:
released = 'released'
else:
released = 'pre-release'
sha = metadata['git_version']
else:
version_part... | def _get_info(name):
| metadata = _get_metadata(name)
version = pkg_resources.get_distribution(name).version
if metadata:
if metadata['is_release']:
released = 'released'
else:
released = 'pre-release'
sha = metadata['git_version']
else:
version_parts = version.split('.'... | def get_sha(args):
sha = _get_info(args.name)['sha']
if sha:
print(sha)
def get_info(args):
print("{name}\t{version}\t{released}\t{sha}".format(
**_get_info(args.name)))
def _get_info(name):
| 63 | 64 | 151 | 6 | 57 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | _get_info | _get_info | 47 | 67 | 47 | 47 | d45885b4ab7b79b0de36c3bc1c01dc73f1018c76 | bigcode/the-stack | train |
f4817df04391641cf7b5866f | train | function | def main():
parser = argparse.ArgumentParser(
description='pbr: Python Build Reasonableness')
parser.add_argument(
'-v', '--version', action='version',
version=str(pbr.version.VersionInfo('pbr')))
subparsers = parser.add_subparsers(
title='commands', description='valid comma... | def main():
| parser = argparse.ArgumentParser(
description='pbr: Python Build Reasonableness')
parser.add_argument(
'-v', '--version', action='version',
version=str(pbr.version.VersionInfo('pbr')))
subparsers = parser.add_subparsers(
title='commands', description='valid commands', help='... | )
def freeze(args):
for dist in pkg_resources.working_set:
info = _get_info(dist.project_name)
output = "{name}=={version}".format(**info)
if info['sha']:
output += " # git sha {sha}".format(**info)
print(output)
def main():
| 67 | 67 | 226 | 3 | 64 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | main | main | 79 | 106 | 79 | 79 | c5b6a8105272a2b0c11bf0e7dbbb79084cbdf3d4 | bigcode/the-stack | train |
87884c76b5451e2e8fc70456 | train | function | def get_sha(args):
sha = _get_info(args.name)['sha']
if sha:
print(sha)
| def get_sha(args):
| sha = _get_info(args.name)['sha']
if sha:
print(sha)
| _name):
try:
return json.loads(
pkg_resources.get_distribution(
package_name).get_metadata('pbr.json'))
except pkg_resources.DistributionNotFound:
raise Exception('Package {0} not installed'.format(package_name))
except Exception:
return None
def get_sha(a... | 64 | 64 | 25 | 5 | 58 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | get_sha | get_sha | 36 | 39 | 36 | 36 | 31fa6036f35a74ede70a4f336ac434d87b72f0f9 | bigcode/the-stack | train |
2e29e74e2ab9b86d0f231693 | train | function | def get_info(args):
print("{name}\t{version}\t{released}\t{sha}".format(
**_get_info(args.name)))
| def get_info(args):
| print("{name}\t{version}\t{released}\t{sha}".format(
**_get_info(args.name)))
| .json'))
except pkg_resources.DistributionNotFound:
raise Exception('Package {0} not installed'.format(package_name))
except Exception:
return None
def get_sha(args):
sha = _get_info(args.name)['sha']
if sha:
print(sha)
def get_info(args):
| 64 | 64 | 32 | 5 | 59 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | get_info | get_info | 42 | 44 | 42 | 42 | 278b1161da2447546fde8ae2dd090ca132728111 | bigcode/the-stack | train |
3ba99ebb22ff66a25b9a73cb | train | function | def freeze(args):
for dist in pkg_resources.working_set:
info = _get_info(dist.project_name)
output = "{name}=={version}".format(**info)
if info['sha']:
output += " # git sha {sha}".format(**info)
print(output)
| def freeze(args):
| for dist in pkg_resources.working_set:
info = _get_info(dist.project_name)
output = "{name}=={version}".format(**info)
if info['sha']:
output += " # git sha {sha}".format(**info)
print(output)
| :]
released = 'pre-release'
else:
sha = ""
released = "released"
for part in version_parts:
if not part.isdigit():
released = "pre-release"
return dict(name=name, version=version, sha=sha, released=released)
def freeze(args)... | 64 | 64 | 63 | 4 | 60 | theholyhades1/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/cmd/main.py | Python | freeze | freeze | 70 | 76 | 70 | 70 | 3e734c67a55ab281425d9ed65bb83b25aafab3c4 | bigcode/the-stack | train |
0c8be8edaaaf16ca530b58af | train | class | class ElseAST(AST):
def __init__(self, scope):
self.scope = scope
| class ElseAST(AST):
| def __init__(self, scope):
self.scope = scope
| from .AST import AST
class ElseAST(AST):
| 11 | 64 | 20 | 5 | 5 | antuniooh/Dattebayo-compiler | code/AST/ElseAST.py | Python | ElseAST | ElseAST | 4 | 6 | 4 | 4 | 54346a0a9893586e306045e164a07f8bbd6eaeef | bigcode/the-stack | train |
1592bd9b8cd00bee27ef493b | train | class | class Ui_Tela_Principal(object):
def setupUi(self, Tela_Principal):
Tela_Principal.setObjectName("Tela_Principal")
Tela_Principal.resize(926, 547)
Tela_Principal.setFixedSize(926, 547)
self.centralwidget = QtWidgets.QWidget(Tela_Principal)
self.centralwidget.setObjectName("ce... | class Ui_Tela_Principal(object):
| def setupUi(self, Tela_Principal):
Tela_Principal.setObjectName("Tela_Principal")
Tela_Principal.resize(926, 547)
Tela_Principal.setFixedSize(926, 547)
self.centralwidget = QtWidgets.QWidget(Tela_Principal)
self.centralwidget.setObjectName("centralwidget")
self.label ... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tela_principal.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Tela_Principal(object):
| 77 | 256 | 944 | 8 | 68 | Gas-Helio/CRUD-Biblioteca | telas/tela_principal.py | Python | Ui_Tela_Principal | Ui_Tela_Principal | 13 | 85 | 13 | 13 | 4e9858186dd2e8a330fcd650745e818203cd9ec4 | bigcode/the-stack | train |
fe96235952ccfb2034814475 | train | class | class FunctionImageData(ImageData):
""" A class that provides data for a 2-D image based upon the range
supplied. This class can be used as the data source for an image plot
or contour plot.
Computation should be fairly swift for acceptable interactive performance.
"""
# The function to call ... | class FunctionImageData(ImageData):
| """ A class that provides data for a 2-D image based upon the range
supplied. This class can be used as the data source for an image plot
or contour plot.
Computation should be fairly swift for acceptable interactive performance.
"""
# The function to call with the low and high values of the ... | from numpy import array
from traits.api import Instance, Callable, on_trait_change
from .data_range_2d import DataRange2D
from .image_data import ImageData
# Adapted (ie. copied and modified) from function_data_source.
# Given the time frequently required for image manipulation,
# it would be awesome if there was a m... | 91 | 113 | 378 | 7 | 84 | martinRenou/chaco | chaco/function_image_data.py | Python | FunctionImageData | FunctionImageData | 12 | 55 | 12 | 12 | e5870af8ea559025e6b917113c4d021b59719706 | bigcode/the-stack | train |
2e20335f525e68f567ce4d96 | train | class | class SelectizeWidget(Select):
_view_name = Unicode('SelectizeView', sync=True)
theme = CaselessStrEnum(
values=['default', 'legacy', 'bootstrap2', 'bootstrap3'],
default_value='default', sync=True,
help="""Use a them styling for the SelectizeWidget.""")
disabled = Bool(False, help="... | class SelectizeWidget(Select):
| _view_name = Unicode('SelectizeView', sync=True)
theme = CaselessStrEnum(
values=['default', 'legacy', 'bootstrap2', 'bootstrap3'],
default_value='default', sync=True,
help="""Use a them styling for the SelectizeWidget.""")
disabled = Bool(False, help="Enable or disable user changes"... | # coding=utf-8
from IPython.html.widgets import Select
from IPython.utils.traitlets import (Unicode, CaselessStrEnum, Bool)
class SelectizeWidget(Select):
| 39 | 76 | 255 | 7 | 32 | dongweiming/divingintoipynb | double11/widget_selectize.py | Python | SelectizeWidget | SelectizeWidget | 7 | 36 | 7 | 7 | eb58120a3c4ec14efe6da1fd09aae816afc859a0 | bigcode/the-stack | train |
3de4e94108423a865e185588 | train | function | def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
result = fib(n - 1) + fib(n - 2)
return result
| def fib(n):
| if n == 0:
return 0
elif n == 1:
return 1
else:
result = fib(n - 1) + fib(n - 2)
return result
| = (fib(2) + fib(1)) + (fib(1) + fib(0)) : 2 + 1
# 3rd : result = (fib(1) + fib(0)) + fib(0) : 1 + 0
'''
def fib(n):
| 63 | 64 | 51 | 4 | 59 | alirsamar/pycourse | Recursive Functions Dictionaries.py | Python | fib | fib | 153 | 161 | 153 | 153 | a778a7a80b21e7b1eae2b219e5215a416f844690 | bigcode/the-stack | train |
89eaa3af9f0230a726fdc746 | train | function | def factorial(num):
# Every recursive function must contain a condition
# when it ceases to call itself
if num <= 1:
return 1
else:
result = num * factorial(num - 1)
return result
| def factorial(num):
# Every recursive function must contain a condition
# when it ceases to call itself
| if num <= 1:
return 1
else:
result = num * factorial(num - 1)
return result
| ----------
# A function that refers to itself is a recursive function
# Calculating factorials is commonly done with a recursive
# function 3! = 3 * 2 * 1
def factorial(num):
# Every recursive function must contain a condition
# when it ceases to call itself
| 64 | 64 | 54 | 24 | 39 | alirsamar/pycourse | Recursive Functions Dictionaries.py | Python | factorial | factorial | 111 | 119 | 111 | 113 | e5dcd556527824166144b5f68027d05f3bb1f7a0 | bigcode/the-stack | train |
f3a263a5cb594d7ba4204e54 | train | class | class Finding:
def __init__(self):
self.output = []
self.is_compliant = False
self.uuid = "20b9aba4-5cc5-11e4-af55-00155d01fe08"
def check(self, cli):
# Initialize Compliance
self.is_compliant = False
# Get Registry DWORD
dword = cli.get_reg_dwor... | class Finding:
| def __init__(self):
self.output = []
self.is_compliant = False
self.uuid = "20b9aba4-5cc5-11e4-af55-00155d01fe08"
def check(self, cli):
# Initialize Compliance
self.is_compliant = False
# Get Registry DWORD
dword = cli.get_reg_dword(r'HKLM:\Softw... | #!/usr/bin/python
################################################################################
# 20b9aba4-5cc5-11e4-af55-00155d01fe08
#
# Justin Dierking
# justindierking@hardbitsolutions.com
# phnomcobra@gmail.com
#
# 10/24/2014 Original Construction
################################################################... | 74 | 91 | 306 | 3 | 70 | phnomcobra/PCAT2PY | pcat2py/class/20b9aba4-5cc5-11e4-af55-00155d01fe08.py | Python | Finding | Finding | 12 | 37 | 12 | 12 | 56194afd07d9eb4f1b910a57d6906e0e00423460 | bigcode/the-stack | train |
8aa531fcccb3d4e7178b56fc | train | class | class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def helper(value):
if value is None:
return 0
if value.left is None:
return 1 + helper(value.right)
if value.right is None:
return 1 + helper(value.left)
... | class Solution:
| def minDepth(self, root: Optional[TreeNode]) -> int:
def helper(value):
if value is None:
return 0
if value.left is None:
return 1 + helper(value.right)
if value.right is None:
return 1 + helper(value.left)
retur... | leaf is a node with no children.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
| 64 | 64 | 87 | 3 | 60 | neerajp99/algorithms | problems/leetcode/lt-111.py | Python | Solution | Solution | 15 | 25 | 15 | 15 | af1611971d1945bec3230721cfe8f2fcb91095ab | bigcode/the-stack | train |
4edd11acfe10a40aadb18848 | train | class | class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# sentinel
sentinel = ListNode(0, head)
# predecessor = the last node
# before the sublist of duplicates
pred = sentinel
while head:
# if it's a beginning of duplicates sublist
... | class Solution:
| def deleteDuplicates(self, head: ListNode) -> ListNode:
# sentinel
sentinel = ListNode(0, head)
# predecessor = the last node
# before the sublist of duplicates
pred = sentinel
while head:
# if it's a beginning of duplicates sublist
# skip al... | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
| 40 | 64 | 161 | 3 | 36 | JawadAsif/leetcode | 82. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.py | Python | Solution | Solution | 8 | 33 | 8 | 8 | 78555df6b0f0fe17faba8d74e565f802dad1e131 | bigcode/the-stack | train |
14975e13ad82838cb2cf6434 | train | class | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
| class ListNode:
| def __init__(self, val=0, next=None):
self.val = val
self.next = next
| # Definition for singly-linked list.
class ListNode:
| 11 | 64 | 30 | 4 | 7 | JawadAsif/leetcode | 82. Remove Duplicates from Sorted List II/82. Remove Duplicates from Sorted List II.py | Python | ListNode | ListNode | 2 | 5 | 2 | 2 | 6d57ae6ce0c3fca23153f37d4914c293ee270856 | bigcode/the-stack | train |
e9b277454b5c223f7ddc0dcf | train | function | def shifted_diff(first, second):
# pivek303 - one line solution from CodeWars
# return (second + second).find(first) if len(first) == len(second) else - 1
if not Counter(first) == Counter(second):
return -1
for i, a in enumerate(xrange(len(first), -1, -1)):
if second == '{}{}'.format(fir... | def shifted_diff(first, second):
# pivek303 - one line solution from CodeWars
# return (second + second).find(first) if len(first) == len(second) else - 1
| if not Counter(first) == Counter(second):
return -1
for i, a in enumerate(xrange(len(first), -1, -1)):
if second == '{}{}'.format(first[a:], first[:a]):
return i
return -1
| from collections import Counter
def shifted_diff(first, second):
# pivek303 - one line solution from CodeWars
# return (second + second).find(first) if len(first) == len(second) else - 1
| 50 | 64 | 101 | 45 | 4 | the-zebulan/CodeWars | katas/kyu_6/calculate_string_rotation.py | Python | shifted_diff | shifted_diff | 4 | 12 | 4 | 6 | b87053d685a2207236205cd6828b32ec01786468 | bigcode/the-stack | train |
a13926fc98e40420c2927377 | train | class | class Application:
#инициация вебдрайвера
def __init__(self):
self.wd = webdriver.Chrome("C:/chromedriver.exe")
self.wd.implicitly_wait(60)
self.session = sessionHelper(self)
self.like = Like(self)
def open_home_page(self):
self.wd.get("https://www.instag... | class Application:
#инициация вебдрайвера
| def __init__(self):
self.wd = webdriver.Chrome("C:/chromedriver.exe")
self.wd.implicitly_wait(60)
self.session = sessionHelper(self)
self.like = Like(self)
def open_home_page(self):
self.wd.get("https://www.instagram.com/")
#закрытие драйвера
def dest... | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from fixture.session import sessionHelper
from fixture.like import Like
class Application:
#инициация вебдрайвера
| 49 | 64 | 101 | 14 | 34 | cryptologix/instagram_full | fixture/application.py | Python | Application | Application | 8 | 22 | 8 | 10 | cdd197cd333af641e6e5268e0076f154dc8aa53a | bigcode/the-stack | train |
4c05d823da154871a7ec04a8 | train | function | def compute_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth=DEFAULT_MAX_DEPTH,
num_leaves=DEFAULT_NUM_LEAVES,
min_child_samples=DEFAULT_MIN_CHILD_SAMPLES):
#... | def compute_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth=DEFAULT_MAX_DEPTH,
num_leaves=DEFAULT_NUM_LEAVES,
min_child_samples=DEFAULT_MIN_CHILD_SAMPLES):
#... | if max_depth is None:
max_depth = DEFAULT_MAX_DEPTH
if num_leaves is None:
num_leaves = DEFAULT_NUM_LEAVES
if min_child_samples is None:
min_child_samples = DEFAULT_MIN_CHILD_SAMPLES
filtered_df = filter_from_cohort(analyzer,
filters,
... | inferred if 'unknown',
but this can be overridden if you specify
'classification' or 'regression'.
"""
RIGHT_CHILD = 'right_child'
LEFT_CHILD = 'left_child'
UNKNOWN = 'unknown'
def compute_json_error_tree(analyzer,
features,
filters,
... | 207 | 207 | 693 | 56 | 151 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | compute_error_tree | compute_error_tree | 64 | 149 | 64 | 71 | 6dd6e4e62a6ae6fa1fd7b92134f34bc71007c832 | bigcode/the-stack | train |
c13c7bbaa3e5fc2c978e00cd | train | function | def node_to_dict(df, tree, nodeid, categories, json,
feature_names, metric, parent=None,
side=TreeSide.UNKNOWN, classes=None):
p_node_name = None
condition = None
arg = None
method = None
parentid = None
if parent is not None:
parentid = int(parent[SPLIT... | def node_to_dict(df, tree, nodeid, categories, json,
feature_names, metric, parent=None,
side=TreeSide.UNKNOWN, classes=None):
| p_node_name = None
condition = None
arg = None
method = None
parentid = None
if parent is not None:
parentid = int(parent[SPLIT_INDEX])
p_node_name = feature_names[parent[SPLIT_FEATURE]]
# use number.Integral to check for any numpy or python number type
if isinsta... | ]
def create_categorical_query(method, arg, p_node_name, p_node_query,
parent, categories):
if method == METHOD_INCLUDES:
operation = "=="
else:
operation = "!="
categorical_values = categories[0]
categorical_indexes = categories[1]
thresholds = []
... | 256 | 256 | 1,075 | 34 | 221 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | node_to_dict | node_to_dict | 306 | 423 | 306 | 308 | db91003d2ca1b53c0144c3dea5f7d1651371b7db | bigcode/the-stack | train |
a3fbe932104ce53ee21e8633 | train | class | class TreeSide(str, Enum):
"""Provide model task constants.
Can be 'classification', 'regression', or 'unknown'.
By default the model domain is inferred if 'unknown',
but this can be overridden if you specify
'classification' or 'regression'.
"""
RIGHT_CHILD = 'right_child'
LEFT_CHILD ... | class TreeSide(str, Enum):
| """Provide model task constants.
Can be 'classification', 'regression', or 'unknown'.
By default the model domain is inferred if 'unknown',
but this can be overridden if you specify
'classification' or 'regression'.
"""
RIGHT_CHILD = 'right_child'
LEFT_CHILD = 'left_child'
UNKNOWN ... | _display_name,
precision_metrics,
recall_metrics)
from erroranalysis._internal.metrics import get_ordered_classes, metric_to_func
MODEL = 'model'
DEFAULT_MAX_DEPTH = 3
DEFAULT_NUM_LEAVES = 31
DEFAULT_MIN_CHILD_SAMPLES = 20
cl... | 64 | 64 | 83 | 7 | 56 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | TreeSide | TreeSide | 32 | 43 | 32 | 32 | 877b88a544a9d958260c700885642fc06df03e5a | bigcode/the-stack | train |
86c0adb5f9aff202ae93db88 | train | function | def create_surrogate_model(analyzer,
dataset_sub_features,
diff,
max_depth,
num_leaves,
min_child_samples,
cat_ind_reindexed):
"""Creates and fits the sur... | def create_surrogate_model(analyzer,
dataset_sub_features,
diff,
max_depth,
num_leaves,
min_child_samples,
cat_ind_reindexed):
| """Creates and fits the surrogate lightgbm model.
:param analyzer: The error analyzer containing the categorical
features and categories for the full dataset.
:type analyzer: BaseAnalyzer
:param dataset_sub_features: The subset of features to train the
surrogate model on.
:type data... | = dumped_model["tree_info"][0]['tree_structure']
max_split_index = get_max_split_index(tree_structure) + 1
tree = traverse(filtered_indexed_df,
tree_structure,
max_split_index,
(categories_reindexed,
cat_ind_reindexed),
... | 119 | 119 | 398 | 36 | 82 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | create_surrogate_model | create_surrogate_model | 152 | 198 | 152 | 158 | 7ba636c3a95e58a780a85cc96fce3f244a9e32e9 | bigcode/the-stack | train |
f9871e14fc10596a3dd900ee | train | function | def get_max_split_index(tree):
if SPLIT_INDEX in tree:
max_index = tree[SPLIT_INDEX]
index1 = get_max_split_index(tree[TreeSide.LEFT_CHILD])
index2 = get_max_split_index(tree[TreeSide.RIGHT_CHILD])
return max(max(max_index, index1), index2)
else:
return 0
| def get_max_split_index(tree):
| if SPLIT_INDEX in tree:
max_index = tree[SPLIT_INDEX]
index1 = get_max_split_index(tree[TreeSide.LEFT_CHILD])
index2 = get_max_split_index(tree[TreeSide.RIGHT_CHILD])
return max(max(max_index, index1), index2)
else:
return 0
| .categorical_features):
try:
index_sub = dataset_sub_names.index(feature)
except ValueError:
continue
cat_ind_reindexed.append(index_sub)
categories_reindexed.append(analyzer.categories[c_index])
return (cat_ind_reindexed, categories_re... | 64 | 64 | 76 | 7 | 57 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | get_max_split_index | get_max_split_index | 227 | 234 | 227 | 227 | 92e2ac16596c7f2d0446abfe47e1eb6571644704 | bigcode/the-stack | train |
d7f043f0d2fa2ef27bf57b06 | train | function | def create_categorical_query(method, arg, p_node_name, p_node_query,
parent, categories):
if method == METHOD_INCLUDES:
operation = "=="
else:
operation = "!="
categorical_values = categories[0]
categorical_indexes = categories[1]
thresholds = []
catc... | def create_categorical_query(method, arg, p_node_name, p_node_query,
parent, categories):
| if method == METHOD_INCLUDES:
operation = "=="
else:
operation = "!="
categorical_values = categories[0]
categorical_indexes = categories[1]
thresholds = []
catcoli = categorical_indexes.index(parent[SPLIT_FEATURE])
catvals = categorical_values[catcoli]
for argi in arg:
... | feature_names,
tree, TreeSide.RIGHT_CHILD, metric,
classes)
return dict
def create_categorical_arg(parent_threshold):
return [float(i) for i in parent_threshold.split('||')]
def create_categorical_query(method, arg, p_node_name, p_node_query,
... | 65 | 66 | 221 | 22 | 43 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | create_categorical_query | create_categorical_query | 278 | 303 | 278 | 279 | 4f08db38c2f0f0a715d3942a2abce3a25e993746 | bigcode/the-stack | train |
22b7136263acb6f9add1061f | train | function | def get_categorical_info(analyzer, dataset_sub_names):
"""Returns the categorical information for the given feature names.
:param analyzer: The error analyzer containing the categorical
features and categories for the full dataset.
:type analyzer: BaseAnalyzer
:param dataset_sub_names: The subs... | def get_categorical_info(analyzer, dataset_sub_names):
| """Returns the categorical information for the given feature names.
:param analyzer: The error analyzer containing the categorical
features and categories for the full dataset.
:type analyzer: BaseAnalyzer
:param dataset_sub_names: The subset of feature names to get the
categorical inde... | _leaves,
min_child_samples=min_child_samples)
if cat_ind_reindexed:
surrogate.fit(dataset_sub_features, diff,
categorical_feature=cat_ind_reindexed)
else:
surrogate.fit(dataset_sub_features, diff)
return surrogate
def get_categorical_in... | 64 | 64 | 200 | 12 | 51 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | get_categorical_info | get_categorical_info | 201 | 224 | 201 | 201 | 59f7aa4bee46811a73afa2c5c5174315c15d4d83 | bigcode/the-stack | train |
626c199f54ab2e1edb4904c9 | train | function | def compute_json_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth=DEFAULT_MAX_DEPTH,
num_leaves=DEFAULT_NUM_LEAVES,
min_child_sample... | def compute_json_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth=DEFAULT_MAX_DEPTH,
num_leaves=DEFAULT_NUM_LEAVES,
min_child_sample... | return compute_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth,
num_leaves,
min_child_samples)
| def compute_json_error_tree(analyzer,
features,
filters,
composite_filters,
max_depth=DEFAULT_MAX_DEPTH,
num_leaves=DEFAULT_NUM_LEAVES,
min_child_sample... | 71 | 64 | 103 | 71 | 0 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | compute_json_error_tree | compute_json_error_tree | 46 | 61 | 46 | 54 | 5d7374c2668577dd930c3473eb2df31513f2af36 | bigcode/the-stack | train |
f1e0b531bab5db7e2ad6a657 | train | function | def get_classification_metric_data(df):
pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
error = df[DIFF].values.sum()
return pred_y, true_y, error
| def get_classification_metric_data(df):
| pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
error = df[DIFF].values.sum()
return pred_y, true_y, error
| def get_regression_metric_data(df):
pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
# total abs error at the node
error = sum(abs(pred_y - true_y))
return pred_y, true_y, error
def get_classification_metric_data(df):
| 64 | 64 | 47 | 8 | 55 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | get_classification_metric_data | get_classification_metric_data | 434 | 438 | 434 | 434 | db3e502e5c4add19c20521afd703f046be85c42d | bigcode/the-stack | train |
06f9f2cfd3058aa9f8c5c469 | train | function | def get_regression_metric_data(df):
pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
# total abs error at the node
error = sum(abs(pred_y - true_y))
return pred_y, true_y, error
| def get_regression_metric_data(df):
| pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
# total abs error at the node
error = sum(abs(pred_y - true_y))
return pred_y, true_y, error
| Note: remove this eventually
"success": float(success), # Note: remove this eventually
"metricName": metric_name,
"metricValue": float(metric_value),
"isErrorMetric": is_error_metric
})
return json, df
def get_regression_metric_data(df):
| 64 | 64 | 56 | 8 | 55 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | get_regression_metric_data | get_regression_metric_data | 426 | 431 | 426 | 426 | f1f3eb3aa64ad57a4fbffaf0dd91b364e75d15ca | bigcode/the-stack | train |
275ae6208fe57c85faac78b8 | train | function | def create_categorical_arg(parent_threshold):
return [float(i) for i in parent_threshold.split('||')]
| def create_categorical_arg(parent_threshold):
| return [float(i) for i in parent_threshold.split('||')]
| dict, feature_names,
tree, TreeSide.LEFT_CHILD, metric,
classes)
dict = traverse(df, right_child, max_split_index,
categories, dict, feature_names,
tree, TreeSide.RIGHT_CHILD, metric,
classes... | 64 | 64 | 23 | 8 | 55 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | create_categorical_arg | create_categorical_arg | 274 | 275 | 274 | 274 | c54d062400947b2c5423eec120d25fd9d8666b1c | bigcode/the-stack | train |
cb4fa18ee1116fcd99ee95eb | train | function | def compute_metric_value(func, classes, true_y, pred_y, metric):
requires_pos_label = (metric == Metrics.RECALL_SCORE or
metric == Metrics.PRECISION_SCORE or
metric == Metrics.F1_SCORE)
if requires_pos_label:
ordered_labels = get_ordered_classes(classe... | def compute_metric_value(func, classes, true_y, pred_y, metric):
| requires_pos_label = (metric == Metrics.RECALL_SCORE or
metric == Metrics.PRECISION_SCORE or
metric == Metrics.F1_SCORE)
if requires_pos_label:
ordered_labels = get_ordered_classes(classes, true_y, pred_y)
if ordered_labels is not None and len(... |
def get_classification_metric_data(df):
pred_y = df[PRED_Y]
true_y = df[TRUE_Y]
error = df[DIFF].values.sum()
return pred_y, true_y, error
def compute_metric_value(func, classes, true_y, pred_y, metric):
| 64 | 64 | 113 | 16 | 47 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | compute_metric_value | compute_metric_value | 441 | 449 | 441 | 441 | 90097c2c50d906cfa0bafc07e63d3ed64fadcb95 | bigcode/the-stack | train |
9a4ec7aa4f63ff37c5054375 | train | function | def traverse(df,
tree,
max_split_index,
categories,
dict,
feature_names,
parent=None,
side=TreeSide.UNKNOWN,
metric=None,
classes=None):
if SPLIT_INDEX in tree:
nodeid = tree[SPLIT_INDEX]
... | def traverse(df,
tree,
max_split_index,
categories,
dict,
feature_names,
parent=None,
side=TreeSide.UNKNOWN,
metric=None,
classes=None):
| if SPLIT_INDEX in tree:
nodeid = tree[SPLIT_INDEX]
elif LEAF_INDEX in tree:
nodeid = max_split_index + tree[LEAF_INDEX]
else:
nodeid = 0
# write current node to a dictionary that can be saved as json
dict, df = node_to_dict(df, tree, nodeid, categories, dict,
... | index2 = get_max_split_index(tree[TreeSide.RIGHT_CHILD])
return max(max(max_index, index1), index2)
else:
return 0
def traverse(df,
tree,
max_split_index,
categories,
dict,
feature_names,
parent=None,
side=Tr... | 76 | 76 | 256 | 41 | 34 | jplummer01/responsible-ai-toolbox | erroranalysis/erroranalysis/_internal/surrogate_error_tree.py | Python | traverse | traverse | 237 | 271 | 237 | 246 | 6a45739f2db5cdb93a3e08719cfbd5069f754dc0 | bigcode/the-stack | train |
09cf3ebd363377bbb628e77a | train | function | def online_predict(mean_file,model_def_file,model_file,classes_file,num_categories):
# caffe init
gpu_id = 0
caffe.set_device(gpu_id)
caffe.set_mode_gpu()
frame_counter = 0
index_to_label = {}
#sampling scheme
algo = [[16],[8,8],[4,4,8],[2,2,4,8],[1,1,2,4,8]]
w... | def online_predict(mean_file,model_def_file,model_file,classes_file,num_categories):
# caffe init
| gpu_id = 0
caffe.set_device(gpu_id)
caffe.set_mode_gpu()
frame_counter = 0
index_to_label = {}
#sampling scheme
algo = [[16],[8,8],[4,4,8],[2,2,4,8],[1,1,2,4,8]]
with open(classes_file,"r") as file:
for line in file:
index, label = line.strip().split(... | """script for predicting labels from live feed"""
import numpy as np
import caffe
import cv2
import math
import scipy.io as sio
import time
import random
import itertools
batch_size = 16 #number of samples per video
def online_predict(mean_file,model_def_file,model_file,classes_file,num_categories):
# c... | 74 | 247 | 824 | 23 | 50 | WingsBrokenAngel/ECO-efficient-video-understanding | scripts/online_recognition/online_recognition.py | Python | online_predict | online_predict | 13 | 108 | 13 | 14 | 847ea7237e8ce476f2ef33f51a0589eb59f8205e | bigcode/the-stack | train |
b358fa33ceee0acaea86c42c | train | function | def add_colorbar(ax, im, **kwargs):
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cb = plt.colorbar(im, cax=cax, **kwargs)
return cb
| def add_colorbar(ax, im, **kwargs):
| divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cb = plt.colorbar(im, cax=cax, **kwargs)
return cb
| for tick in chain(ax.xaxis.get_major_ticks(), ax.yaxis.get_major_ticks()):
tick.label.set_fontsize(12)
tick.label.set_fontsize(12)
fig.tight_layout()
fig.savefig(path)
return fig, axs
def add_colorbar(ax, im, **kwargs):
| 64 | 64 | 60 | 11 | 52 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | add_colorbar | add_colorbar | 61 | 65 | 61 | 61 | 8651c6c11f17b56c9366a70629f9853909ecadfa | bigcode/the-stack | train |
4e07683e6ec135433f5a795e | train | function | def remove_tick_labels(ax):
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % 2 == 0:
label.set_visible(False)
for n, label in enumerate(ax.yaxis.get_ticklabels()):
if n % 2 == 0:
label.set_visible(False)
| def remove_tick_labels(ax):
| for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % 2 == 0:
label.set_visible(False)
for n, label in enumerate(ax.yaxis.get_ticklabels()):
if n % 2 == 0:
label.set_visible(False)
| 42
plt.rc('font', family='serif', serif='Times')
COLUMN_WIDTH = 3.487
HEIGHT = COLUMN_WIDTH / 1.618
WORKSPACE = ((0.3, -0.2), (0.7, 0.2))
def remove_tick_labels(ax):
| 64 | 64 | 66 | 6 | 58 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | remove_tick_labels | remove_tick_labels | 27 | 34 | 27 | 27 | 4cf915c5f1f861dfc21f8f17173620ba18407eea | bigcode/the-stack | train |
1997c84ccc737018f4d294be | train | function | def plot_src_tgt_config(src_aabbs=None,
tgt_aabbs=None,
radius=0.055,
path='figures/configs.pdf'):
width = COLUMN_WIDTH * 2
height = COLUMN_WIDTH
fig, axs = plt.subplots(1, 2, figsize=(width, height))
for ax, aabbs, title in zip(ax... | def plot_src_tgt_config(src_aabbs=None,
tgt_aabbs=None,
radius=0.055,
path='figures/configs.pdf'):
| width = COLUMN_WIDTH * 2
height = COLUMN_WIDTH
fig, axs = plt.subplots(1, 2, figsize=(width, height))
for ax, aabbs, title in zip(axs, (src_aabbs, tgt_aabbs), ('Source', 'Target')):
plot_gt_objects(ax, aabbs, plot_center=False, target_box=False,
alpha=1.0, collision_alph... | (False)
for n, label in enumerate(ax.yaxis.get_ticklabels()):
if n % 2 == 0:
label.set_visible(False)
def plot_src_tgt_config(src_aabbs=None,
tgt_aabbs=None,
radius=0.055,
path='figures/configs.pdf'):
| 67 | 67 | 224 | 35 | 32 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | plot_src_tgt_config | plot_src_tgt_config | 37 | 58 | 37 | 40 | 23899d6e3b8bb7c9554c4592b965d4b94af9ccd9 | bigcode/the-stack | train |
b4c96a1abad18a3a421ff64d | train | function | def save_train_test_images(synth_ids,
real_ids,
save_dir='figures'):
scene_ds = LMDBDataset(Path('../../data/datasets/') / 'synthetic-shapes-1to6')
width = COLUMN_WIDTH * 5
height = width * 3 / 4 * 2 / 3
n_rows, n_cols = 2, 3
fig, axs = plt.subp... | def save_train_test_images(synth_ids,
real_ids,
save_dir='figures'):
| scene_ds = LMDBDataset(Path('../../data/datasets/') / 'synthetic-shapes-1to6')
width = COLUMN_WIDTH * 5
height = width * 3 / 4 * 2 / 3
n_rows, n_cols = 2, 3
fig, axs = plt.subplots(n_rows, n_cols, figsize=(width, height))
fig.subplots_adjust(wspace=0.0, hspace=0.0)
for ax, synth_id in zip(a... | ax, patch, color in zip(axs.flatten(), patches, sns.color_palette()):
ax.imshow(patch.permute(1, 2, 0))
ax.add_artist(plt.Rectangle((0, 0), 62, 62, color=color, fill=False, linewidth=6))
ax.axis('off')
fig.savefig(save_dir / f'example_patches.pdf', bbox_inches='tight')
def save_train_test_i... | 106 | 106 | 356 | 20 | 86 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | save_train_test_images | save_train_test_images | 173 | 202 | 173 | 175 | c8a64f85cc40ad59169c6aceab9f9340e8621d7b | bigcode/the-stack | train |
ed71664b7cca684787248531 | train | function | def plot_vision_eval(summary, path='figures/plot_variable_n_objects.pdf'):
width = COLUMN_WIDTH * 4
height = width / 2
n_rows, n_cols = 1, 2
fig, axs = plt.subplots(n_rows, n_cols, figsize=(width, height))
n_objects = np.array(range(1, 13))
succ = np.array([summary['identification_success_n_obj... | def plot_vision_eval(summary, path='figures/plot_variable_n_objects.pdf'):
| width = COLUMN_WIDTH * 4
height = width / 2
n_rows, n_cols = 1, 2
fig, axs = plt.subplots(n_rows, n_cols, figsize=(width, height))
n_objects = np.array(range(1, 13))
succ = np.array([summary['identification_success_n_objects'][n] for n in n_objects])
# axs[0].grid()
for (th, values), co... | 1, 4
fig, axs = plt.subplots(n_rows, n_cols, figsize=(width, height))
fig.subplots_adjust(wspace=0.0, hspace=0.0)
for ax, real_id in zip(axs.flatten(), real_ids):
rgb = scene_ds[real_id][0][..., :3]
ax.imshow(rgb)
ax.axis('off')
save_dir = Path(save_dir)
fig.savefig(save_dir ... | 128 | 128 | 427 | 19 | 109 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | plot_vision_eval | plot_vision_eval | 205 | 237 | 205 | 206 | e7d498617ebd08c4fb43cf719e42dd3daa9f9115 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.